MCP Server Security: Risks and Safeguards for Agents

MCP Server Security: Risks and Safeguards for Agents

A 2025 security census of 12,230 tools across 1,360 MCP servers found that 1,062 tools, 8.7% of the total, had at least one risk-related capability exploitable in MCP toolchains, according to the study's authors. That's the part of an agent stack most developers never read line by line: the tool list they accepted when they pasted a server config into Claude Code or Cursor.

MCP server security isn't a prompt-filtering problem. It's a containment problem. Assume an injected instruction eventually reaches the model, then make sure the agent still can't send from a mailbox it doesn't own, spend past its limit, approve its own action, or rewrite the policy that constrains it. The controls below are ordered by what they cost to implement and what they stop.

Table of Contents

Six Risks Every MCP Server Introduces

An MCP connection gives an agent capabilities, not just context. The official MCP specification says servers can give agents arbitrary data access and code-execution capabilities, and that tools must be treated cautiously for exactly that reason. Its three foundational controls are explicit user consent and control, data privacy, and tool safety.

RiskTypical exampleControl
Over-broad tool accessAgent sends mail from any mailbox in the accountMailbox-scoped keys with read, send or manage rights
Credential exposureAPI key committed in a config fileSecret manager, one key per agent, rotate on leak
Tool poisoningTool description tells the agent to read private key filesReview tool descriptions, pin tool definitions
Indirect prompt injectionEmail body tells the agent to forward the whole threadTreat content as data, validate outputs in code before acting
Vulnerable dependenciesUnpatched package in the transitive dependency treeInventory dependencies, pin versions, update on advisories
Unbounded actionsAgent sends hundreds of emails overnightSend limits, cooldowns, suppression lists and an audit log

A diagram illustrating six security risks associated with MCP servers, including potential threats and mitigation control strategies.

Where the documented failures actually sit

The failures cluster where silicon meets authority: the server, the client and the SDK. That is also where containment has to live. You cannot rely on catching every malicious string, because inbound mail, fetched pages and tool output all become model input. Design for the moment an instruction gets through.

Two risks deserve attention first because they are cheap to fix and expensive to ignore. Over-broad access turns a single confused tool call into an account-wide incident: an agent holding one key for every mailbox can send a customer reply from the founder's address. Unbounded actions turn a loop into a reputation problem, since an agent that retries a failed send all night burns the sending domain before anyone wakes up.

The other four risks fail in quieter ways. A leaked key gives the holder the same reach as the agent. A poisoned tool description can steer behavior before a single user message is sent. Untrusted email content can ask for threads, attachments or replies. An unpatched transitive dependency can change what a server does without changing its name.

I treat the table as a workflow test, not a server checklist. Connect the tools, feed in hostile content, then check what the agent can call, send and read. If a single tool can cross mailbox boundaries, resume a paused mailbox, or skip a send check, the setup needs tighter scope before it needs smarter prompts.

Practical rule: the first control to set isn't a filter, it's the permission scope on the key the agent holds.

For a wider treatment of hardening steps across server, client and host layers, the MCP server security best practices write-up from PostPulse is a useful companion to the table above.

Limit Each Agent to the Mailboxes and Tools It Needs

Permissions are the main lever, because an agent with a broad key can do everything that key allows, regardless of what the system prompt says. Start from the task, not from the tool list the server happens to expose.

TaskPermissionScope
Read and summarize a support inboxReadOne mailbox, no send right
Draft and send repliesSendOne mailbox, no manage right
Create mailboxes or change send rulesManageHeld by a person, not the agent key
Look up a customer record for a replyReadRead-only tool, no outbound tool in the same key
Forward a thread to an analytics toolNone until reviewedDenied by default, reviewed per chain

The MCP authorization specification defines authorization at the transport layer for HTTP-based connections, letting a client make requests to restricted servers on behalf of a resource owner, and recommends requesting only the scopes required for the operation rather than asking for broad access. Its security requirements cover token audience binding and validation, token theft, communication security, authorization-code protection, mix-up and confused-deputy attacks, open redirection, and client metadata security. In practice that translates to one key per agent, limited to the mailboxes that agent's job touches. Molted Email issues mailbox-scoped keys with separate read, send or manage rights on each mailbox, which is the granularity to look for in any mail tool an agent uses.

Three steps to a smaller tool list

  1. List every tool the agent can call. Print the tool names from each connected server, including the ones you don't remember enabling. In a hosted setup, list them from the server itself rather than from your config file, since the two drift.
  2. Remove any tool no task uses. A summarizing agent doesn't need a delete tool. Every unused tool is attack surface with no upside.
  3. Split what remains into read, send or manage, and grant only that. If a server bundles read and send in one tool, put it behind your own wrapper that checks the action before calling through, or don't connect it.

The edge case that catches teams: a tool that touches more than one mailbox, or forwards data outside the organization, should be denied by default until a person reviews the specific chain it enables. "Export contacts" and "forward thread" look like read operations and behave like exfiltration.

Then test the scope, don't assume it. Call each tool with a key that lacks the permission and confirm the call fails with an authorization error rather than succeeding. A key that can read a mailbox it was never granted isn't scoped, whatever the dashboard says.

Keeping API Keys and Tokens Out of Agent Reach

In a 2025 empirical study of 1,899 MCP servers, 7.2% of repositories contained at least one security vulnerability, and half of those affected repositories involved credential exposure, according to the study authors. Credentials are the most common thing to leak in this ecosystem, and the reason is structural: anything the model can read, it can repeat back in a response, a log line, or an outbound email body.

LocationSafeReason
Environment variable injected at launchYesStays out of the repository and can be scoped per agent
Secret manager read at runtimeYesRotation needs no code change or redeploy
Config file committed to gitNoCopied into history, forks and CI logs
Tool description or prompt textNoThe model can read it and repeat it
Tool output or log lineNoEnters the model context and persistent logs

The five-step handling procedure

  1. Create one key per agent. Shared keys make attribution impossible and rotation a coordinated outage.
  2. Store it in a secret manager or the launch environment. Read it at process start, pass it as a bearer token, never write it into a file the agent can open.
  3. Grant only the rights the task needs, per mailbox, as separate credentials for read and send.
  4. Redact keys from tool outputs and logs. Strip anything matching your key prefix before a result is returned to the model, and mask it in structured logs too.
  5. Rotate on any suspected leak and after staff changes. Treat rotation as routine, not as an incident response.

A key pasted into a chat window, a support ticket or a screenshot is already leaked. Revoke it immediately instead of waiting for a review meeting, then issue a narrower replacement.

Before the next push, scan the repository and its history. gitleaks detect --source . --log-opts="--all" walks commit history rather than just the working tree, and trufflehog git file://. --only-verified cuts noise by checking which findings still authenticate. Add one of them as a pre-push hook so the check runs without anyone remembering it. When you wire mail into an agent, the Molted mailbox API guide shows the bearer-key pattern where each request carries only the permissions of the key presented, which is the shape you want regardless of vendor.

A credential in the model's context is a credential you've published to whoever controls the next email the agent reads.

Pinning Tool Definitions and Dependencies

Tool poisoning travels through the definitions the agent reads. Treat those definitions as code under review, and freeze the shape the agent is allowed to call.

  1. List each server's tools with their names, descriptions and input schemas, and save the output.
  2. Store a hash of each definition in version control (sha256sum tools.json), next to the server version it came from.
  3. On every server update, diff the new descriptions and reject changes that mention files, keys, other tools, or instructions addressed to the model rather than to a developer.
  4. Reject any tool whose name collides with a tool on another server. Two servers registering search is an ambiguity an attacker can pick the winner of. That is a containment failure: the model cannot reliably choose the safe path once names blur together.

Dependencies are the second path in, and they are concentrated. A 2025 measurement study found more than 93% of MCP servers were implemented in JavaScript or Python, so one vulnerable npm or PyPI package can reach many deployments at once. A separate 2025 study of 2,562 real-world MCP applications found network APIs in 1,438 servers and system-resource APIs in 1,237 servers, which helps identify which servers can reach the network or run commands, and therefore which ones deserve sandboxing first.

Audit both trees, including the parts you did not install directly:

  • npm audit and npm ls --all for advisories and the transitive package list.
  • pip-audit and pipdeptree for the Python equivalents.

Whole-workflow tests matter here. Pinning a tool definition proves little if a dependency update changes what that tool does after approval. Run the same task against the pinned setup and the proposed update, then compare tool calls, outputs and side effects. The trade-off is real: strict pinning slows upgrades, while loose ranges let a transitive package change the effective server underneath a stable-looking schema.

Commit lock files, pin versions, and review advisories before each deploy. Read lock file diffs the way you read code diffs, because a new transitive package is new code running with your agent's privileges. Keep that review as a maintained artifact rather than a one-off snapshot, with Faberwork on technical documentation's future as background on keeping documentation current.

Screening Untrusted Content Before the Agent Acts

The email path is short. An attacker sends a message with a hidden instruction inside an existing thread, the agent reads that message as part of its working context, and the agent then acts with the user's privileges. The NIST presentation on agentic security names email as a concrete delivery channel for indirect injection and separates direct injections, which target the system prompt or user interaction, from indirect injections, which arrive through external sources such as emails, PDFs, retrieval systems, or other agents.

An infographic showing an AI agent being manipulated by an attacker injecting hidden instructions via email threads.

Why filtering text alone doesn't settle it

Both tool descriptions and tool outputs land in the same context window as the user's request, and the model has no built-in way to rank them by trustworthiness. Encoded and multilingual payloads slip past pattern checks, and an instruction that reads as harmless in isolation ("include the full thread for context") becomes an exfiltration step once a send tool is available. Screening reduces volume. It doesn't produce a proof.

The defenses that hold, in order:

  • Treat message bodies, attachments and thread content as data. Never let inbound text function as an instruction, including quoted history and signature blocks.
  • Keep explicit allow and deny rules for what the agent may do, as OWASP's prompt injection guidance recommends, with the agent's role constrained rather than improvised.
  • Validate outputs in application code before any send. Check recipient, mailbox and content against policy in trusted code, not in the prompt.
  • Keep credentials and state-changing capability outside the model, so a hijacked reasoning step can't reach them directly.

Molted Email applies this pattern at the mailbox: it screens every incoming email for prompt injection before the agent can read it, and a message scored high risk is quarantined so only a person can release the original. The write-up on scanning for prompt injection in email pipelines covers where that check sits relative to the agent's inbox access.

Screening and intent classification help agents process inbound mail, and they aren't infallible. That's why the send path needs its own independent checks, enforced outside the model, on every message.

Approvals, Audit Logs and Kill Switches That Hold

Containment means an injected instruction that reaches the model still can't release quarantined data, approve its own action, exceed a send limit, or change policy. Those four denials are the design target. Everything else is detection.

A diagram illustrating security protocols like audit logs, human approvals, and kill switches for AI model safety.

The approval flow, in order

The agent proposes a tool call. A policy check runs in application code. A person approves that exact call. The approval is then checked immediately before execution and consumed once, so it can't be replayed. OWASP's MCP security cheat sheet is specific about this: approval should be bound to the exact actor and tool call, verified at execution time, and consumed atomically to prevent replay or concurrent-request abuse.

The edge case is an approval tied only to a tool name. Approve send_email once and an attacker reuses that grant for a different recipient, a different mailbox, and a different body. Bind the approval to a hash of the full argument set, with a short expiry.

The audit log has to record every send, policy block, approval decision and mailbox change, with actor and timestamp, so you can establish what the agent did and when without reconstructing it from chat history. Molted Email enforces the asymmetry that makes logs trustworthy: an agent can lengthen a cooldown, pause a mailbox or lower its autonomy, but shortening the cooldown, resuming a mailbox or turning off injection quarantine returns a 403 and a link for a person to decide. The agent can't switch off the prompt-injection and quarantine checks at all, and its mailbox audit log records the blocked attempts alongside the successful sends.

Tightening a control can be automated. Loosening one needs a human, every time.

When something goes wrong, the kill switch runs in a fixed order: pause the mailbox or agent, revoke its key, review the audit log back to the last known good state, then reissue a narrower key before resuming. Write that procedure down and rehearse it on a test agent, because the first time you need it is the worst time to invent it.

Multi-Server Workflows That Leak Data

Every server can pass a scanner and the composed workflow can still leak. That's the result most per-server audits miss.

A diagram illustrating a security vulnerability where an attacker bypasses scanner systems by using multiple server pathways.

Two chains show it. An email-reading server passes attacker-controlled content straight into a sending server, and the send looks legitimate because both endpoints are trusted. Or a support agent forwards confidential thread context into an analytics tool, where it becomes queryable by everyone with dashboard access. Protocol-level analysis of multi-server configurations describes cross-tool attacks in which seemingly benign servers enable unintended exfiltration, plus implicit trust propagation and tool-name collisions when two servers register the same name.

Metadata won't save you either. A cross-registry study of 67,057 MCP servers collected from six public registries reported that its analysis tool identified 833 vulnerable servers and 18 servers with suspicious descriptions, according to the study authors.

Test the chain, not the endpoint:

  1. Draw the data flow from each input to each output.
  2. Mark every edge that crosses a trust boundary.
  3. Bind each tool to a stable identity, not only a name.
  4. Stop one agent from treating another agent's output as verified.
  5. Write one test per chain where the attacker tries to cause an unauthorized end-to-end effect.

A chain that reads from one source and writes to another needs a deny rule even when each server is safe alone. The metric that matters is whether an attacker can produce an unauthorized effect end to end.

Audit Your MCP Setup Before the Next Connection

Run these before go-live, not after the first incident.

  1. Each agent has its own key scoped to the mailboxes it needs.
  2. No key appears in a config file, log or tool output.
  3. Send and manage rights come from separate keys.
  4. Tool definitions are pinned and dependency lock files are committed.
  5. Untrusted inbound content is treated as data.
  6. Every outbound action passes a policy check.
  7. Approvals bind to the exact call.
  8. The audit log records sends, blocks and approvals.
  9. The pause and revoke procedure is written down and tested on a test agent.
  10. Each multi-server chain has an end-to-end test where an attacker tries to cause an unauthorized effect.

Two checks are worth automating in CI. Call a send tool with a read-only key and assert the call fails. Then revoke a key mid-run and assert every subsequent send fails, including calls already queued. If either test passes when it shouldn't, the scope exists only in documentation.

None of this should be a paid tier. Molted Email includes injection screening, quarantine, canary tokens, thread checks, the send policy, approvals and the audit log on every plan, including Free.


Molted Email gives each agent its own address and inbox, the way Gmail does for a person, with no separate email provider account to set up. Inbound mail is screened for prompt injection before the agent reads it, every send is checked against mailbox policy, and keys stay scoped to the mailboxes and actions each agent needs, which is the containment model this article argues for. Start free at Molted Email, free for people, with paid plans from $19 a month.

The Molted team