Skip to main content
MCP WebSocket Security Template for AI AgentsResearch
4 min readFor Security Engineers

MCP WebSocket Security Template for AI Agents

When Microsoft disclosed the AutoJack vulnerability in AutoGen Studio, the attack vector was clear: three layered weaknesses in the Model Context Protocol (MCP) WebSocket implementation allowed malicious webpages to execute arbitrary code on the host machine. Although the vulnerable code never shipped through PyPI, the pattern it exposed affects any AI agent framework that trusts localhost connections from web contexts.

You need a security configuration template that hardens MCP WebSocket implementations before deploying AI agents in production. This template addresses the core architectural flaw: treating localhost as an implicit trust boundary when web-enabled agents can bridge that boundary.

Purpose of This Template

This configuration template secures MCP WebSocket servers that power AI agent frameworks. It implements three defensive layers:

  1. Origin validation to reject connections from untrusted web contexts.
  2. Authentication tokens to verify client identity beyond network location.
  3. Process isolation to contain the blast radius if an agent is compromised.

Use this when deploying AI agents that:

  • Accept WebSocket connections for real-time communication.
  • Run on developer workstations or shared infrastructure.
  • Have filesystem or process execution capabilities.
  • Integrate with web applications or browser extensions.

The template maps to OWASP ASVS v4.0.3 Requirement 9.1.2 (WebSocket origin validation) and NIST 800-53 Rev 5 control SC-7 (boundary protection).

Prerequisites

Before implementing this template, verify:

  • Your MCP server supports configurable origin checking (check framework documentation).
  • You can generate and rotate cryptographic tokens (minimum 256-bit entropy).
  • Your deployment environment supports process-level sandboxing (containers, VMs, or OS-level isolation).
  • You have logging infrastructure to capture WebSocket handshake attempts.

You'll need access to:

  • The MCP server configuration file (typically config.json or server.yaml).
  • Web application CORS settings if your agent accepts browser connections.
  • Container orchestration configs if deploying in Kubernetes or Docker.

The Template

{
  "mcp_server": {
    "websocket": {
      "bind_address": "127.0.0.1",
      "port": 8765,
      "allowed_origins": [
        "https://your-app.example.com",
        "https://admin.example.com"
      ],
      "require_origin_header": true,
      "reject_on_missing_origin": true
    },
    "authentication": {
      "enabled": true,
      "method": "bearer_token",
      "token_header": "X-MCP-Auth-Token",
      "tokens": [
        {
          "name": "prod-web-client",
          "value": "GENERATE_256_BIT_TOKEN_HERE",
          "expires": "2025-06-01T00:00:00Z",
          "allowed_capabilities": ["read_files", "execute_approved_tools"]
        }
      ],
      "rotation_warning_days": 30
    },
    "process_isolation": {
      "enabled": true,
      "sandbox_type": "container",
      "resource_limits": {
        "max_memory_mb": 512,
        "max_cpu_percent": 25,
        "network_access": "egress_only",
        "filesystem_access": "read_only",
        "writable_paths": ["/tmp/agent-workspace"]
      },
      "blocked_syscalls": [
        "ptrace",
        "mount",
        "reboot"
      ]
    },
    "logging": {
      "log_all_connections": true,
      "log_rejected_origins": true,
      "log_auth_failures": true,
      "siem_integration": {
        "enabled": true,
        "endpoint": "https://siem.example.com/ingest",
        "alert_on": ["auth_failure", "origin_mismatch", "sandbox_violation"]
      }
    }
  }
}

Origin Validation Block: The allowed_origins array prevents the core AutoJack attack pattern. When a malicious webpage attempts a WebSocket connection, the server checks the Origin header against this allowlist. Setting reject_on_missing_origin: true blocks requests that don't declare their origin—a common exploit technique.

Authentication Block: Localhost binding isn't authentication. This section requires a cryptographic token in every WebSocket handshake. The allowed_capabilities field implements least-privilege: even authenticated clients can't execute arbitrary processes unless you explicitly grant that capability.

Process Isolation Block: If an agent is compromised, this sandbox limits damage. The read_only filesystem prevents persistence mechanisms. The blocked_syscalls list stops privilege escalation attempts. The resource limits prevent denial-of-service.

Logging Block: You can't secure what you can't see. This configuration sends all connection attempts to your SIEM, with automatic alerting on suspicious patterns.

How to Customize It

For development environments: Replace allowed_origins with your local development URLs. Generate a development token with shorter expiration (7 days). Keep process_isolation enabled—developer machines are high-value targets.

For production web applications: Add your production domains to allowed_origins. Use your secrets management system (HashiCorp Vault, AWS Secrets Manager) to inject tokens at runtime instead of storing them in config files. Set rotation_warning_days to align with your key rotation policy.

For internal tools: If your AI agent only serves backend services (no web browser access), set allowed_origins: [] and reject_on_missing_origin: false. You're not vulnerable to the web-based attack vector, but still enforce token authentication.

For high-security environments: Add "require_tls": true to the websocket block to enforce encryption even on localhost. Implement mutual TLS if your infrastructure supports it. Reduce max_memory_mb and max_cpu_percent based on your agent's actual resource profile.

Capability scoping: The allowed_capabilities array should match your agent's job. An agent that summarizes documents needs ["read_files"]. An agent that deploys infrastructure needs ["execute_approved_tools"] with a separate allowlist of permitted commands. Never grant ["*"].

Validation Steps

After deploying this configuration:

1. Test origin rejection: Use curl to attempt a WebSocket connection with a fake origin:

curl -i -N -H "Origin: https://malicious.example.com" \
  -H "Upgrade: websocket" \
  -H "Connection: Upgrade" \
  http://127.0.0.1:8765/

You should receive HTTP 403 Forbidden. If you get HTTP 101 Switching Protocols, your origin validation isn't working.

2. Verify authentication: Attempt connection without the token header. Check your logs for an auth_failure event with the client IP and timestamp.

3. Confirm sandbox boundaries: If your agent has a command execution capability, try to write outside the writable_paths. The operation should fail with a permission error, and you should see a sandbox_violation alert in your SIEM.

4. Monitor for 30 days: Review your connection logs weekly. Legitimate clients should appear consistently. Rejected connections should be investigated—they're either misconfigured clients or reconnaissance attempts.

5. Audit token usage: Before each token expires, verify which services are using it. Rotate tokens that show unexpected access patterns.

The AutoJack vulnerability combined three weaknesses. This template addresses all three: it validates origins, requires authentication beyond network location, and isolates the agent process. Implement it before your AI agents handle production data, and treat localhost as the network boundary it actually is—permeable unless you explicitly harden it.

WebSocket Protocol

Topics:Research

You Might Also Like