A Practical Guide for Secure MCP Server Development provides actionable guidance for securing Model Context Protocol (MCP) servers, the critical connection point between AI assistants and external tools, APIs, and data sources.

Unlike traditional APIs, MCP servers operate with delegated user permissions, dynamic tool-based architectures, and chained tool calls , increasing the potential impact of a single vulnerability.

This post outlines best practices for secure architecture, strong authentication and authorization, strict validation, session isolation, and hardened deployment. Designed for software architects, platform engineers, and development teams, it helps organizations reduce risk while confidently enabling powerful, tool-integrated agentic AI capabilities.

model context protocol architecture

Introduction & Background

Organizations need to secure their MCP servers to safeguard AI integrations. These servers act as bridges
between AI assistants and external tools or data sources, so any security gap could allow attackers to
manipulate those AI assistants, steal sensitive information, or compromise downstream systems.

While security practitioners will certainly benefit from this guide, it is intended for software architects, platform engineers, and development teams responsible for MCP server development. The content outlines essential security controls and design decisions to apply from initial architecture through production deployment.

Vulnerability Landscape

MCP servers expose a broad and unique attack surface, containing traditional API security vulnerabilities and some unique AI-oriented risks. Common vulnerabilities/risks include:

Vulnerabilities

Insufficient Isolation (Session, Identity & Compute): MCP servers often manage multiple
concurrent sessions, share access privileges, or execute code in shared environments, creating
multiple layers of isolation risks. Without protocol-enforced state separation, there is a distinct risk
of cross-tenant data leakage where one user might accidentally access another’s context.

Furthermore, if the MCP server shares a single access identity (such as a service account) among
multiple users, it creates an identity impersonation risk where individual user actions cannot be
distinguished. Beyond logical separation, there is a critical need for compute isolation; when
servers execute code or tools in a shared host environment without strict sandboxing (like
containers or micro-VMs), malicious tenants can potentially exhaust shared resources or access the
process memory of others.

Tool Poisoning: Adversaries manipulate the AI through crafted inputs in prompts or tool metadata.
A maliciously designed tool description, for example, can include hidden instructions that trick the
model into performing unintended actions or exfiltrating data.

Dynamic Tool Instability (“Rug Pulls”): Given the lack of strict versioning for tool descriptions and
the dynamic nature of loading them, there is a risk of “rug pulls.” A previously trusted tool definition
can be swapped or modified in real-time to introduce malicious behavior, bypassing initial security
checks that occurred before the change.

Code Injection & Unsafe Execution: The MCP server passes model-provided inputs directly into
system commands, APIs, or database queries without validation. Incorrect, misguided, or malicious
code might be executed without user awareness or approval.

Credential Leakage & Token Misuse: MCP servers often handle API keys or OAuth tokens. If these
secrets are improperly stored, logged in plaintext, or cached for too long, attackers can steal them
to impersonate the client or access connected systems.

Excessive Permissions: Over-privileged tools or broad access scopes dramatically amplify the
impact of a breach. This violates the principle of least privilege and allows a single compromised
tool to endanger many systems. Applicable if the MCP server is the policy enforcer, or if the LLM has
a permissions mismatch when interacting with a user.

Secure MCP Architecture

Local vs Remote Connections: MCP exposes two communication channels, STDIO or Unix sockets
for local network communications, and Streamable HTTP for remote connections. For each
communication type, additional security controls apply:

  • Local MCP Servers: Prefer STDIO or Unix sockets over network sockets. If you must use local HTTP, bind only to 127.0.0.1, still utilize explicit authorization/authentication, and validate the Origin header. Run processes in isolated/sandboxed subprocesses or containers, with minimal or no access to external networks and minimal privileges.
  • Remote MCP Servers: Enforce TLS 1.2+ for all remote connections. Strictly validate all JSON-RPC messages against the MCP schema, rejecting any malformed or unrecognized data.

Enforce Trusted Connections and Authentication for MCP Clients: To secure interactions between
MCP Clients and Servers, use strong validation techniques such as allowlists, hardcoded
connections, or mutual TLS (mTLS) for known static relationships. In dynamic environments where
clients change, use strong authentication protocols (such as OAuth 2.1 or OIDC) to dynamically verify
client identity and allow connections rather than depending exclusively on static network trust.

Isolate Users and Sessions: In multi-tenant systems, strictly segregate execution contexts,
memory, and temp storage for each user or agent. Strictly prohibit the use of global variables, class-
level attributes, or shared singleton instances for storing user-specific data. Architect the server to
instantiate separate objects per session or utilize a strictly session-keyed state store (e.g., Redis
with session_id namespaces).

  • Strict Lifecycle Management: Implement deterministic cleanup routines. Ensure that when an MCP session terminates, disconnects, or times out, all associated file handles, temporary storage, in-memory contexts, and cached tokens are immediately flushed and destroyed to prevent residual data exposure.
  • Per-Session Resource Quotas: Enforce strict limits on memory, CPU, file system usage,and API rate limits keyed to the session ID or user identity.

Safe Tool Design

Cryptographic Tool Manifests: Require every tool to have a signed manifest that includes its
description, schema, version, and required permissions. Verify this signature and hash at load time.

Strict Onboarding and Approval: Maintain a formal approval workflow for adding or updating any
tool description or functionality. This must include code scanning (SAST), dynamic testing,
dependency scanning (SCA), and manual security review.

  • Validate Descriptions vs. Behavior: Implement manual checks, tool pinning, and LLM scans to ensure a tool’s advertised functionality (in its description) matches its actual code behavior during runtime. Flag any tool that attempts to perform actions (e.g., network writes) not mentioned in its description.
  • Tool Structure Validation: Maintain and audit all fields of each tool added to the policy. Only expose minimal, strictly necessary fields to the model, keeping internal metadata and sensitive fields outside of model context.

Data Validation & Resource Management

Resource Usage Limits: Impose quotas and rate limits on tool invocations and data fetches per
session. Use timeouts and isolated memory/compute budgets to prevent DoS attacks or runaway
processes.

Strict Input/Output Validation: Treat all data as untrusted. Define and enforce JSON Schemas for
every tool’s inputs (from the model) and outputs (back to the model). Reject any request that doesn’t
match the expected schema.

Strict Input/Output Sanitization and Encoding: Filter and sanitize all inputs to the model and
outputs into the tool. Strip or escape sequences which could lead to classic code injection attacks
(e.g. XSS, SQL Injection, RCE). Enforce size limits on all outputs from the tools or model.

Prompt Injection Controls

Structured Tool Invocation: Favor structured JSON tool calls over having the model generate free-
form text commands. This funnels the model’s intent through a formal, schema-validated interface.

Human-in-the-Loop (HITL): For high-risk actions (e.g., deleting data, sending money, system-level
changes), implement an approval checkpoint. Pause the action and require explicit confirmation
(e.g., using MCP elicitations) from a human user on MCP Client before proceeding.

LLM-as-a-Judge: For high-risk actions, run a dedicated approval check in a distinct context LLM
session, using a policy prompt that defines which tool calls and parameters are allowed and which
are blocked.

One Task, One Session: Reset MCP sessions when an agent switches contexts or tasks. This
“context compartmentalization” prevents hidden instructions from persisting in a long conversation
history, and could minimize “context degradation” improving LLM output quality.

Authentication & Authorization

Enforce OAuth 2.1 / OIDC: Treat authentication as mandatory for all remote MCP servers. Use OAuth
2.1/OIDC for client and user identity, validate iss, aud, exp, and signatures on every request.

  • Token Delegation: Use the OAuth token delegation flow to pass user context and
    permissions to an MCP server while limiting permissions and retaining distinct server non-
    human identity (NHI). (RFC 8693)
  • Prohibit Token Passthrough: Do not forward client tokens to downstream APIs; instead,
    use tokens explicitly issued to the MCP server or validated via “On-Behalf-Of” flows. Direct
    passthrough breaks audit trails and bypasses policies, creating a critical Confused Deputy
    risk. This vulnerability allows the MCP server to be tricked into misusing a user’s privileges
    to execute unauthorized actions, effectively bypassing the server’s intended security
    constraints.

Use Short-Lived, Scoped Tokens: Issue access tokens with minimal lifetimes (minutes) and narrow
scopes. Revalidate token signature, audience, and expiry on each call before executing any tool or
resource access.

Treat Sessions as State, Not Identity: Never rely on session IDs alone for authorization or
authentication. Bind any session/stream/queue entry to validated user and client identity (OAuth),
rotate/expire aggressively, and re-check authorization before performing sensitive actions.

Centralize Policy Enforcement: Use a dedicated policy/gateway layer to enforce authentication,
authorization, consent, tool filtering, and audit logging. Evaluate all requests centrally so policies
remain consistent across agents, servers, and upstream services.

Secure Deployment & Updates

Secrets Storage and Management: Utilize secrets storage vaults for client credentials and API keys.
Do not store secrets in environment variables, logs or plain-text in code. Never allow an LLM access
to a secret. Perform all secrets management functions in transparent middleware which is
inaccessible to the LLM.

Containerize and Harden: Deploy the MCP server in a minimal, hardened container. Run the
container as a non-root user. Drop all unnecessary container packages, dependencies, or Linux
capabilities. Limit residual attack surface.

Network Segmentation: Place the server in a restricted network segment. Use firewall rules or
Kubernetes NetworkPolicies to block all inbound and outbound traffic, except for what is explicitly
required.

Supply Chain Controls: Version pin and scan all dependencies at build time. Use signed container
images, monitor for new CVEs, and maintain AIBOMs for all builds to ensure provenance and detect
tampering.

CI/CD Security Gates: Integrate security checks and scanning directly into your pipeline as a gate.
Fail the build if new code introduces a vulnerability, uses an unapproved dependency, or fails a
policy check. (e.g., using policy-as-code tools like OPA).

Safe Error Handling: Do not return stack traces, tokens, filesystem paths, or tool internals in
responses returned to the model/client.

Governance

Cryptographic Integrity: Use cryptographic signing and version pinning for all tools, dependencies,
and registry manifests. Ensure their integrity and prevent tampering.

Peer Review and Oversight: Establish a policy that no new tool or major code change goes live
without a security-focused peer review.

Audit Logs and Trails: Log every action, including tool invocations (with parameters), resource
access, authentication/authorization events, and configuration changes (logging new and old
values). Use field-level allowlists and redaction/hashing to prevent sensitive data from entering
verbose logs. Store these logs securely and immutably for forensic analysis.

Non-Human Identity Governance: Treat all automated agents, backend processes or MCP server
systems as first-class identities with unique credentials and tightly scoped permissions.
Continuously audit NHI systems for data access and tool usage.

Tools & Continuous Validation

Automated Code Scanning: Use static analysis (SAST) tools (with custom MCP rules) and Invariant
MCP-Scan in your CI/CD pipeline. Use Software Composition Analysis (SCA) tools (e.g., npm audit,
pip audit, OSV-Scanner) to find vulnerabilities in dependencies. Break any build which exceeds your
risk tolerance due to scan findings.

Runtime Protections: Use runtime security tools to enforce isolation. This includes Docker’s
seccomp profiles, AppArmor, or specialized wrappers like context-protector. Tools like mcp-watch
can monitor runtime behavior.

Continuous Monitoring: Feed MCP server audit logs into a centralized monitoring system (SIEM).
Configure real-time alerts for suspicious patterns, such as a spike in failed validations, high-
frequency tool calls, or a tool suddenly accessing unusual files.

Supply Chain Vigilance: Use frameworks like the OpenSSF Scorecard to evaluate your project’s
security posture. Monitor vulnerability databases like OSV for new issues in your dependencies.

As AI systems expand in capability and complexity, the importance of secure MCP server development can’t be overstated. This guide provides a comprehensive, actionable roadmap for teams building and deploying MCP servers, empowering them to manage risks without sacrificing innovation or performance.

How Vox Machina Helps

At Vox Machina, we specialize in implementing AI automation solutions tailored to your industry. Whether you’re in finance, healthcare, retail, or manufacturing, we design systems that combine 20 Years of software development, marketing, web, security, servers and now AI to streamline your operations and deliver measurable results. Look at our process.

Want to explore how AI can transform your business?
Contact Vox Machina, your partner in Generative, Analytical, Reasoning, and Agentic AI solutions.

1 Comment

  1. Amazing. Thank you for this information. Very useful. Im starting to dabble in AI dev and your site is a very informative resource.

Leave a Reply

Your email address will not be published. Required fields are marked *

Not Sure Which Service Fits?

Book a free 30-minute discovery call and we'll help you identify where AI can make the biggest impact in your business.

Book a Discovery Call