# MCP security best practices This lesson targets [MCP specification 2026-07-28][mcp-spec]. [mcp-spec]: https://modelcontextprotocol.io/specification/2026-07-28/ **Level:** Intermediate-to-advanced reference. **Estimated time:** 30 minutes, excluding setup. **Prerequisites:** Complete the [security lesson](./README.md) first. A **JWT** is a token format that carries claims; its audience names the intended service and its scope names allowed operations. The [advanced terms](./README.md#terms-for-the-advanced-references) explain MRTR, PKCE, and client registration. ## Learning objectives After reading this reference, you will be able to: - Distinguish token validation, state ownership, and tool-content checks. - Choose which security checklist sections apply to a server review. ## Choose a review path Start with token security, state handles, AI-specific threats, and permissions (sections 1–4). Sections 5–12 cover optional operational and enterprise practices. For each control, identify the component that enforces it and the evidence you would inspect; a checklist alone doesn't secure a server. **Check:** If a caller presents a valid token for a different server, should this server accept it? No. A token must be issued for this server and meet its authorization requirements, including any required scope. > **Important:** This document reflects > [MCP Specification 2026-07-28](https://modelcontextprotocol.io/specification/2026-07-28/) > and the official > [MCP Security Best Practices](https://modelcontextprotocol.io/specification/2026-07-28/basic/security_best_practices). Follow the [authorization specification](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization) and [current request-model checklist](./README.md#secure-the-current-request-model). Use the [runnable authorization sample](./samples/cimd-dcr-auth/README.md) to practice per-request JWT validation and operation-specific scopes. ## Current protocol boundaries MCP `2026-07-28` is stateless: no `initialize`, protocol session headers, or standalone GET stream. Discover capabilities with `server/discover` and send the reserved `_meta` fields with every request. On HTTP, mirror version, method, and named operation in `MCP-Protocol-Version`, `Mcp-Method`, and `Mcp-Name`. Validate `Host` and a present `Origin`. Results carry `resultType`; keep caller-dependent cache hints private and reauthorize cached reads. Additional input uses MRTR, not independent server-initiated requests. Bind integrity-protected `requestState` to the caller, original operation, and expiry; reauthorize retries and enforce single-use when required. ## 🏔️ Hands-On Security Training For practical implementation experience, we recommend the **[MCP Security Summit Workshop (Sherpa)](https://azure-samples.github.io/sherpa/)** - a comprehensive guided expedition to securing MCP servers in Azure. The workshop covers all OWASP MCP Top 10 risks through a "vulnerable → exploit → fix → validate" methodology. All practices in this document align with the **[OWASP MCP Azure Security Guide](https://microsoft.github.io/mcp-azure-security-guide/)** for Azure-specific implementation guidance. ## Essential Security Practices for MCP Implementations The Model Context Protocol introduces unique security challenges that extend beyond traditional software security. These practices address foundational requirements and MCP-specific threats including prompt injection, tool poisoning, state-handle hijacking, confused deputy problems, and token passthrough vulnerabilities. ### **MANDATORY Security Requirements** **Critical Requirements from MCP Specification:** > **MUST NOT**: MCP servers **MUST NOT** accept any tokens that were not explicitly issued for the MCP server > > **MUST**: MCP servers implementing authorization **MUST** verify ALL inbound requests > > **MUST NOT**: MCP servers **MUST NOT** treat possession of a state handle as authentication > > **MUST**: MCP proxy servers using a static third-party client ID **MUST** > obtain consent for each MCP client before forwarding authorization --- ## 1. **Token Security & Authentication** **Authentication & Authorization Controls:** - **Rigorous Authorization Review**: Conduct comprehensive audits of MCP server authorization logic to ensure only intended users and clients can access resources - **External Identity Provider Integration**: Use established identity providers like Microsoft Entra ID rather than implementing custom authentication - **Token Audience Validation**: Always validate that tokens were explicitly issued for your MCP server - never accept upstream tokens - **Proper Token Lifecycle**: Implement secure token rotation, expiration policies, and prevent token replay attacks - **Resource discovery**: Publish RFC 9728 metadata and a `resource_metadata` challenge; include RFC 8707 `resource` in authorization and token requests - **Issuer binding**: Store registrations and tokens keyed by issuer and re-register with a newly selected authorization server **Protected Token Storage:** - Use Azure Key Vault or similar secure credential stores for all secrets - Implement encryption for tokens both at rest and in transit - Regular credential rotation and monitoring for unauthorized access ## 2. **State Handle & Transport Security** **Secure Application State Practices:** - **Opaque State Handles**: Use secure, non-deterministic handles for application state that spans requests - **User-Specific Binding**: Bind handles server-side to the authenticated principal and reject cross-user reuse - **Lifecycle Management**: Expire and revoke handles to limit vulnerability windows - **Per-request Authorization**: Never treat a state handle as authentication; authorize every request that presents one **Transport Layer Security:** - Require HTTPS for remote HTTP transports in production - Use process isolation and environment credentials for local stdio servers - Configure modern TLS with proper certificate rotation and validation ## 3. **AI-Specific Threat Protection** 🤖 **Prompt Injection Defense:** - **Microsoft Prompt Shields**: Deploy AI Prompt Shields for advanced detection and filtering of malicious instructions - **Input validation**: Validate arguments and enforce authorization; input validation alone doesn't prevent every prompt injection or confused deputy attack - **Content boundaries**: Treat tool output, resource text, and metadata as untrusted data. Delimiters and classifiers aren't authorization controls **Tool Poisoning Prevention:** - **Tool Metadata Validation**: Implement integrity checks for tool definitions and monitor for unexpected changes - **Dynamic Tool Monitoring**: Monitor runtime behavior and set up alerting for unexpected execution patterns - **Approval Workflows**: Require explicit user approval for tool modifications and capability changes ## 4. **Access Control & Permissions** **Principle of Least Privilege:** - Grant MCP servers only minimum permissions required for intended functionality - Implement role-based access control (RBAC) with fine-grained permissions - Regular permission reviews and continuous monitoring for privilege escalation **Runtime Permission Controls:** - Apply resource limits to prevent resource exhaustion attacks - Use container isolation for tool execution environments - Jail filesystem access after canonicalization and symlink resolution; explicit path arguments and resource URIs don't grant permission - Implement just-in-time access for administrative functions ## 5. **Content Safety & Monitoring** **Content Safety Implementation:** - **Azure Content Safety Integration**: Use Azure Content Safety to detect harmful content, jailbreak attempts, and policy violations - **Behavioral Analysis**: Implement runtime behavioral monitoring to detect anomalies in MCP server and tool execution - **Comprehensive Logging**: Log all authentication attempts, tool invocations, and security events with secure, tamper-proof storage **Continuous Monitoring:** - Real-time alerting for suspicious patterns and unauthorized access attempts - Integration with SIEM systems for centralized security event management - Regular security audits and penetration testing of MCP implementations ## 6. **Supply Chain Security** **Component Verification:** - **Dependency Scanning**: Use automated vulnerability scanning for all software dependencies and AI components - **Provenance Validation**: Verify the origin, licensing, and integrity of models, data sources, and external services - **Signed Packages**: Use cryptographically signed packages and verify signatures before deployment **Secure Development Pipeline:** - **GitHub Advanced Security**: Implement secret scanning, dependency analysis, and CodeQL static analysis - **CI/CD Security**: Integrate security validation throughout automated deployment pipelines - **Artifact Integrity**: Implement cryptographic verification for deployed artifacts and configurations ## 7. **OAuth Security & Confused Deputy Prevention** **OAuth 2.1 Implementation:** - **PKCE**: Use the authorization code flow with **S256** - **Client registration**: Prefer Client ID Metadata Documents or pre-registration; use deprecated Dynamic Client Registration only as a compatibility fallback - **Explicit consent**: MCP proxies using a static third-party client ID must obtain consent for each MCP client before forwarding authorization - **Redirect URI validation**: Require exact redirect URI and client ID checks - **Response issuer**: Compare a present RFC 9207 `iss` exactly with the validated issuer recorded before redirecting, even if not advertised. Reject a missing `iss` when support was advertised, before code exchange - **CIMD and discovery SSRF**: Validate metadata identity and redirect URIs. Restrict egress, resolved IPs, redirects, DNS changes, response sizes, and timeouts; don't assume an HTTPS URL is safe to fetch ### Legacy notes [Roots, Sampling, Logging, and DCR are deprecated](https://modelcontextprotocol.io/specification/2026-07-28/deprecated), not removed from this revision. Prefer explicit path arguments with a jail, direct provider APIs, stderr/OpenTelemetry, and CIMD or pre-registration. If protocol logging is retained, set `io.modelcontextprotocol/logLevel` in each request's `_meta`; don't use a persistent logging-level setting. **Proxy Security:** - Prevent authorization bypass through static client ID exploitation - Implement proper consent workflows for third-party API access - Monitor for authorization code theft and unauthorized API access ## 8. **Incident Response & Recovery** **Rapid Response Capabilities:** - **Automated Response**: Implement automated systems for credential rotation and threat containment - **Rollback Procedures**: Ability to quickly revert to known-good configurations and components - **Forensic Capabilities**: Detailed audit trails and logging for incident investigation **Communication & Coordination:** - Clear escalation procedures for security incidents - Integration with organizational incident response teams - Regular security incident simulations and tabletop exercises ## 9. **Compliance & Governance** **Regulatory Compliance:** - Ensure MCP implementations meet industry-specific requirements (GDPR, HIPAA, SOC 2) - Implement data classification and privacy controls for AI data processing - Maintain comprehensive documentation for compliance auditing **Change Management:** - Formal security review processes for all MCP system modifications - Version control and approval workflows for configuration changes - Regular compliance assessments and gap analysis ## 10. **Advanced Security Controls** **Zero Trust Architecture:** - **Never Trust, Always Verify**: Continuous verification of users, devices, and connections - **Micro-segmentation**: Granular network controls isolating individual MCP components - **Conditional Access**: Risk-based access controls adapting to current context and behavior **Runtime Application Protection:** - **Runtime Application Self-Protection (RASP)**: Deploy RASP techniques for real-time threat detection - **Application Performance Monitoring**: Monitor for performance anomalies that may indicate attacks - **Dynamic Security Policies**: Implement security policies that adapt based on current threat landscape ## 11. **Microsoft Security Ecosystem Integration** **Comprehensive Microsoft Security:** - **Microsoft Defender for Cloud**: Cloud security posture management for MCP workloads - **Azure Sentinel**: Cloud-native SIEM and SOAR capabilities for advanced threat detection - **Microsoft Purview**: Data governance and compliance for AI workflows and data sources **Identity & Access Management:** - **Microsoft Entra ID**: Enterprise identity management with conditional access policies - **Privileged Identity Management (PIM)**: Just-in-time access and approval workflows for administrative functions - **Identity Protection**: Risk-based conditional access and automated threat response ## 12. **Continuous Security Evolution** **Staying Current:** - **Specification Monitoring**: Regular review of MCP specification updates and security guidance changes - **Threat Intelligence**: Integration of AI-specific threat feeds and indicators of compromise - **Security Community Engagement**: Active participation in MCP security community and vulnerability disclosure programs **Adaptive Security:** - **Machine Learning Security**: Use ML-based anomaly detection for identifying novel attack patterns - **Predictive Security Analytics**: Implement predictive models for proactive threat identification - **Security Automation**: Automated security policy updates based on threat intelligence and specification changes --- ## **Critical Security Resources** ### **Official MCP Documentation** - [MCP Specification (2026-07-28)](https://modelcontextprotocol.io/specification/2026-07-28/) - [MCP Security Best Practices](https://modelcontextprotocol.io/specification/2026-07-28/basic/security_best_practices) - [MCP Authorization Specification](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization) ### **OWASP MCP Security Resources** - [OWASP MCP Azure Security Guide](https://microsoft.github.io/mcp-azure-security-guide/) - Comprehensive OWASP MCP Top 10 with Azure implementation - [OWASP MCP Top 10](https://owasp.org/www-project-mcp-top-10/) - Official OWASP MCP security risks - [MCP Security Summit Workshop (Sherpa)](https://azure-samples.github.io/sherpa/) - Hands-on security training for MCP on Azure ### **Microsoft Security Solutions** - [Microsoft Prompt Shields](https://learn.microsoft.com/azure/ai-services/content-safety/concepts/jailbreak-detection) - [Azure Content Safety](https://learn.microsoft.com/azure/ai-services/content-safety/) - [Microsoft Entra ID Security](https://learn.microsoft.com/entra/identity-platform/secure-least-privileged-access) - [GitHub Advanced Security](https://github.com/security/advanced-security) ### **Security Standards** - [OAuth 2.0 Security Best Practices (RFC 9700)](https://datatracker.ietf.org/doc/html/rfc9700) - [OWASP Top 10 for Large Language Models](https://genai.owasp.org/) - [NIST AI Risk Management Framework](https://www.nist.gov/itl/ai-risk-management-framework) ### **Implementation Guides** - [Azure API Management MCP Authentication Gateway](https://techcommunity.microsoft.com/blog/integrationsonazureblog/azure-api-management-your-auth-gateway-for-mcp-servers/4402690) - [Microsoft Entra ID with MCP Servers](https://den.dev/blog/mcp-server-auth-entra-id-session/) --- > **Security notice:** MCP security practices evolve rapidly. Always verify > against the current [MCP specification](https://modelcontextprotocol.io/specification/2026-07-28/) > and [official security documentation](https://modelcontextprotocol.io/specification/2026-07-28/basic/security_best_practices) > before implementation. ## Takeaway Token validation, access decisions, state ownership checks, and content inspection protect different boundaries. None replaces the others. ## What's Next - Previous: [Security quick reference](./mcp-best-practices.md) - Optional next: [MCP Security Controls](./mcp-security-controls.md) - Return to: [Security Module Overview](./README.md) - Continue the core journey: [Simple authentication](../03-GettingStarted/11-simple-auth/README.md)