MCP servers can be secured, but they carry delegated-permission risks that dwarf most conventional APIs. The single most urgent action is to audit your OAuth consent flow timing: the MCP Security Best Practices draft mandates that state-tracking cookies must not be set until after explicit user consent, and most early implementations get this backwards. Three controls to implement immediately:
- Fix consent-state ordering. Generate and store the OAuth state value only after the user approves consent, using a cryptographically secure RNG. Setting it before consent approval defeats CSRF protection entirely.
- Harden transport. Disable unauthenticated HTTP transports; enforce mTLS or equivalent for any hosted MCP endpoint. Local stdio servers need process isolation and argument allowlisting before they touch production data.
- Enforce runtime least privilege. Scope every token and API credential to the minimum capability the MCP server actually needs. Token passthrough — forwarding a token not explicitly issued to your MCP server — is forbidden by the MCP authorisation spec and must be blocked at the server layer.
Key takeaways
Securing MCP servers requires fixing consent-state ordering first, then layering transport hardening, token audience validation, and runtime least privilege before any MCP server touches production data.
| Point | Details |
|---|---|
| Consent-state ordering is the top priority | Set the OAuth state cookie only after user consent approval; earlier placement defeats CSRF protection. |
| PKCE and audience binding are non-negotiable | Enforce PKCE with S256 and restrict token aud to the specific MCP server's identifier on every deployment. |
| Local stdio servers are not inherently safe | Apply argument allowlists, process sandboxing, and SCA on all dependencies before permitting local MCP execution. |
| SOC integration requires structured telemetry | Emit consent, state, token audience, and tool invocation events as structured JSON to your existing SIEM pipeline. |
| Alectura provides fleet-wide MCP visibility | Alectura's AIDR discovers, inventories, and monitors MCP servers across managed endpoints with SIEM and SOAR integration. |
Authoritative resources to consult next
The sources below are the primary references for implementing and auditing the controls covered in this guide.
-
MCP Security Best Practices — the canonical spec for consent handling, state ordering, cookie attributes, and confused-deputy mitigations. Start here for configuration rules.
-
MCP Authorisation Spec — covers token audience validation, token passthrough prohibition, and the authorisation flow requirements for MCP servers. Use for protocol-level audit tests.
-
OWASP GenAI Security Project — Practical Guide for Secure MCP Server Development — threat modelling framework and hardening recommendations from an application security perspective. Use for risk assessments and SOC playbook development.
-
OWASP GenAI LLM Top 10 — LLM-specific risk taxonomy including prompt injection and access control failures. Use to map MCP threats to a recognised risk framework for reporting and governance.
-
Red Hat — MCP Security Risks and Controls — practical analysis of local stdio risks, command injection, supply-chain concerns, and least-privilege recommendations. Use for developer-facing guidance and red-team scenario planning.
-
RFC 9700 — OAuth 2.0 Best Current Practice — the authoritative OAuth security guidance covering PKCE, redirect-URI matching, implicit flow deprecation, and CSRF protections. Use as the reference for authorisation server configuration reviews.
-
MCPSafe — OAuth State Parameter Threats — detailed documentation of the cookie-before-consent and weak-RNG failure modes with CWE mapping. Use for test case design and code review checklists.
Table of Contents
- What are the highest-impact MCP server security threats?
- OAuth and consent pitfalls that catch MCP proxies out
- How your deployment model changes the risk profile
- Runtime controls: what your MCP server should and shouldn't be able to do
- Logging, monitoring and SOC integration for MCP servers
- Hardening checklist and OAuth configuration every operator must verify
- How to test MCP server security and what audits should prove
- Practical detection and response for Australian SOCs
- Security review checklist: run this before every MCP deployment
- Sources
What are the highest-impact MCP server security threats?
MCP servers sit at a delegated-permission boundary. When a model invokes an MCP tool, it acts with the permissions of the token or credential the server holds — not just the model's own scope. A single exploit can therefore chain across every API and data source that the server is authorised to reach. OWASP GenAI frames this explicitly: treat a single MCP compromise as potentially granting chained access to multiple downstream systems.
Primary attack vectors, ranked by impact:
- Confused deputy / consent-cookie bypass. An MCP proxy that sets the OAuth state cookie before the user approves consent allows an attacker to craft a request that completes the OAuth flow without genuine user approval. This is the highest-frequency misconfiguration in current deployments.
- Authorisation-code interception. If redirect URIs are not matched exactly, an attacker can register a near-match URI and intercept the authorisation code before the legitimate server receives it.
- Token passthrough. Forwarding a token issued to a different audience to an upstream API is an anti-pattern that bypasses audience validation and lets a compromised MCP server impersonate the original caller.
- Open redirectors. An MCP proxy that accepts arbitrary redirect URIs can be weaponised to exfiltrate authorisation codes to attacker-controlled endpoints.
- SSRF via OAuth URL fetching. MCP clients that fetch OAuth-related URLs without restricting private IP ranges are vulnerable to server-side request forgery, potentially exposing internal services.
- Prompt and tool injection. A malicious tool description or crafted model input can redirect the model's tool invocations, escalating to unauthorised API calls or data exfiltration.
- Malicious or trojanised MCP servers. MCP servers are executable code distributed via package registries. A supply-chain compromise can introduce a backdoor that exfiltrates credentials or pivots to internal networks.
- Local stdio code execution. Red Hat's analysis notes that local stdio MCP servers can execute arbitrary code and are vulnerable to command injection when tool arguments are not sanitised.
How vectors chain into high-impact outcomes: a confused-deputy bypass yields a valid authorisation code; combined with token passthrough, that code grants access to a privileged upstream API; a prompt-injection payload then directs the model to exfiltrate data through an already-authorised tool call. The result is remote code execution or bulk data exfiltration without any single step looking obviously malicious in isolation.
Risk priority ranking: confused deputy and consent-state misconfiguration sit at the top because they are easy to introduce, hard to spot in code review, and give an attacker a fully valid OAuth session. Token passthrough and open redirectors follow closely. Stdio injection and supply-chain risks are lower frequency but catastrophic when they land.
OAuth and consent pitfalls that catch MCP proxies out
The consent-cookie ordering problem is the most concrete and most commonly missed. MCPSafe documents two failure modes that defeat CSRF protection in MCP proxy flows: setting the state cookie before the user approves consent, and using a weak or predictable RNG to generate the state value. Both map to CWE-352 and both are trivially exploitable once identified.
Required protections from the MCP Security Best Practices:
- Per-client consent storage: consent decisions must be stored per MCP client identity, not globally or per user alone.
- State must be generated with a cryptographically secure RNG and stored server-side only after the user explicitly approves consent.
- Consent pages must include CSRF protections independent of the state parameter.
- Redirect URIs must be matched exactly — no prefix matching, no wildcard patterns.
- Consent cookies must carry
HttpOnly,Secure, andSameSite=Strictattributes.
PKCE, audience binding and resource indicators:
RFC 9700 (OAuth BCP) requires the authorisation code flow with PKCE (RFC 7636) for all public and most confidential clients. For MCP proxies this means: generate a code_verifier per authorisation request, send the code_challenge in the authorisation request, and verify the code_verifier at the token endpoint. Audience-restricted tokens — where the aud claim is bound to the specific MCP server's identifier — prevent a token issued for one server being replayed against another. Resource indicators (RFC 8707) let you bind a token to a specific resource URI, which is the cleanest way to enforce this at the authorisation server.
Token passthrough is categorically forbidden. The MCP authorisation spec requires servers to validate that any token they accept was explicitly issued for them — aud must match the server's registered identifier.
Protocol checklist for MCP proxy implementers:
[ ] State generated with CSPRNG, stored server-side only after consent approval
[ ] PKCE (S256 method) enforced for all authorisation requests
[ ] Redirect URIs registered and matched exactly — no wildcards
[ ] Token audience validated on every inbound request
[ ] Implicit grant flow disabled at the authorisation server
[ ] Consent cookie attributes: HttpOnly, Secure, SameSite=Strict
[ ] Per-client consent records stored and auditable
[ ] State validated at callback before any token exchange
Pro Tip: When reviewing a third-party MCP proxy, check the order of operations in the callback handler: if the state cookie is written before the consent approval response is processed, the implementation is vulnerable regardless of how strong the RNG is. Look for the cookie Set-Cookie header appearing in the pre-consent redirect response.
How your deployment model changes the risk profile
The transport and hosting model you choose for an MCP server determines which attack surface dominates. There is no universally safe option — each pattern trades one set of risks for another.
| Deployment model | Primary risks | Recommended mitigations |
|---|---|---|
| Local stdio (same machine) | Command injection, local privilege escalation, trojanised server packages | Argument allowlisting, process sandboxing, signed releases, SCA on dependencies |
| Proxied stdio (local server, remote proxy) | Confused deputy, consent-state bypass, SSRF via proxy | Full OAuth consent flow hardening, egress proxy, network segmentation |
| HTTP/streaming (self-hosted remote) | Token theft, open redirectors, SSRF, unauthenticated endpoints | mTLS, exact redirect-URI matching, PKCE, private IP blocking |
| Third-party hosted MCP | Supply-chain risk, data residency, opaque consent flows | Vendor assessment, trusted vendor vetting, contractual data handling obligations |
Local stdio servers are the most deceptive. "Local" does not mean "trusted" — a trojanised package or a crafted tool argument can escalate to arbitrary code execution on the host. Red Hat's guidance is explicit: treat local MCP servers as executable boundaries and audit how tool descriptions map to subprocess arguments.
HTTP/streaming servers expand the remote attack surface significantly. Every unauthenticated endpoint is a potential entry point. SSRF is a real concern when the server fetches OAuth-related URLs: the MCP Best Practices spec recommends blocking private and reserved IP ranges and routing all outbound fetches through an egress proxy.
Third-party hosted MCP servers introduce supply-chain and data residency risks that are particularly relevant under Australian privacy law. You are trusting the vendor's consent flow, their token handling, and their logging. Contractual controls and vendor assessment are the primary mitigations here — technical controls alone are insufficient.
Runtime controls: what your MCP server should and shouldn't be able to do
The goal at runtime is to make the blast radius of any single compromise as small as possible. That means constraining what the server can call, what arguments it will accept, and what the model can direct it to do.

Allowlisting tool actions and arguments:
Every tool exposed by an MCP server should have an explicit allowlist of permitted actions and argument shapes. A JSON Schema definition per tool argument is the practical mechanism:
{
"type": "object",
"properties": {
"filename": {
"type": "string",
"pattern": "^[a-zA-Z0-9_\\-\\.]+$",
"maxLength": 255
}
},
"required": ["filename"],
"additionalProperties": false
}
Reject any request that fails schema validation before it reaches business logic. additionalProperties: false is not optional — it prevents argument smuggling through undeclared fields.
Capability scoping:
- Issue separate, minimally scoped tokens for each downstream API the MCP server calls. A server that reads files should not hold a token that can also write to a database.
- Revoke tokens on session end, not just on expiry.
- Enforce scope at the authorisation server, not just in application code — application-layer scope checks are bypassable; authorisation server enforcement is not.
Prompt and tool injection mitigations:
Canonicalise tool names before routing: a model output of read_file and read-file should resolve to the same handler, not create an ambiguous dispatch. For high-risk actions (deleting records, sending messages, executing shell commands), require explicit user confirmation in the UI before the tool call is executed. The OWASP GenAI LLM Top 10 maps prompt injection as a top-tier risk for LLM-integrated systems, and MCP tool calls are a direct execution path for injected instructions.
Pro Tip: Sandbox local MCP server processes using OS-level controls: on Linux, apply a restrictive seccomp profile and drop all capabilities except those explicitly needed. On macOS, use sandbox-exec with a deny-default profile. Never let a local MCP server process inherit the parent process's full environment — strip secrets from the environment before spawning.
Logging, monitoring and SOC integration for MCP servers
An MCP server that emits no telemetry is a blind spot in your SOC. The minimum viable telemetry set is small but specific.
Minimum telemetry to emit:
- Consent decisions: timestamp, client ID, user ID (hashed), approved scopes, and outcome (approved/denied/expired).
- State generation and validation events: timestamp, state handle (hashed), and whether validation succeeded or failed at callback.
- Token audience checks: every inbound token validation, including the claimed
aud, the expectedaud, and pass/fail outcome. - Tool invocation logs: tool name, argument schema hash (not raw arguments if they contain PII), invoking session ID, and outcome.
- Input/output digests: SHA-256 of tool inputs and outputs for audit trail purposes, without logging raw content that may contain secrets or personal data.
SIEM/SOAR integration:
Structured JSON logs with consistent field names (mcp.event_type, mcp.client_id, mcp.tool_name) make ingestion into SIEM platforms straightforward. For Australian SOC teams already running a SIEM, MCP logs should feed the same pipeline as application and identity logs — correlation between an anomalous token audience error and a concurrent unusual login event is the kind of signal that surfaces real attacks. LLM monitoring tooling that surfaces MCP-specific signals alongside standard endpoint telemetry gives analysts a unified view rather than a separate console to check.
| Alert rule | Threshold | Suggested action |
|---|---|---|
| Repeated state validation failures | 3+ failures in 5 minutes from same client | Block client, alert SOC |
| Token audience mismatch | Any single occurrence | Immediate alert, investigate token origin |
| Unexpected redirect URI | Any URI not in registered allowlist | Block request, alert SOC |
| High-frequency tool invocations | Baseline + 3 standard deviations | Rate-limit, queue for analyst review |
| Consent decision from unknown client ID | Any occurrence | Block, alert, investigate registration |
Rate limiting at the MCP server layer is a prerequisite for these alerting rules to be meaningful. Without it, a high-volume attack simply floods the log with noise before the alert fires.
Hardening checklist and OAuth configuration every operator must verify
Platform hardening and OAuth configuration are separate concerns, but both need to be verified before an MCP server goes near production data.
Platform hardening:
- Run MCP server processes in containers with a read-only root filesystem and a minimal base image (distroless or equivalent).
- Use a dedicated, least-privilege service account — no shared credentials, no ambient cloud IAM roles broader than the server needs.
- Store all secrets in a secrets manager (AWS Secrets Manager, HashiCorp Vault, or Azure Key Vault). Never pass secrets as environment variables in container definitions.
- Enforce egress controls: MCP servers should only be able to reach the specific upstream APIs they are authorised to call. An egress proxy with an explicit allowlist is the practical enforcement mechanism.
- Apply network segmentation: MCP servers should not be reachable from the public internet unless that is explicitly required by their function.
OAuth configuration specifics:
- Require PKCE with the
S256method for all clients —plainmethod provides no meaningful protection. - Register redirect URIs as exact strings at the authorisation server. Reject any authorisation request whose
redirect_uridoes not match exactly. - Issue audience-restricted tokens: the
audclaim must be the MCP server's registered resource identifier. - Disable the implicit grant flow at the authorisation server level, not just in client configuration.
- Where the deployment supports it, use mutual TLS (
tls_client_auth) orprivate_key_jwtfor client authentication at the token endpoint — both are significantly stronger thanclient_secret_post.
Pro Tip: During a security review, pull the authorisation server's metadata endpoint (/.well-known/oauth-authorization-server) and check grant_types_supported. If implicit appears in the list, the server is misconfigured regardless of what the client is doing. Fix it at the server, not the client.
Supply-chain hygiene applies to MCP servers as directly as to any other executable component. Run SCA (Software Composition Analysis) on every MCP server dependency, enforce signed releases, and treat an unsigned MCP server package the same way you would treat an unsigned binary from an unknown vendor.
How to test MCP server security and what audits should prove
Testing MCP security requires a purpose-built matrix. Standard web application test cases miss the consent-ordering and token-audience issues that are specific to MCP proxy flows.
Test matrix:
| Test case | What to verify | Expected evidence |
|---|---|---|
| Consent-state ordering | State cookie is NOT set before consent approval | Proxy logs show cookie written only post-consent |
| Token audience validation | Server rejects tokens with wrong aud claim | 401 response with invalid_token error |
| SSRF via OAuth URL fetch | Private IP ranges blocked | Connection refused or egress proxy block log |
| Open redirector | Non-registered redirect URI rejected | error response, no code issued |
| Prompt/tool injection | Injected tool name does not execute unintended action | Tool dispatch log shows canonical name only |
| Stdio argument injection | Shell metacharacters in arguments rejected | Schema validation error, no subprocess spawned |
| Token passthrough | Forwarded token from different audience rejected | 401 response, audience mismatch logged |
| Implicit flow | Authorisation server rejects implicit grant requests | error response, unsupported_response_type |
Audit artefacts to collect:
- Consent decision logs covering at least one approved and one denied consent flow, with timestamps and state handle hashes.
- Token introspection results showing
audclaim values for tokens issued during the test. - Egress proxy logs confirming private IP block rules fired during SSRF test cases.
- Sandbox configuration snapshots (seccomp profile, container capabilities) for local MCP server deployments.
- SCA report for all MCP server dependencies, with no critical CVEs unmitigated.
- SAST report covering the consent-flow handler and the tool dispatch logic.
Red-team playbooks to run:
- Attempt to complete an OAuth flow without user interaction by replaying a pre-consent state value.
- Register a near-match redirect URI (e.g. adding a trailing slash or a query parameter) and attempt code interception.
- Craft a tool description containing a prompt injection payload and observe whether the model executes an unintended tool call.
- Submit a tool argument containing
; rm -rf /tmpand verify the server rejects it before spawning a subprocess.
Least-privilege regression tests should run on every deployment: after any dependency update or configuration change, re-verify that the service account cannot access resources outside its defined scope.
Practical detection and response for Australian SOCs
Australian organisations face a specific regulatory context that shapes how MCP visibility needs to be operationalised. The Australian Cyber Security Centre (ACSC) Essential Eight framework emphasises application control, patching, and restricting administrative privileges — controls that map directly to MCP server hardening. Under the Privacy Act 1988 and the Notifiable Data Breaches (NDB) scheme, a token theft or data exfiltration event involving personal information triggers mandatory notification obligations, which means your MCP incident response process needs to include a privacy assessment step from the outset.
Practical integration patterns for Australian SOCs:
- Ingest MCP server logs into your existing SIEM alongside endpoint telemetry. Correlate MCP tool invocation events with the device and user context from your endpoint agent — a tool call that originates from a device flagged as non-compliant is a higher-priority alert than the same call from a managed, patched endpoint.
- Use endpoint-level AIDR telemetry to detect unauthorised local MCP servers running on managed devices. A process listening on a stdio pipe that is not in your approved software inventory is a detection signal, not background noise.
- Build detection rules for token audience misuse: if an MCP server's token appears in a request to an API it is not registered to call, that is an indicator of token passthrough or credential theft.
Specific use cases for Australian SOC teams:
- Detecting prompt-injection chains: correlate a spike in tool invocation volume from a single session with an unusual data access pattern (e.g. bulk file reads followed by an outbound connection). Neither signal alone is conclusive; together they warrant immediate investigation.
- Detecting unauthorised local MCP servers: an endpoint agent that inventories running processes and network connections can flag a new stdio-based MCP server that appeared after a developer installed an unapproved package.
- Detecting consent-flow anomalies: repeated state validation failures from the same client ID, or consent decisions recorded for client IDs not in your registered inventory, are high-fidelity signals that warrant immediate triage.
The ACSC's guidance on network segmentation and access control provides the baseline framework; MCP-specific controls layer on top of it rather than replacing it. For organisations subject to the Security of Critical Infrastructure Act 2018, MCP servers that touch operational data may fall within the scope of mandatory risk management programme requirements.
Security review checklist: run this before every MCP deployment
A numbered checklist with ownership and expected evidence for each control.
-
Consent-state ordering verified (Dev) — Code review confirms state cookie is written only after consent approval. Evidence: pull request diff showing cookie write in post-consent handler only.
-
PKCE enforced with S256 method (Dev) — Authorisation requests include
code_challenge_method=S256. Evidence: captured authorisation request in test logs. -
Exact redirect-URI matching configured (Dev/Infra) — Authorisation server configuration shows redirect URIs as exact strings. Evidence: authorisation server metadata or admin console screenshot.
-
Token audience validation active (Dev) — Server rejects tokens where
auddoes not match its registered identifier. Evidence: test case showing 401 response on audience mismatch. -
Token passthrough prohibited (Dev) — Code review confirms no forwarding of inbound tokens to upstream APIs. Evidence: pull request diff and SAST report.
-
SSRF protections in place (Infra) — Egress proxy configured with allowlist of permitted outbound destinations; private IP ranges blocked. Evidence: egress proxy configuration file and test log showing blocked private-IP request.
-
Tool argument allowlists enforced (Dev) — JSON Schema validation applied to all tool arguments;
additionalProperties: falseset. Evidence: schema definitions in code and test case showing rejection of invalid arguments. -
Implicit grant flow disabled (Infra) — Authorisation server metadata does not list
tokeninresponse_types_supported. Evidence:/.well-known/oauth-authorization-serverresponse. -
Secrets stored in secrets manager (Infra) — No secrets in environment variables or container definitions. Evidence: infrastructure-as-code review and secrets manager audit log.
-
MCP telemetry flowing to SIEM (SOC) — Consent, state, token audience, and tool invocation events visible in SIEM. Evidence: sample log entries in SIEM console.
-
SCA and SAST completed (Dev/Infra) — No critical CVEs unmitigated; SAST covers consent handler and tool dispatch. Evidence: SCA and SAST reports dated within 30 days of deployment.
-
Incident response plan updated (SOC) — MCP-specific scenarios (token theft, prompt injection, unauthorised local server) added to IR playbook. Evidence: updated IR document with MCP section and NDB assessment step.
The part most teams get wrong
The consent-state ordering bug is not subtle. It is a sequencing error that is easy to introduce when a developer writes the OAuth callback handler and sets up session state before checking whether the user actually approved consent. The fix is three lines of code. The problem is that nobody tests for it specifically, because standard OAuth test suites do not include a "did the cookie appear before the consent page rendered?" check.
The deeper issue is that MCP security is being treated as OAuth plumbing rather than as a first-class security concern. Teams that have shipped OAuth integrations before assume they understand the attack surface. They do not — because MCP proxies introduce a three-party state machine (client, proxy, upstream IdP) that creates ordering constraints that do not exist in a standard two-party OAuth flow.
The practical trade-off that comes up repeatedly in enterprise deployments: consent UX versus security. Product teams push for a frictionless consent experience; security teams need the consent to be genuine and auditable. The answer is not to reduce friction by weakening the consent flow — it is to make the consent UI clear and fast while keeping the security properties intact. A consent page that takes two seconds and is cryptographically sound is not a UX problem. A consent bypass that takes zero seconds and hands an attacker a valid session is.
One anonymised example: an enterprise MCP proxy deployment had the state cookie set in the pre-consent redirect handler, before the consent page was ever shown to the user. The fix was to move the Set-Cookie call from the pre-consent handler to the post-consent callback, add a CSPRNG-generated state value, and add a validation step at the callback. The change took less than a day. The vulnerability had been in production for three months.
Alectura gives your SOC visibility over MCP activity across your fleet
Most security stacks have no idea an MCP server is running on a managed endpoint, let alone what it is connecting to or what data it is touching. Alectura is AI Detection & Response built for exactly this gap.

Alectura discovers MCP servers running across your fleet, inventories the access each one holds, and tracks prompt timelines so your SOC can see what the model was directed to do and what tools it called. When a token audience anomaly fires, or a local MCP server appears on a device that should not have one, Alectura surfaces the signal in your existing SIEM or SOAR pipeline — no separate console, no manual correlation. For Australian organisations under NDB obligations, the on-device audit log gives you the evidence trail a privacy assessment requires. Review Alectura's enterprise service commitments and speak with the team about deploying AIDR across your environment.
Sources
- OAuth state parameter missing or set before consent in MCP Servers — Explanation & Prevention | MCPSafe | MCPSafe
- Model Context Protocol (MCP): Understanding security risks and controls
- A practical guide for secure MCP server development — OWASP GenAI Security Project
