Home / Insights / AI Agents and Automation

AI Agents and Automation

Deploying AI Agents Securely: Sandboxes, Credentials and Network Boundaries

Most writing about agent security covers prompt injection and permissions. This guide covers the layer underneath: where the agent runs, what credentials it holds, what networks it can reach and how you contain the damage when the model is tricked. It is written for the architects and platform teams who have to deploy agents, not just design them.

TopicsAI Agents and AutomationArchitecture and Modernization

Key takeaways

  • Assume the model will sometimes follow malicious instructions. Security has to come from the runtime around it: sandboxes, credentials, network rules and logging that limit what a misled agent can actually do.
  • Run anything the agent executes (code, shell commands, browsers, untrusted tool servers) in an isolated sandbox with no standing credentials, a read-mostly filesystem and an egress allowlist.
  • Agents should never hold long-lived secrets. Issue short-lived, narrowly scoped credentials per task through a broker, and keep the user’s identity attached to every downstream call.
  • Network boundaries are the cheapest and most reliable control: block private ranges and cloud metadata endpoints, allowlist destinations, and route all outbound traffic through a proxy that logs it.
  • Treat MCP and other tool servers as part of your attack surface. Apply the protocol’s own security guidance on token handling, session IDs and local server execution, and pin and review every server you connect.

An AI agent is a program that reads untrusted text and then takes actions with real credentials. That combination is unusual in software, and it is why conventional application security is necessary but not sufficient. A web application processes attacker-controlled input too, but it does not decide for itself which API to call next based on that input. An agent does. Prompt injection is not a bug you patch once; it is a property of current models you design around.

This guide is for CTOs, platform engineers and security leads who are moving agents from prototype to production. It does not repeat the permission design and approval patterns we covered in our article on AI agent permissions and approvals, or the input-side defences in prompt injection in agentic systems. Instead it covers the deployment layer: execution sandboxes, credential handling, network boundaries, tool server hardening and the operational controls that make an incident containable. It reflects how we build in our AI agent development work, where each tool has typed inputs, validation and permission checks, write actions usually require human approval, and every action is logged.

What are you actually defending against?

Before choosing controls, it helps to be explicit about the failure modes. For a deployed agent, the practical threat model has four parts.

The four things that go wrong

  1. The model is manipulated. Content the agent reads (a support ticket, a web page, a file in a repository, a tool result) contains instructions, and the model acts on them. The OWASP Top 10 for LLM Applications lists prompt injection as LLM01 and excessive agency, where systems are given more autonomy or permission than they need, as LLM06.
  2. The model is wrong. No manipulation is needed: the agent misreads a situation and deletes, sends or changes the wrong thing. Autonomy compounds errors, as Anthropic’s guidance on building effective agents notes, which is why it recommends extensive sandboxed testing and guardrails.
  3. A tool or dependency is compromised. A third-party tool server, package or model endpoint behaves maliciously or leaks data. OWASP lists supply chain risks as LLM03.
  4. Secrets leak. Credentials end up in prompts, logs, tool outputs or model context, and are then exposed through sensitive information disclosure (LLM02) or system prompt leakage (LLM07).

The design consequence

You cannot make the model reliably ignore injected instructions, so deployment security aims to keep the blast radius small, the action visible and recovery quick.

AimPrimary controls
Small blast radiusSandboxed execution, least-privilege and short-lived credentials, egress allowlists, approval gates for writes
VisibilityStructured action logs, proxy logs, tool-call tracing, alerts on unusual destinations or volumes
Quick recoveryRevocable credentials, reversible actions where possible, kill switches, replayable logs

Action: write down, for each agent, what the worst plausible action is if the model follows an attacker’s instructions with the permissions it currently holds. If the answer is unacceptable, the fix is in the runtime, not the prompt.

Where should the agent run, and what should the sandbox look like?

Agents execute code, run commands, drive browsers and process files, each a route from bad model output to something happening on a machine, so the execution environment needs stronger isolation than a typical application container.

Separate the orchestrator from the execution environment

Split the agent in two: an orchestrator that talks to the model, holds state and chooses tools, and a disposable execution environment where risky work happens. The execution environment holds no credentials beyond what the orchestrator hands it for a single task.

Isolation options compared

OptionIsolation strengthStart-up and costGood fitCaveats
Plain container with hardening (non-root, read-only root filesystem, dropped capabilities, seccomp profile)Moderate; shares the host kernelFast, cheapTrusted code paths, light file processingKernel vulnerabilities and misconfigurations can allow escape
Application-kernel sandbox such as gVisorStrong; system calls are intercepted by a userspace kernelFast start, modest overheadRunning model-generated code and untrusted toolsgVisor’s documentation notes reduced compatibility and higher per-system-call overhead, so syscall-heavy workloads may be slow
Micro-VM or full VM per taskStrongest; separate kernelSlower to start, higher costLong-running coding agents, browser automation, multi-tenant platformsNeeds orchestration for lifecycle and snapshots
Managed code-execution service from a cloud or model providerDepends on providerOperationally simpleTeams without platform capacityCheck data residency, network controls and what the provider logs

Sandbox baseline, whichever option you choose

  • Non-root user, read-only root filesystem, a single writable scratch directory that is wiped after the task.
  • No secrets in environment variables or files. Credentials arrive per call through the orchestrator (see the next section).
  • No access to the host’s Docker socket, cloud instance metadata or shared volumes.
  • CPU, memory, disk and wall-clock limits per task, so an agent in a loop cannot exhaust resources. OWASP calls the general problem unbounded consumption (LLM10).
  • Outbound network denied by default, with an allowlist enforced outside the sandbox.
  • Ephemeral by default: destroy after the task; persist only explicit outputs through a controlled channel.

Illustrative example: a 40-person SaaS company deploying an internal coding agent might run a gVisor-backed container per task with a repository clone, a scratch directory and no credentials; the orchestrator commits results under its own identity after tests pass and a human reviews the diff.

How should agents handle credentials?

Credential handling is where most agent deployments are weakest, because prototypes start with an API key in an environment variable and nobody revisits it. In production, the rule is simple: the model, and the sandbox it drives, should never hold a long-lived secret.

Principles

  • Broker, do not embed. Put a credential broker between the orchestrator and downstream systems. The orchestrator asks for a token for a specific tool, scope and user; the broker issues a short-lived token; the token is used and expires.
  • Keep the human’s identity attached. Downstream calls should run as the user who asked for the task (or a clearly labelled service identity acting on their behalf), so that existing authorisation rules apply and audit logs show who was really behind the action. Retrieval should be limited to what that user may see.
  • Scope narrowly and elevate progressively. Start with read-only or discovery scopes and request elevation only when a privileged action is attempted. The MCP security best practices describe exactly this progressive, least-privilege scope model and warn against wildcard or omnibus scopes that expand the blast radius of a stolen token.
  • Never pass tokens through. The same MCP guidance forbids “token passthrough”, where a server accepts a token not issued to it and forwards it downstream, because it circumvents controls and breaks audit trails. The principle applies to any tool layer you build: each hop validates that the token was meant for it.
  • Keep secrets out of the model’s context. Tool results that contain credentials, connection strings or personal data should be redacted before they are returned to the model. Anything the model sees can end up in a log, a summary or an attacker’s exfiltration attempt.

A credential flow that works

  1. User triggers a task; the orchestrator records the user identity and task ID.
  2. The model requests a tool call; the orchestrator validates the arguments against the tool’s schema and policy.
  3. If the action is a write or otherwise sensitive, the orchestrator routes it to a human approval step with full context.
  4. The orchestrator requests a token from the broker for that tool, scope, user and task, with a lifetime measured in minutes.
  5. The call is made from the orchestrator or a dedicated tool service, not from inside the model’s sandbox, and the result is redacted before it returns to the model.
  6. The token expires; the action, arguments, result summary, user, task and model version are logged.

What network boundaries should agents have?

Network controls are the most dependable layer because they do not rely on the model’s behaviour at all. If the agent cannot reach a destination, no amount of clever injection will get data there.

Egress rules

  • Deny by default, allowlist by destination. The sandbox and tool services should reach only the hosts they need: your APIs, approved SaaS endpoints, the model provider and package mirrors you control.
  • Route everything through a logging proxy. An egress proxy gives you an enforcement point and a record of every destination, which is invaluable in an incident and for spotting exfiltration attempts.
  • Block private and link-local ranges. The MCP security guidance highlights server-side request forgery (SSRF), where a malicious server supplies URLs pointing at internal services or cloud metadata endpoints such as 169.254.169.254, and recommends blocking private IPv4 and IPv6 ranges and link-local addresses, enforcing HTTPS and validating redirect targets. It also warns against hand-rolled IP validation because of encoding tricks, and suggests egress proxies that prevent SSRF by design.

Ingress and lateral movement

Sandboxes accept no inbound connections except from the orchestrator; tool services sit in their own segments with access only to the systems they wrap; and agent web browsing gets its own sandbox and proxy policy, since pages are the most common carrier of injected instructions.

Who can reach whom

FromToAllowed?
OrchestratorModel provider, credential broker, tool services, loggingYes, over TLS with service identity
Execution sandboxAllowlisted hosts via egress proxyYes, logged
Execution sandboxInternal networks, metadata endpoints, other sandboxesNo
Tool serviceThe specific system it wrapsYes, with per-call short-lived credentials
InternetSandbox or tool serviceNo inbound

Action: export one week of outbound connections from your agent environment and compare them with the allowlist you think you have. The gap is usually instructive.

How do you harden MCP and other tool servers?

Tool servers, including those built on the Model Context Protocol (MCP), are the hands of the agent. They are also a supply-chain and authorisation surface in their own right. The MCP specification’s security best practices document is worth reading in full; the points below are the ones that most often bite in deployment.

Treat every tool server as code you run

  • Pin versions and review the source or provenance of any third-party server before connecting it. A server can rewrite its tool descriptions at any time, and those descriptions go straight into the model’s context.
  • Run local servers in the same sandbox regime as other untrusted code. The MCP guidance describes how a malicious startup command in a client configuration can exfiltrate data or escalate privileges, and recommends showing the full command, requiring explicit consent and executing servers with minimal privileges.
  • Prefer the stdio transport for local servers, or restrict HTTP transports with authorisation tokens or local sockets, so other processes on the machine cannot drive them.

Get the authorisation details right

  • Servers must verify every inbound request and must not use session IDs for authentication. Session IDs should be non-deterministic and bound to the user, which prevents the session hijacking and event-injection attacks the specification describes for multi-server deployments.
  • Proxy servers that connect to third-party APIs must implement per-client consent to avoid the confused deputy problem, where a cached consent cookie lets an attacker obtain tokens without the user’s approval.
  • Validate authorisation URLs strictly: only https (and loopback http in development), never javascript: or file: schemes, and never opened through a shell.

Design tools so mistakes are hard

Anthropic recommends investing in the agent-computer interface as much as a human interface: clear descriptions, explicit boundaries between similar tools, and “poka-yoke” designs that make errors structurally difficult. Add typed, validated arguments, separate read and write tools, idempotent writes and hard batch limits so one misguided call cannot delete ten thousand records. For interoperability questions, see our guide to agent interoperability standards.

Logging, monitoring and incident response for agents

Without good logs you cannot tell whether a surprising action was a bug, an injection or a reasonable decision based on information you did not see.

What to log

  • Every tool call: tool name, validated arguments (with secrets and personal data redacted), result summary, duration, task ID, user identity, model and prompt version.
  • Every approval request and decision, with who approved and what they saw.
  • Every outbound connection from sandboxes and tool services, via the egress proxy.

What to alert on

  • Connections to destinations not on the allowlist, or unusual volumes to allowed ones.
  • Tool calls outside the expected pattern for a task type (for example a summarisation agent attempting a write).
  • Step counts, token usage or cost per task above thresholds.

Incident playbook essentials

  1. Pause the agent: a kill switch that stops new tasks and halts in-flight ones at the next tool boundary.
  2. Revoke credentials issued to the affected agent, user or tool.
  3. Reconstruct the sequence from logs: inputs, context, decisions, actions.
  4. Reverse or remediate actions, which is far easier if writes were designed to be reversible or staged.
  5. Add the injection source or failure pattern to your evaluation suite so it is tested before every release; our article on testing AI agents before release covers scenario suites and tool mocks.

A staged path to production

Agents earn autonomy; they should not start with it. A staged rollout lets you build the controls above while the agent proves itself on low-risk work.

StageScopeControls that must be in placeExit criteria
1. Read-only assistantRetrieves, summarises, drafts; no writesSandbox baseline, egress allowlist, identity-scoped retrieval, loggingEvaluation suite passes; no unexpected destinations in proxy logs
2. Proposes actionsPrepares writes for human approvalApproval workflow, credential broker, redaction of tool resultsApproval rejection rate understood; reversible write paths designed
3. Executes low-risk writesNarrow, reversible, rate-limited actionsShort-lived scoped tokens, batch limits, alerts, kill switchIncident drill completed; recovery time acceptable
4. Broader autonomyMulti-step tasks across systemsEverything above plus per-tool network segmentation and regular red-team exercisesReviewed quarterly against new threats and model changes

Each stage adds platform work (brokers, proxies, sandboxes) that is cheaper to build once as a shared agent runtime than to retrofit per agent.

Go-live checklist for a production agent

Use this as a gate review with engineering, security and the business owner of the agent.

  1. Worst-case action under manipulation documented and judged acceptable given current permissions.
  2. Orchestrator and execution environment separated; sandboxes are ephemeral, non-root, read-only and resource-limited.
  3. No long-lived secrets in sandboxes, environment variables or prompts; a credential broker issues short-lived, narrowly scoped tokens per task.
  4. User identity attached to downstream calls; retrieval limited to what the user may access.
  5. Token passthrough prohibited; each tool layer validates tokens issued to it.
  6. Egress denied by default; allowlist enforced by a logging proxy; private, loopback and link-local ranges blocked; redirects validated.
  7. Third-party tool servers pinned, reviewed and run with minimal privileges; local servers use stdio or restricted transports.
  8. Write actions require approval or are reversible, rate-limited and batch-capped.
  9. Structured logs for tool calls, approvals, credentials and connections; alerts configured for unusual destinations, actions and spend.
  10. Kill switch and credential revocation tested; incident playbook rehearsed.
  11. Evaluation suite includes known injection patterns and runs before every release.

Frequently asked questions

Can we just give the agent a service account with the permissions it needs?

A static service account with broad permissions is the pattern most likely to turn a prompt injection into a serious incident. Prefer a credential broker that issues short-lived, task-scoped tokens, and keep the requesting user’s identity attached so existing authorisation and audit apply.

How do we stop an agent exfiltrating data through a web request?

Network controls: deny outbound by default, allowlist destinations, route traffic through a logging egress proxy, and block private and link-local ranges including cloud metadata endpoints. Combined with redaction of sensitive tool results before they reach the model, this removes most practical exfiltration paths.

Are MCP servers safe to use?

MCP is a protocol, and its specification includes detailed security best practices on token handling, session IDs, SSRF and local server execution. The risk lies in the servers you connect. Treat each as code you run: pin versions, review provenance, run local servers sandboxed with minimal privileges, and follow the specification’s authorisation guidance.

How much does this security layer add to an agent project?

It depends on what platform capabilities you already have. Teams with an existing secrets manager, identity provider, egress proxy and container platform can assemble an agent runtime relatively quickly; teams without them should budget for building these once and reusing them. The cost of retrofitting after an incident is far higher.

Sources and methodology

Guidance reflects PoliteTech delivery experience. The external references below informed specific points in this article.

  1. OWASP: Top 10 for LLM Applications 2025 — accessed 10 November 2026. Risk categories referenced: prompt injection, sensitive information disclosure, supply chain, excessive agency, system prompt leakage and unbounded consumption.
  2. Model Context Protocol specification: Security Best Practices — accessed 10 November 2026. Confused deputy and per-client consent, token passthrough prohibition, SSRF mitigations (private range blocking, HTTPS, redirect validation, egress proxies), session ID requirements, local server consent and sandboxing, authorisation URL validation and scope minimisation.
  3. gVisor documentation: What is gVisor? — accessed 10 November 2026. Application-kernel sandboxing model, syscall interception, OCI runtime compatibility and the trade-offs of reduced compatibility and per-syscall overhead.
  4. Anthropic: Building effective agents (December 2024) — accessed 10 November 2026. Workflows versus agents, compounding errors and cost of autonomy, sandboxed testing and guardrails, human checkpoints and stopping conditions, agent-computer interface design including poka-yoke tools.

Moving an AI agent from prototype to production and unsure the runtime is safe?

We can review your agent architecture, design the sandbox, credential and network controls, and build the tool layer with approvals and logging built in.