MCP Security: Risks and Best Practices for AI Agents

By Jesse Sumrak

  • Updated:
  • 18 min read

Model Context Protocol (MCP) adoption is outpacing the safeguards around it. Anthropic counted more than 10,000 active public MCP servers by December 2025. The National Security Agency’s (NSA) May 2026 MCP guidance warns that “MCP’s rapid proliferation has outpaced the development of its security model.”

These gaps aren’t just theoretical, either. In March 2026, a security researcher found that nginx-ui (an open-source web interface for managing Nginx servers) protected its main MCP endpoint but left the endpoint that handles every tool call open by default. This meant anyone who could reach one of roughly 2,600 exposed instances could rewrite the server’s configuration.

That’s why MCP security (aka Model Context Protocol security), now matters for AI agents in production. The agent decides at runtime which tools to call, with whose credentials, and where the results go, but the protocol leaves most guardrails (from authentication to approvals) to whoever deploys it. Let’s break down real MCP security incidents and how to enforce the controls that contain them, including with DigitalOcean.

Key takeaways:

  • MCP security covers what an AI agent can reach through MCP servers, which credentials it uses, where its data can go, and who approves its actions.
  • The incidents and research in this MCP security guide map to six recurring risks, from prompt injection and tool poisoning to open network egress and missing approval gates.
  • No control stops prompt injection outright, so MCP security best practices limit the damage with least privilege, approval rules, brokered credentials, isolated runtimes, and egress allowlists.
  • DigitalOcean Managed Agents makes it possible for teams to build agents with these controls in place: Action Gateway governs which tools an agent can call, and Harness Runtime isolates where it runs.

What is MCP security?

MCP security is the set of practices that protect AI agents, MCP clients, and MCP servers. It applies whenever an agent finds and calls external tools through MCP. It covers who can connect to a server, what each tool is allowed to do, how credentials are handled, where data can travel, and how tool calls are approved and logged.

How MCP expands the attack surface for AI agents

MCP standardizes how AI applications connect to outside tools. A host application, such as an integrated development environment (IDE), runs one MCP client for each MCP server it connects to, and each server exposes tools the model can call.

That flexibility introduces new security risks:

  1. The agent chooses the call: A traditional API client runs calls that a developer wrote and reviewed. An agent picks tools at runtime, so an attacker can plant instructions in content the agent reads, like a GitHub issue, and steer which tool it calls and with what arguments.
  2. Tools act with real privileges: The MCP specification warns that “Tools represent arbitrary code execution and must be treated with appropriate caution.” A local MCP server, which usually runs over standard input/output (stdio), launches with your user account’s permissions. That means it can read your files and run commands as you.
  3. Security is mostly opt-in: The current spec on November 3, 2026 states, “Authorization is OPTIONAL for MCP implementations,” leaving authentication and scoping to whoever deploys the server.

The MCP project’s security best practices cover protocol-level risks in depth, and the NSA advises that “Adopters should therefore proceed with caution.”

Leading MCP security risks

The incidents below map to the top recurring MCP security risks, and many of them involve more than one risk at once.

Note: Some of these incidents involve researcher demonstrations rather than real-world breaches.

Prompt injection and tool poisoning

Prompt injection occurs when an agent treats the text it reads (e.g., issues, emails, or error logs) as instructions. Tool poisoning hides those malicious instructions in a tool’s description, which the model reads in full but users typically see only in summary.

In a rug pull, a server looks harmless when you approve it, but then sneakily swaps in a malicious tool description later. Most clients don’t ask for approval again, so the agent follows the new instructions. Invariant Labs showed this with a “fact of the day” server that, once approved, rewrote its description to hijack a WhatsApp tool and send the user’s chat history to an attacker.

Invariant Labs named and demonstrated tool poisoning in April 2025, then showed how a malicious issue on a public GitHub repository could steer an agent using the official GitHub MCP server into leaking private repository data through a public pull request.

Implement these controls to limit prompt injection and tool poisoning (the MCP security best practices section below covers each one in depth):

  • Least privilege
  • Approval rules on write actions
  • Egress limits
  • LLM guardrails (help, but aren’t enough on their own)

Curious how these risks compound together? Our breakdown of agentic tooling shows the problems and how DigitalOcean Action Gateway can address them.

Over-permissioned tools and the confused deputy problem

A confused deputy is a program tricked into using its own broad privileges on behalf of someone with fewer. MCP servers tend to fall into that role because they connect with one powerful credential, then serve whatever the agent asks for.

In July 2025, General Analysis showed how a support ticket with hidden instructions could lead Cursor, connected to Supabase’s MCP server with the all-access service_role key, to post a private table of integration tokens back into the ticket. Supabase disputed parts of the write-up but documented read-only mode and project scoping, and advised: “Never connect AI agents directly to production data.”

In June 2025, Asana disclosed a real incident - a logic bug in its MCP server could have exposed some customers’ data to other organizations.

Implement these controls to limit what an over-permissioned tool can do:

  • Least privilege at the provider and the tool
  • Allow, ask, and deny rules

Credential and token exposure

MCP servers need credentials, and those often sit where an agent or attacker can read them. Astrix Security’s review of 5,205 open-source MCP servers found that 53% rely on static API keys or personal access tokens, and only 8.5% use OAuth.

Anything an agent can read, a prompt injection can ask it to print or send elsewhere. Static keys are usually stored in plaintext config files or environment variables. Astrix found that 79% of API keys are exposed via environment variables, which the agent and any process it starts can read. Invariant’s tool-poisoning demo exploited this vulnerability by instructing the model to retrieve the user’s MCP config file and SSH key. And because static keys rarely expire, one that has leaked continues to work until someone rotates it.

GitGuardian found a path traversal bug in Smithery.ai (an MCP server host) that exposed a Fly.​io token with access to 3,243 apps. Smithery fixed it within two days, with no evidence of exploitation. The spec also bans token passthrough: “MCP servers MUST NOT accept any tokens that were not explicitly issued for the MCP server.”

Implement these controls to keep credentials and tokens out of reach:

  • Keep credentials out of the model and the sandbox
  • Scope every token to one server

Untrusted third-party MCP servers

Installing an MCP server means running someone else’s code with access to your data. That’s why MCP server security needs to start before installation. Koi Security called postmark-mcp the first malicious MCP server found in the wild. The npm package impersonated the email provider Postmark, built trust over 15 versions, then added a backdoor in version 1.0.16 that secretly copied outgoing emails to an attacker’s address.

Registries don’t offer reliable screening. In February 2026, Straiker found the SmartLoader malware group cloning a legitimate Oura Ring MCP server. It used fake GitHub accounts and forks to look legitimate and listed it on an MCP registry to spread malware that steals passwords and keys. OX Security reported that 9 of 11 MCP registries accepted its poisoned test package.

Implement these controls before you trust a third-party server:

  • Vet and pin third-party servers
  • Isolate where third-party servers run
  • Restrict egress

Open network egress and data exfiltration

Egress is outbound network traffic, and an agent that can reach any host can send anything it reads to anyone. Simon Willison calls the combination of private data, untrusted content, and an outbound channel the lethal trifecta.

The good news? If you remove any one of the three, that exfiltration path closes.

Open egress also enables server-side request forgery (SSRF), where an attacker tricks software into calling internal addresses. MCP security best practices involve telling clients to block private IP addresses (such as a cloud metadata endpoint that can hand out credentials) when they fetch sign-in URLs. Apply the same rule to your agent’s outbound traffic.

Implement these controls to block exfiltration paths:

  • Restrict network egress
  • Log every tool call

Want a clear record of every tool call your agents make? Our guide to the best LLM observability tools covers the top platforms for tracing agent runs, running evals, and tracking latency.

Missing authentication, approval gates, and audit trails

In July 2025, Knostic found 1,862 MCP servers exposed to the internet, and all 119 hand-checked servers listed their tools without asking for authentication. By April 2026, TrendAI found that the number of exposed MCP servers had nearly tripled, from 492 to 1,467.

Then, there are approvals, and they tend to fail without anyone even noticing. Invariant Labs noted that many users switch to an “Always Allow” policy and stop reviewing individual calls. Cursor’s MCPoison flaw let an attacker swap a malicious command into an MCP config the victim had already approved, with no new prompt.

Implement these controls to close approval and audit gaps:

  • Gate sensitive actions with allow, ask, and deny rules
  • Log every tool call
  • Don’t switch agents to “Always Allow”

Modern threats aren’t limited to MCP. Our guide to AI security covers top risks, including memory poisoning and cascading failures in multi-agent workflows.

MCP security best practices

MCP security best practices work in layers, with each control covering gaps left by the others. Not every risk has a complete fix yet, so each layer should limit what a compromised agent can do.

Apply least privilege at the provider and the tool

Least privilege means giving each agent, token, and tool only the access its task requires. Start by scoping credentials at the source:

  • Limit fine-grained tokens to the repositories or projects a task needs
  • Use read-only database roles for agents that only read
  • Run separate servers for payments or personal data

Next, narrow which tools each session can reach. You want to limit exposure to only the essential requirements. For example, a credential without delete permissions can’t delete anything, no matter how convincing the injected instruction.

Current limitations of this approach: An agent can still misuse access it legitimately has (and needs).

Gate sensitive actions with allow, ask, and deny rules

Auto-approving every call keeps agents moving but removes your last check.

Sort tools by what they can change:

  • Allow read-only calls
  • Require approval (ask) for writes and anything that sends data outside your systems
  • Deny destructive actions
  • Set the default to ask or deny so new tools don’t inherit broad access

The MCP spec states “there SHOULD always be a human in the loop with the ability to deny tool invocations.” Prompts should also show full arguments and reappear when a tool definition changes.

Current limitations of this approach: Approval fatigue. Gate everything, and reviewers start approving on reflex. Gate nothing, and you lose all control.

Keep credentials out of the model and the sandbox

Broker credentials instead of handing them over. For example, a gateway or proxy, like DigitalOcean Action Gateway, attaches the secret when a tool executes, so the model only sees inputs and results. For remote servers, use OAuth 2.1 with resource indicators, as the spec requires, so each token names the server it’s meant for. Always opt for short-lived tokens over static keys to mitigate exposure.

DigitalOcean’s approach to managing credentials for autonomous agents starts from the premise that ‘the agent should never hold the secret in the first place.’ Action Gateway injects credentials per call, so they never enter the model’s context or the sandbox. When an agent needs its own key for a private MCP server or internal API, a scoped secret (still rolling out) binds that key to a single HTTPS host. The sandbox holds only a short-lived handle, which the egress proxy redeems when the agent calls that host.

Current limitations of this approach: A brokered credential still acts on behalf of the agent, so pair brokering with a tool policy.

Isolate where the agent runs

Run agents and local MCP servers in a sandbox, not on a shared machine. The NSA recommends operating system controls that limit what a process can touch, which on Linux means tools like SELinux or AppArmor.

MicroVMs (lightweight virtual machines, each with its own kernel) go further than containers by keeping sessions fully separate. DigitalOcean Harness Runtime gives each agent session its own hardware-isolated microVM sandbox, and it can also run a standalone sandbox with no agent inside for code your app generates. For teams that want the lower-level compute, DigitalOcean MicroVMs (public preview) runs Firecracker-based VMs directly.

Whatever you use, run as a non-root user, keep the filesystem read-only except for a working folder, and never mount host credentials.

Current limitations of this approach: A sandbox protects the host, but it doesn’t protect the network access and credentials you grant the agent.

Restrict network egress

Ultimately, you need a control that breaks the lethal trifecta. If an injected instruction can’t reach an attacker’s server, then it can’t send your data there.

Here’s how to do it:

  • Allowlist the hosts each agent needs and deny everything else
  • Block private IP ranges and the cloud metadata endpoint
  • Route traffic through an egress proxy that logs each request
  • Reach internal systems over a private network

Current limitations of this approach: Allowed destinations, such as an email tool, can still be used to exfiltrate data.

Vet and pin third-party servers

Before you install a server, confirm who publishes it. Install from the vendor’s official GitHub organization or a link in its own docs, check the maintainer’s account age and release history, and skip packages from new accounts, recent forks, or names that imitate a real brand (the tactics behind security risks like postmark-mcp and the SmartLoader clone).

Then read the full tool descriptions the model will see. Don’t be tempted to paste them into an LLM for review. Read them yourself, because the hidden instructions you’re looking for can also steer a model into calling the tool safe. Finally, pin the exact version, so updates can’t change it without your review.

Make a list of approved servers: the OWASP MCP Top 10 (beta project) flags unapproved “shadow” servers. Keep MCP client tools patched. A flaw in the mcp-remote package, CVE-2025-6514, let a malicious server run commands on a user’s machine until version 0.1.16.

Current limitations of this approach: A trusted publisher can still ship a bad release.

Log and review every tool call

The NSA recommends logging “all tool and model invocations” along with “the exact parameters,” then sending those logs to your security information and event management (SIEM) system.

Here’s where to start:

  • Record each call’s arguments, result, identity, and approval decision
  • Alert on writes and new destinations
  • Audit a sample of approvals

Current limitations of this approach: Logs explain an incident after the fact but don’t block anything on their own.

Want to make sure credentials never reach your agent? Our tutorial on credential brokering tests every place a key can hide, from environment variables to logs.

How DigitalOcean helps you build and secure MCP-connected agents

DigitalOcean, the AI-Native Cloud, gives teams the tools to build agents and enforce MCP security controls on the same platform. DigitalOcean Managed Agents, in public preview since September 2026, combines inference, tool access, and agent execution: Action Gateway governs what an agent can call, and Harness Runtime contains where it runs.

Action Gateway: Governed tool access through one MCP endpoint

DigitalOcean Action Gateway (public preview) works as an MCP gateway: a managed layer between agents and the tools they call.

It connects agents to more than 16,000 tools from 500+ providers through one endpoint and handles controls that would otherwise fall to each server:

  • Session tool selection: Calls outside a session’s selected tools are denied, even with an allow rule. Finding a tool through search doesn’t grant permission to run it.
  • Allow, ask, and deny policy: Tool policies allow, require approval for, or block each tool. Deny beats ask at equal specificity, approval can’t override a deny, and an omitted default resolves to ask.
  • Bound approvals: Clients that support MCP elicitation (a spec feature that lets a server pause a call to ask the user for input) show approval requests inline. Each approval is bound to the session, tool version, and arguments.
  • Credentials resolved at execution time: The gateway looks up each provider secret when a tool runs, and as the engineering team’s inside look at Action Gateway puts it, “The model sees the tool result, not the token.” New connections belong to the user who creates them.

Harness Runtime: Isolated execution with permission and egress policy

DigitalOcean Harness Runtime (public preview) runs agents like Claude Code, Codex, and OpenHands in hardware-isolated microVM sandboxes, where the hypervisor keeps each session from reaching another.

Each session’s environment spec sets:

  • Permission policy: Permission rules allow, ask, or deny actions like shell commands and file writes. If the agent’s adapter (the integration for a specific agent, such as Claude Code can’t enforce a strict rule, the session fails at creation.
  • Network egress: Egress is unrestricted until you name an allowed host, which turns on an allowlist that denies everything else. Sandboxes accept no inbound internet connections, and Action Gateway tools need no allowlist entry.
  • Secrets: Secret values stay out of the saved spec and logs, though the agent can read plain secrets inside its sandbox. Scoped secrets, which give the sandbox a short-lived handle instead of the real credential, are rolling out.
  • Audit logs: Each action, its policy decision, who approved it, and the prompt behind it are recorded, and the records don’t expire.

How DigitalOcean security controls map to MCP risks

Together, Action Gateway and Harness Runtime can help protect against each of the major MCP security risks:

MCP risk How DigitalOcean helps
Prompt injection and tool poisoning Session tool selection and ask rules on write tools (Action Gateway)
Over-permissioned tools Per-tool allow, ask, and deny rules that approval can’t override (Action Gateway)
Credential and token exposure Secrets resolved at execution time, outside the model’s context (Action Gateway)
Untrusted third-party servers Tool selection and policy for gateway servers (Action Gateway), plus microVM isolation for code run in the sandbox (Harness Runtime)
Open network egress Opt-in host allowlists and no inbound internet connections (Harness Runtime)
Missing approvals and audit trails Argument-bound approvals (Action Gateway) and audit logs that don’t expire (Harness Runtime)

To understand how these controls work together, read DigitalOcean’s guide to connecting Action Gateway to Harness Runtime. It builds a Claude Code agent that can search the web and read Jira freely, but requires approval to make changes.

It selects eight tools, preloads only the two web tools into the model’s context, and sets this permissions block:

permissions:
  default: ask
  rules:
    - tool: do.actions/exa_web_search
      action: allow
    - tool: do.actions/exa_web_fetch
      action: allow
    - tool: do.actions/jira_list_issues
      action: allow
    - tool: do.actions/jira_get_issue
      action: allow
    - tool: do.actions/jira_create_issue
      action: ask
    - tool: do.actions/jira_update_issue
      action: ask
    - tool: do.actions/jira_add_comment
      action: ask
    - tool: do.actions/jira_transition_issue
      action: ask

Any Jira write pauses for approval, and the guide’s last step rejects a test write to prove the gate works. Approval prompts work on the Claude Code and Codex adapters. For production, we recommend a default of deny with reviewed calls explicitly allowed (Codex falls back to ask, since it doesn’t support a deny default). Gateway tools need no egress allowlist, but any MCP server you connect directly needs its host listed under egress.

Your ongoing responsibility with MCP security

These DigitalOcean tools help enforce MCP security best practices, but a few decisions stay with your team:

  • Provider-side scopes: Our tool policy docs reiterate that “A tool policy does not reduce the scopes of the underlying provider credential,” so grant least privilege when you connect each account.
  • Instructions versus enforcement: Our permission policy docs warn that “An agent can be argued out of an instruction,” so rely on tool selection and policy for anything that matters.
  • The servers you add: Custom MCP servers you connect carry their own supply chain risk.
  • Prompt injection itself: Our guide to OpenClaw security challenges states, “There’s no perfect fix for prompt injection right now…but you can reduce the blast radius by limiting what tools and permissions your agent has access to.”

Ready to try it with your own tools? Our tutorial on connecting AI agents to SaaS tools with Action Gateway walks through completing setup without sharing your credentials.

How to choose an MCP security approach

MCP security works best in layers, because no single tool covers every risk. A layered MCP security architecture combines several of the controls above.

Where to start depends on how your agents use MCP today:

  • If your agents use third-party or community MCP servers, start with a scanner that checks packages and tool descriptions for known flaws and hidden instructions, then pin approved versions.
  • If agents write to production systems or SaaS accounts, put an MCP gateway in front of your servers to enforce tool selection, approval rules, and credential brokering in one place.
  • If many people and agents share the same tools, add an identity layer that associates each tool call with a specific user and agent.
  • If agents run code, install packages, or browse the web, prioritize runtime isolation with an egress allowlist.

If your team wants a gateway and an isolated runtime managed together, use DigitalOcean. Action Gateway rules live in the same environment spec as Harness Runtime’s sandbox and egress settings.

MCP security FAQ

How do you let an AI agent reach a private database without exposing it to the public internet?

Put an MCP server or internal API in front of the database on a private network, give it a read-only database role, and let the agent reach only that service. On DigitalOcean, Action Gateway private connections route tool calls through your Virtual Private Cloud (VPC) to only the hosts and ports you list, in the RIC1 region (Richmond), once DigitalOcean Support enables the feature for your team. Keep firewall rules and service authentication in place, because the gateway’s Code Execution tool keeps public internet access.

How do you give a coding agent scoped access to a cloud account without a full-access API token?

Scope credentials at the source with fine-grained tokens limited to the repositories or projects a task needs, and read-only roles for agents that only read. Then narrow which tools each session can reach, since a credential without delete permissions can’t delete anything. On DigitalOcean, Action Gateway denies calls outside a session’s selected tools, but you still need to grant least privilege on each provider account you connect.

How do you manage secrets and API keys for autonomous agents running in the cloud?

Broker credentials instead of handing them to the agent, so a gateway attaches the secret when a tool runs and the model only sees inputs and results. Prefer short-lived OAuth tokens over static keys, which usually sit in plaintext config files or environment variables that an agent can read. On DigitalOcean, Action Gateway resolves each provider secret at execution time, and Harness Runtime keeps secret values out of saved specs and logs.

How do you run untrusted LLM-generated code in an isolated environment?

Run it in a sandbox instead of on a shared machine, and use microVMs where possible, since each has its own kernel and keeps sessions fully separate. Run as a non-root user, keep the filesystem read-only except for a working folder, and never mount host credentials. A sandbox doesn’t limit the network access you grant, so pair it with an egress allowlist, which DigitalOcean Harness Runtime supports on its microVM sandboxes.

How do you build an audit trail for AI agent actions?

Record each tool call’s arguments, result, identity, and approval decision, and send the logs to your SIEM, as the NSA recommends. Alert on writes and new destinations, and audit a sample of approvals. DigitalOcean Harness Runtime logs each action, its policy decision, who approved it, and the prompt behind it, and those records don’t expire.

Which cloud runs AI coding agents in microVM sandboxes?

DigitalOcean Harness Runtime (public preview) runs agents like Claude Code, Codex, and OpenHands in hardware-isolated microVM sandboxes, where the hypervisor keeps each session from reaching another. Each session’s spec sets permission rules, an optional egress allowlist, and secrets handling, and sandboxes accept no inbound internet connections. Action Gateway adds governed access to more than 16,000 tools from 500+ providers through one endpoint.

Build and secure your agents on DigitalOcean

DigitalOcean Managed Agents gives teams one place to build, run, and govern AI agents, with inference, tool access, and isolated execution on the same platform.

Key features include:

  • One managed MCP endpoint to more than 16,000 tools, with allow, ask, and deny policy per tool
  • Credentials brokered at execution time, so the model never holds the stored secret
  • Hardware-isolated microVM sandboxes with opt-in egress allowlists and audit logs

Get started with DigitalOcean ->

Product information in this article is based on DigitalOcean documentation as of October 30, 2026. Managed Agents, Action Gateway, and Harness Runtime are in public preview, and features and availability may change before general availability. Third-party incident details are based on the linked public disclosures.

About the author

Jesse Sumrak
Jesse Sumrak
Author

Related Resources

Articles

What Is DigitalOcean? Inside the AI-Native Cloud (2027)

Articles

10 Best LLM Observability Tools for AI Agents in 2027

Articles

Grok Bot vs Dots vs Muse: Which Agent Fits Developers in 2027?

Start building today

From GPU-powered inference and Kubernetes to managed databases and storage, get everything you need to build, scale, and deploy intelligent applications.