AI Agents
·IdenticAPI

How to Secure MCP Servers Used by AI Agents

Secure MCP servers with authentication, least privilege, exposed tool review, transport boundaries, secrets handling, and safe logging.

Securing MCP servers means hardening the processes that expose tools, resources, and prompts to MCP hosts — authentication at the deployment boundary, least-privilege credentials, minimal tool surface, safe logging, and network isolation. An MCP server is effectively a privileged API adapter: whatever tools it implements, the model can attempt to invoke through the host. Server security reduces what can be reached and what credentials can be abused if an agent is manipulated.

This guide focuses on server-side and deployment controls. Host-side policy enforcement (allow / review / block before invocation) is equally critical; pair server hardening with Agent Action Guard at the host. See What Is MCP Security? for the full stack.

MCP server threat model

Assume the LLM planner is untrusted. Successful prompt injection or tool output injection may cause the host to call MCP tools with arguments your operators never intended.

Server-side goals:

GoalWhy
Limit blast radiusOne compromised agent session should not access all backends
Protect credentialsServer holds secrets; model sees tool metadata only
Validate at the serverDefense in depth even if host policy fails
Safe observabilityLogs aid forensics without storing secrets

Authentication and transport boundaries

MCP supports multiple transports (for example local stdio and remote HTTP with streaming). The protocol does not define a universal authentication model — you implement access control for your deployment:

Local stdio servers

Common in desktop hosts. Risks:

  • Any process the user runs may spawn the server
  • Server inherits OS user permissions — often too broad

Controls:

  • Run dedicated low-privilege OS accounts for MCP server processes
  • Restrict filesystem tools to explicit allowlisted roots
  • Avoid mounting sensitive paths into server visibility

Remote HTTP / SSE servers

Expose MCP over the network. Risks:

  • Unauthenticated endpoints become open tool APIs
  • SSRF from other services may reach internal MCP URLs

Controls:

  • Require authentication at the edge (API gateway, mTLS, signed tokens issued by your host)
  • Network policies: MCP servers on private subnets, no public ingress without WAF
  • Rate limiting and connection quotas per tenant

Document who may open an MCP session separately from what tools exist. Connection auth is not a substitute for per-tool authorization inside the server implementation.

Least-privilege credentials

MCP servers typically use service credentials to call downstream APIs. Apply least privilege for AI agents to those credentials:

┌─────────────────────────────────────────────────────────────┐
│ MCP server credential matrix (example)                      │
├──────────────────┬──────────────────────────────────────────┤
│ Tool group       │ Credential scope                         │
├──────────────────┼──────────────────────────────────────────┤
│ ticket_read      │ read-only DB role, tenant-scoped         │
│ ticket_write     │ write role, no DELETE grant              │
│ billing_refund   │ separate microservice token, refund cap    │
│ admin_*          │ not deployed in prod MCP server            │
└──────────────────┴──────────────────────────────────────────┘

Practices:

  • One credential per tool domain — compromise of search_docs should not grant send_email
  • Short-lived tokens where downstream APIs support OAuth or STS
  • No secrets in tool descriptions — models and logs may capture descriptions
  • Rotate credentials on the same schedule as other service accounts

Scan proposed tool arguments for embedded secrets before execution; Agent Action Guard blocks contains_secret matches in default policy.

Tool surface review

Every exposed MCP tool expands excessive agency. Before production:

Inventory and justify

For each tool:

  • Business owner and risk class (read / write / destructive / external)
  • Downstream API and credential used
  • Maximum data volume per call
  • Whether a narrower tool could replace a generic one

Remove experimental tools from production server builds. Prefer get_order over sql_query.

Implement server-side authorization

Even when the host calls Agent Action Guard, the server must:

  • Re-validate tenant ID and user ID passed from the host (do not trust model-supplied tenant fields alone)
  • Enforce row-level filters in the server implementation
  • Reject path traversal in file tools (../ patterns)
  • Cap batch sizes and export ranges
POST /api/v1/security/agent-action
{
  "tool_name": "mcp_database",
  "action": "query",
  "arguments": { "sql": "SELECT * FROM users LIMIT 100000" },
  "context": "session tenant=acme"
}

A host policy might review large exports; the server should still enforce LIMIT caps.

Separate read and write servers

Deploy distinct MCP server processes:

  • mcp-read.internal — search, get, list only
  • mcp-write.internal — create, update with stricter network ACLs

Hosts register read tools for most agents; write tools only for approved workflows. See MCP Tool Permissions.

Handling untrusted content in server responses

MCP servers often return text from external systems (web fetches, email bodies, ticket threads). That text may contain indirect injection payloads.

Server responsibilities:

  • Normalize and bound response size (truncate with explicit truncated: true metadata)
  • Strip active content from HTML when returning text extracts
  • Optionally pre-scan with injection detection before returning to host:
POST /api/v1/security/prompt-injection
Authorization: Bearer idapi_test_your_key_here
{"text": "<downstream response>", "source": "mcp_tool_result"}

Hosts should still scan before re-prompting — defense in depth.

Secrets and configuration

  • Store secrets in a vault or managed secret service; inject at process start
  • Separate config per environment; block prod credentials in dev servers
  • Audit which operators can deploy MCP server images and change tool manifests

Run PII & secrets detection on server logs and error responses before they reach centralized logging.

Safe logging

Log for security operations without creating a new data leak channel:

LogDo not log
Tool name, action, latencyFull argument payloads with PII
Host session ID, tenant IDRaw API keys, bearer tokens
Policy decision correlation IDComplete tool results
Error class and downstream status codeUser chat content

Structure logs so they correlate with host-side Agent Action Guard request_id fields. Details in AI Agent Runtime Monitoring.

Network and dependency security

  • Pin and scan MCP server dependencies
  • Restrict outbound network from servers (egress allowlists to known APIs)
  • Monitor for new tools added to server manifests in CI — unexpected tool registration is an incident signal

For browsing-related tools, apply SSRF controls from secure agent web browsing at the server fetch layer.

Incident response

Prepare runbooks:

  1. Revoke compromised MCP credentials immediately
  2. Disable tool registration in host configs without full server redeploy when possible
  3. Query audit logs by request_id and session ID
  4. Re-scan historical tool outputs if injection suspected

Link MCP incidents to broader AI agent security checklist procedures.

Checklist summary

Before production MCP servers:

  • Authentication documented for each transport
  • Credentials scoped per tool domain
  • Tool inventory reviewed; admin tools removed
  • Server-side authorization independent of model
  • Response size limits and truncation metadata
  • Privacy-safe logging configured
  • Host enforces Agent Action Guard on every call

Full itemized list: MCP Security Checklist.

Frequently asked questions

What is the main security goal for MCP servers?

Limit blast radius: MCP servers hold credentials and expose tools to hosts. Harden authentication at the deployment boundary, scope credentials per tool domain, enforce server-side authorization, and avoid exposing admin or destructive tools in production manifests.

Should MCP servers trust tenant IDs from tool arguments?

No. Tenant and user scope should come from authenticated host tokens or session context validated by the server. Model-supplied tenant fields in arguments are untrusted and must not be the sole authorization source.

How should MCP servers handle large or HTML tool responses?

Normalize and bound response size with truncation metadata, strip active HTML when returning text extracts, and optionally pre-scan downstream text for injection before returning to the host. Hosts should still screen results before re-prompting.

What should MCP server logs include?

Tool name, latency, session or tenant identifiers, error classes, and correlation IDs — not full argument payloads, raw tool results, API keys, or user chat content. Align with privacy-safe agent monitoring practices.

Should read and write MCP tools share one credential?

Avoid it in production. Separate credentials per tool domain so compromise of a read tool cannot authorize writes or exports. Deploy distinct read and write MCP server processes when practical.

Related reading