MCP server security: how to secure and monitor Model Context Protocol servers used by AI agents in production

How the Model Context Protocol works, the threat model from indirect prompt injection to tool poisoning and token passthrough, the controls that matter, what to log for every tool call, example detection rules and an incident runbook.

Obseria TeamObseria
Summary
  • MCP server security starts with the assumption that everything an agent reads, including tool descriptions and tool results, can contain instructions from an attacker. Indirect prompt injection, tool poisoning and over-privileged tools are the core risks.
  • The most effective controls are architectural: least-privilege tools and tokens, allowlisted and version-pinned servers, human approval for destructive actions, no token passthrough, sandboxing and limited network egress.
  • MCP monitoring means logging every tool call with caller, tool, redacted arguments, result size, latency, errors and approvals, and alerting on unusual patterns such as new tools, changed tool definitions, bursts of calls or large outbound data.

MCP server security has become a practical concern for every team that connects AI agents to real systems. The Model Context Protocol lets an agent read your tickets, query your databases, open pull requests or restart deployments through a standard interface. That is exactly what makes it useful, and exactly what makes it risky: a model that can call tools can also be talked into calling the wrong ones. Securing an MCP server means limiting what each tool can do, controlling which servers an agent may use and monitoring every tool call so that misuse becomes visible.

This guide explains how MCP works, the threat model for Model Context Protocol security, the controls that matter, what to log for MCP monitoring, example detection rules, an incident runbook and a checklist. It builds on our LLM observability guide, which covers prompts, tokens and evaluations, and focuses on the tool layer.

What is the Model Context Protocol?

The Model Context Protocol (MCP) is an open protocol that Anthropic introduced in November 2024. It standardises how AI applications connect to external tools and data, so that one integration works across many clients. The specification is versioned by date and has evolved quickly since the first release, so check the version that your clients and servers implement.

  • Hosts are the AI applications the user works with, for example a desktop assistant, an IDE or your own agent runtime.
  • Clients live inside the host and each maintain a connection to one server.
  • Servers expose capabilities. A server can wrap a database, a SaaS API, a file system or an internal service.

Servers offer three main primitives. Tools are functions the model can call, with a name, a description and a JSON schema for the input. Resources are data the client can read, such as files or records. Prompts are reusable templates. Messages are exchanged as JSON-RPC 2.0, with methods such as tools/list and tools/call, and servers can notify clients when their tool list changes.

Two standard transports exist. stdio runs the server as a local subprocess of the host and communicates over standard input and output. Streamable HTTP runs the server as a remote service; it replaced the earlier HTTP with Server-Sent Events transport in the 2025 revisions of the specification. For HTTP-based transports, the specification defines an authorization framework based on OAuth 2.1, in which the MCP server acts as a resource server and validates tokens issued for it. Details such as metadata discovery and resource indicators have changed between spec versions, so verify against the revision you implement. Authorization is optional in the specification, which means that many community servers ship without it.

Threat model: how MCP servers get abused

The central problem is that a language model does not reliably separate instructions from data. Anything that reaches the model's context can steer its next tool call. Combine that with tools that have real permissions and you get the following risks.

ThreatHow it worksTypical impact
Indirect prompt injection via tool outputA web page, ticket, email or document returned by a tool contains hidden instructions that the model followsUnwanted tool calls, data leaks, actions in the user's name
Tool poisoningA malicious server hides instructions in a tool description or schema that the user never sees but the model readsThe agent reads secrets or sends data to the attacker while seemingly doing something else
Rug pullA server that looked harmless changes its tool definitions after approval or after an updatePreviously reviewed tools suddenly behave differently
Tool shadowingOne server's tool description influences how the model uses tools from another, trusted serverTrusted tools used with attacker-chosen parameters
Over-privileged toolsA tool runs with broad credentials, such as an admin database user or a token with all scopesAny successful injection becomes a large blast radius
Confused deputy and token passthroughA server forwards the client's token to downstream APIs, or acts with its own privileges on behalf of a caller who should not have themBypassed access controls, broken audit trails
Data exfiltrationThe agent is induced to place sensitive data in a URL, an outgoing message or a tool argument that reaches the attackerLeak of personal data, secrets or source code
Supply chain of community serversServers installed from public registries or repositories with unreviewed code, typosquatted names or compromised maintainersCode execution on developer machines or servers
Local server exposureA local server listens on a network interface without authentication, or a stdio server runs with the user's full rightsAccess from other processes or hosts

The MCP specification has a security best practices section that discusses several of these issues, including confused deputy problems, token passthrough, which it forbids, and session hijacking. The general background on prompt injection applies fully: there is no known filter that blocks all injections, so you design for the case that one succeeds.

Controls that actually reduce risk

Because injection cannot be fully prevented, the strongest controls limit what a successful injection can do. Think in layers: what servers are allowed, what each tool may do, what needs a human, and what leaves the sandbox.

Least privilege for tools and tokens

  • Give each server its own credentials, scoped to the minimum. A server that reads tickets does not need write access to the database.
  • Prefer narrow tools over generic ones. A tool get_invoice_status(id) is much easier to secure than run_sql(query).
  • Use short-lived tokens issued for the specific server (audience-bound), and never pass the client's token through to downstream APIs.
  • Separate read and write tools, so that policies and approvals can treat them differently.

Allowlists and version pinning

  • Maintain an allowlist of approved servers per environment. Block everything else at the host or gateway.
  • Pin server versions and verify package integrity. Do not let clients pull the latest version of a community server on every start.
  • Record a hash of each server's tool definitions at approval time and alert when the definitions change.
  • Review the source of community servers before use, as you would for any dependency, and track them in your software bill of materials (SBOM).

A pinned configuration for a local server could look like this. The package name, version and path are example values:

{
  "mcpServers": {
    "docs-readonly": {
      "command": "npx",
      "args": ["--yes", "example-docs-mcp-server@1.4.2", "--read-only", "/srv/docs"],
      "env": { "DOCS_API_TOKEN": "${DOCS_READONLY_TOKEN}" }
    }
  }
}

Human approval for destructive actions

Any tool that deletes, pays, sends, deploys or changes access should require explicit approval by a human who sees the exact arguments. The specification defines tool annotations such as readOnlyHint and destructiveHint, but they are hints from the server and must not be trusted from servers you do not control. Make the approval decision in the host or in a gateway, based on your own classification of each tool.

Input and output validation

  • Validate tool arguments against strict schemas on the server, including length limits and allowed values. Do not assume the model sends what the schema says.
  • Treat tool results as untrusted. Mark them clearly as data in the context, strip or neutralise markup that can hide instructions and limit result size.
  • Use AI guardrails to detect obvious injection patterns and sensitive data in inputs and outputs, as one layer among several, not as the only defense.

Sandboxing, secrets and network egress

  • Run servers in containers or sandboxes with a read-only file system where possible, without access to the host's home directory or SSH keys.
  • Keep secrets in a secret manager and inject them at runtime; never put them in tool descriptions, prompts or logs.
  • Limit outbound network access to the domains a server needs. Egress limits are one of the few controls that stop exfiltration even when the model has been fully manipulated.
  • Bind local HTTP servers to localhost only, require authentication and validate the Origin header, as the specification recommends for Streamable HTTP.

What to log for MCP monitoring

MCP monitoring answers two questions: what did the agent do, and was it allowed to? Both require an audit record for every tool call, correlated with the user request and the model call that triggered it. Log at the point where you have control, ideally in a gateway or proxy between clients and servers, and additionally in the servers you operate.

FieldExampleWhy it matters
Caller identityUser ID hash, agent ID, client nameWho triggered the call, for access review and incidents
Server and versiontickets-mcp, 2.3.1Detect unknown servers and unexpected upgrades
Tool nameupdate_ticketCore dimension for every rule
Tool definition hashSHA-256 of name, description and schemaDetect rug pulls and changed descriptions
ArgumentsHash plus redacted copyInvestigate without storing secrets or personal data in plain text
Result size and typeBytes, item count, error flagSpot bulk reads and exfiltration
Latency and errorsDuration, error codeOperational health and probing behaviour
ApprovalRequired, approved by, decision timeProve that destructive actions had human sign-off
Trace contextTrace ID, span ID, session IDConnect the tool call to the prompt, the model response and downstream requests

OpenTelemetry's GenAI semantic conventions define attributes for generative AI operations, including tool execution spans with attributes such as gen_ai.operation.name and gen_ai.tool.name. These conventions are still marked as in development, and work on MCP-specific conventions is ongoing, so check the current status and expect names to change. Emitting tool calls as spans means you see them in the same trace as the model call and the downstream API requests.

A single tool call record could look like this (values are examples):

{
  "ts": "2026-11-04T09:12:44.381Z",
  "event": "mcp.tool_call",
  "gen_ai.operation.name": "execute_tool",
  "gen_ai.tool.name": "update_ticket",
  "mcp.server": "tickets-mcp",
  "mcp.server.version": "2.3.1",
  "tool_definition_sha256": "9f2c...e41a",
  "caller.user_id_hash": "hmac:5d1e...",
  "caller.agent_id": "support-agent",
  "args_sha256": "c7b0...19aa",
  "args_redacted": { "ticket_id": "T-4821", "comment": "[REDACTED:120 chars]" },
  "result.bytes": 412,
  "result.error": false,
  "duration_ms": 238,
  "approval.required": true,
  "approval.by": "hmac:a90f...",
  "trace_id": "0af7651916cd43dd8448eb211c80319c"
}

Apply PII masking before storage. Tool arguments and results often contain exactly the data you are trying to protect, and the audit log must not become the leak.

Detection ideas and example rules

Agent traffic is bursty and varies by use case, so start with baselines and treat every number below as an example value to calibrate. Several rules need no threshold at all because the event itself is suspicious.

SignalDetectsExample rule (calibrate to your baseline)
Unknown server or toolShadow servers, unapproved installsAny call to a server or tool not on the allowlist
Changed tool definitionRug pull, tool poisoning after updateDefinition hash differs from the approved hash
Destructive call without approvalBroken approval flow, bypassTool classified as destructive, approval.required false or missing
Call burstLoops, automated abuseMore than 50 calls per session in 5 minutes (example value)
Large result volumeBulk reads before exfiltrationResult bytes per session above 10x the 7-day median for that tool (example value)
Read then outbound sendExfiltration chainSensitive read tool followed by a tool that sends email, posts to a URL or creates a public link in the same session
URLs or encoded data in argumentsExfiltration via parametersArguments of non-network tools containing external URLs or long base64 strings
Error spikes per toolProbing, schema abuseValidation errors for one tool above 5x baseline in 15 minutes (example value)
Egress denialsAttempted exfiltrationAny blocked outbound connection from a server sandbox

The read-then-send chain, written as generic SQL over tool call events, could look like this:

-- example: sensitive read followed by an outbound tool in the same session
SELECT r.session_id, r.caller_agent_id,
       r.tool_name AS read_tool, s.tool_name AS send_tool,
       r.ts AS read_ts, s.ts AS send_ts
FROM mcp_tool_calls r
JOIN mcp_tool_calls s
  ON s.session_id = r.session_id
 AND s.ts BETWEEN r.ts AND r.ts + INTERVAL '10 minutes'
WHERE r.tool_class = 'sensitive_read'
  AND s.tool_class = 'outbound'
  AND r.ts > now() - INTERVAL '1 hour';

Correlate these alerts with traces. A suspicious tool call is much easier to judge when you can see the prompt, the retrieved document that contained the injection and the model output in one view, which is the core idea of AI observability.

Incident runbook for a compromised MCP integration

  1. Contain. Disable the affected server or tool in the gateway or host allowlist. Pause the agents that used it.
  2. Revoke credentials. Rotate the tokens and API keys the server held, and revoke sessions and OAuth grants issued for it.
  3. Preserve evidence. Export tool call logs, traces, tool definitions and server versions for the relevant period before retention removes them.
  4. Scope. List all tool calls in affected sessions, which data was read, which actions were taken and which outbound connections occurred.
  5. Find the entry point. Identify the content or server change that injected the instructions: a document, a ticket, a web page or a new tool definition.
  6. Remediate. Reverse unwanted changes, notify data owners and, where personal data is involved, involve your data protection officer for the assessment of reporting duties.
  7. Harden and review. Tighten scopes, add approvals or egress rules, add a detection rule for the pattern and hold a blameless review. Follow your regular incident management and postmortem process.

MCP server security checklist

Copy this checklist into your AI platform backlog

  • Inventory of all MCP servers in use, with owner, version, transport and credentials
  • Allowlist of approved servers per environment, enforced at the host or gateway
  • Pinned server versions, verified packages and reviewed source for community servers
  • Approved hash of every tool definition, with alerts on change
  • Dedicated, least-privilege, short-lived credentials per server; no token passthrough
  • Narrow tools instead of generic execute or query tools; read and write separated
  • Own classification of destructive tools and mandatory human approval with visible arguments
  • Strict schema validation of arguments on the server side
  • Tool results treated as untrusted data, size-limited and filtered by guardrails
  • Servers sandboxed, secrets injected at runtime, outbound network restricted to required domains
  • OAuth-based authorization for remote servers according to the spec version you implement; local HTTP servers bound to localhost
  • Audit log for every tool call with caller, server, tool, definition hash, redacted arguments, result size, latency, errors and approval
  • Tool calls as spans in the same trace as model calls and downstream requests
  • Detection rules for unknown tools, changed definitions, unapproved destructive calls, bursts, bulk reads and read-then-send chains
  • Runbook for disabling a server, revoking credentials and preserving evidence

Frequently asked questions about MCP security

Is MCP insecure by design?

No. MCP is a protocol for connecting tools; the risks come mostly from giving a model broad permissions and untrusted inputs. The specification includes authorization and security guidance, but implementing it is up to clients and servers.

Do local stdio servers need security?

Yes. A stdio server runs with the rights of the user who started it. A malicious or compromised local server can read files and credentials on that machine, so allowlisting, pinning and sandboxing matter there too.

Can a guardrail model stop prompt injection?

It can catch many known patterns, but not reliably all of them. Use it as one layer and rely on least privilege, approvals and egress limits for the cases it misses. For background, see our glossary entry on agentic AI.

How Obseria helps with MCP server security and monitoring

Obseria is an OpenTelemetry-native observability platform, so tool calls from your agents and MCP servers arrive as traces, logs and metrics next to the model calls and downstream requests they belong to.

  • AI observability shows prompts, model calls, tool calls, latency, cost and errors of agent workflows in one trace.
  • Obseria Pipeline masks personal data and drops secrets from tool arguments and results before storage in the EU.
  • Obseria Security Enterprise adds security analytics and alerting on top of the same telemetry, so the detection rules above can run where the data already is.
  • Obseria's own MCP server gives AI assistants access to your observability data, and the AI SRE agent acts only with human approval, which is the same principle we recommend for your tools. Read more in our article on AI SRE agents in incident response.

To see agent and tool call traces in Obseria, book a demo.

Share

Observability that delivers answers.

Start for free with OpenTelemetry, no credit card required.