SPB Git

Repository Public

deploy-compose.md 22.2 KB 475 lines markdown

1---2title: Deploy MCP tunnels with Docker Compose3url: https://platform.claude.com/docs/en/agents-and-tools/mcp-tunnels/deploy-compose4description: Install the MCP tunnel stack on a VM using Docker Compose.5---67<Note>8  MCP tunnels are in research preview. [Request access](https://claude.com/form/mcp-tunnels) to try them.9</Note>1011This guide deploys the [tunnel stack](https://platform.claude.com/docs/en/agents-and-tools/mcp-tunnels/concepts#components) as hardened containers on a single host. The same configuration can be replicated across multiple hosts for availability.1213## Before you begin1415You need:1617* **A tunnel.** With programmatic access, the [setup component](https://platform.claude.com/docs/en/agents-and-tools/mcp-tunnels/concepts#components) creates one for you when you don't supply a tunnel ID; to attach to an existing tunnel instead, [create it in the Console](https://platform.claude.com/docs/en/agents-and-tools/mcp-tunnels/console#create-a-tunnel) and record the tunnel ID (`tnl_...`). Manual provisioning always starts from a Console-created tunnel.1819* **A way for the host to authenticate to the Tunnels API.**2021  * **Programmatic access (recommended).** Turn on **Set up programmatic access** when creating the tunnel (or create the federation rule directly under **Settings > Workload identity** if you're letting the setup component create the tunnel) so the setup component can authenticate through Workload Identity Federation. Record the federation rule ID (`fdrl_...`) and your organization ID.22  * **Manual.** Skip programmatic access. You'll [get the tunnel token from the Console](https://platform.claude.com/docs/en/agents-and-tools/mcp-tunnels/console#get-the-connection-details), generate a CA and server certificate yourself, and [register the CA in the Console](https://platform.claude.com/docs/en/agents-and-tools/mcp-tunnels/console#add-a-ca-certificate).2324* **A host with Docker and Docker Compose** installed. The manual flow also requires `openssl` (1.1.1 or later).2526* **Outbound network connectivity** from the host to `api.anthropic.com` (443 TCP) and the [tunnel edge](https://platform.claude.com/docs/en/agents-and-tools/mcp-tunnels/concepts#components) (7844 TCP and UDP). See the full [network requirements](https://platform.claude.com/docs/en/agents-and-tools/mcp-tunnels/overview#network-requirements).2728* **One or more MCP servers** running and reachable from the host on the addresses you'll configure under `routes`. If you don't have one yet, [use the sample server](https://platform.claude.com/docs/en/agents-and-tools/mcp-tunnels/deploy-compose#optional-use-a-sample-mcp-server).2930## Optional: Use a sample MCP server3132If you don't have an MCP server available for testing, use this minimal one:3334```bash35mkdir -p mcp-tunnel36cat > mcp-tunnel/hello_server.py <<'EOF'37from mcp.server.fastmcp import FastMCP3839mcp = FastMCP("hello-server", host="0.0.0.0", port=9000)404142@mcp.tool()43def hello(name: str = "world") -> str:44    """Say hello to someone."""45    return f"Hello, {name}!"464748if __name__ == "__main__":49    mcp.run(transport="streamable-http")50EOF51```5253The following Install steps `cd` into `mcp-tunnel/` and note where to add the corresponding service and route.5455## Install5657This guide provides one reference approach using Docker Compose. You are responsible for adapting it to meet your organization's security requirements.5859<Tabs>60  <Tab title="With programmatic access">61    This path requires the host to have an OIDC identity provider (such as a cloud VM metadata server or SPIFFE). If it doesn't, use the **Without programmatic access** tab instead.6263    The setup component uses Workload Identity Federation to fetch the tunnel token, generate a CA and server certificate, and register the CA with Anthropic.6465    <Steps>66      <Step title="Prepare the deployment directory">67        ```bash68        mkdir -p mcp-tunnel/{config,data}69        cd mcp-tunnel70        sudo chown 65532:65532 data71        ```7273        The containers run as the non-root UID `65532` and need write access to `data/`.74      </Step>7576      <Step title="Write docker-compose.yaml">77        The compose file pins images by SHA-256 digest, runs every container as non-root with a read-only filesystem, drops all Linux capabilities, and disables privilege escalation.7879        ```bash80        cat > docker-compose.yaml <<'EOF'81        services:82          setup:83            image: us-docker.pkg.dev/anthropic-public-registry/images/mcp-proxy@sha256:efb27b299d627e4134815663cb8896641eeaee025d734c0f695582b4df38f01384            entrypoint: ["/setup"]85            command:86              - init87              - --api-url=https://api.anthropic.com88              - --output=dir:/data89              - --token-version=190            environment:91              - TUNNEL_ID92              - ANTHROPIC_FEDERATION_RULE_ID93              - ANTHROPIC_ORGANIZATION_ID94              - ANTHROPIC_WORKSPACE_ID95              - ANTHROPIC_IDENTITY_TOKEN96            volumes:97              - ./data:/data98            user: "65532:65532"99            read_only: true100            security_opt:101              - no-new-privileges:true102            cap_drop:103              - ALL104            profiles: ["setup"]105106          cloudflared:107            image: cloudflare/cloudflared@sha256:6b599ca3e974349ead3286d178da61d291961182ec3fe9c505e1dd02c8ac31b0108            command: tunnel --no-autoupdate run --url http://localhost:8080109            environment:110              - TUNNEL_TOKEN111            # Share the proxy's netns so localhost:8080 reaches it.112            network_mode: "service:mcp-proxy"113            restart: unless-stopped114            user: "65532:65532"115            read_only: true116            security_opt:117              - no-new-privileges:true118            cap_drop:119              - ALL120            stop_grace_period: 30s121            logging:122              options:123                max-size: "10m"124                max-file: "3"125126          mcp-proxy:127            image: us-docker.pkg.dev/anthropic-public-registry/images/mcp-proxy@sha256:efb27b299d627e4134815663cb8896641eeaee025d734c0f695582b4df38f013128            volumes:129              - ./config/mcp-proxy.yaml:/etc/mcp-gateway/config.yaml:ro130              - ./data:/data:ro131            restart: unless-stopped132            user: "65532:65532"133            read_only: true134            security_opt:135              - no-new-privileges:true136            cap_drop:137              - ALL138            stop_grace_period: 30s139            logging:140              options:141                max-size: "10m"142                max-file: "3"143        EOF144        ```145146        If you're using the [sample MCP server](https://platform.claude.com/docs/en/agents-and-tools/mcp-tunnels/deploy-compose#optional-use-a-sample-mcp-server), append it as a service:147148        ```bash149        cat >> docker-compose.yaml <<'EOF'150151          hello-mcp:152            image: python:3.13-slim153            working_dir: /app154            volumes:155              - ./hello_server.py:/app/hello_server.py:ro156            command: sh -c "pip install --quiet mcp && python hello_server.py"157            restart: unless-stopped158        EOF159        ```160      </Step>161162      <Step title="Provision the tunnel">163        Set the identifiers. Leave `TUNNEL_ID` unset to have the setup component create a tunnel; set it to attach to an existing tunnel from the [Console](https://platform.claude.com/docs/en/agents-and-tools/mcp-tunnels/console#create-a-tunnel):164165        ```bash166        # export TUNNEL_ID=tnl_...   # set to attach to an existing tunnel167        export ANTHROPIC_FEDERATION_RULE_ID=fdrl_...168        export ANTHROPIC_ORGANIZATION_ID=00000000-0000-0000-0000-000000000000169        ```170171        If your federation rule is scoped to a workspace other than your organization's default, also set `ANTHROPIC_WORKSPACE_ID=wrkspc_...`; the setup component uses the default workspace otherwise. An auto-created tunnel is created in that workspace.172173        Set `ANTHROPIC_IDENTITY_TOKEN` to an OIDC JWT from this host's identity provider. Follow the [WIF guide for your provider](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation#identity-providers) to register the issuer, set the rule's subject, and mint the token; the rule's audience must match the audience you request when minting.174175        Run the setup component:176177        ```bash178        docker compose run --rm setup179        ```180181        `setup init` is idempotent over `data/`: re-running it reuses the tunnel ID and CA already stored there and never creates a second tunnel. A new CA is generated and registered only when `data/` is empty or `TUNNEL_ID` has changed; in that case the cap of two active certificates applies, so revoke one in the Console first if both slots are filled.182183        See [Setup component authentication failures](https://platform.claude.com/docs/en/agents-and-tools/mcp-tunnels/troubleshooting#setup-component-authentication-failures) if it errors.184185        Retrieve your tunnel domain and export it for later steps:186187        ```bash188        export TUNNEL_DOMAIN=$(sudo cat data/tunnel-domain)189        echo "$TUNNEL_DOMAIN"190        ```191192        <Note>193          Workload Identity Federation tokens are short-lived (1 hour by default) and expire automatically; there is nothing to revoke after setup completes.194        </Note>195      </Step>196197      <Step title="Write the proxy config">198        `tunnel_domain` is **required**: the [proxy](https://platform.claude.com/docs/en/agents-and-tools/mcp-tunnels/concepts#components) uses it to strip the domain suffix from incoming hostnames before looking up the subdomain in `routes`. `routes` is a flat map from subdomain to upstream URL, not a list.199200        ```bash201        cat > config/mcp-proxy.yaml <<EOF202        listen_addr: ":8080"203        log_level: info204        shutdown_timeout: 30s205        tunnel_domain: ${TUNNEL_DOMAIN}206        tls:207          cert_file: /data/tls.crt208          key_file: /data/tls.key209        routes:210          echo: http://hello-mcp:9000211        EOF212        ```213214        The `echo:` route targets the [sample MCP server](https://platform.claude.com/docs/en/agents-and-tools/mcp-tunnels/deploy-compose#optional-use-a-sample-mcp-server); replace it with (or add) your own routes. See the [proxy configuration](https://platform.claude.com/docs/en/agents-and-tools/mcp-tunnels/reference#proxy-configuration) reference for all available fields.215      </Step>216217      <Step title="Start the deployment">218        ```bash219        export TUNNEL_TOKEN=$(sudo cat data/tunnel-token)220        docker compose up -d221        ```222      </Step>223    </Steps>224  </Tab>225226  <Tab title="Without programmatic access">227    Use this flow if you didn't turn on **Set up programmatic access**, or for local development and testing. There is no `setup` service.228229    <Steps>230      <Step title="Get the tunnel token and domain from the Console">231        On the tunnel detail page, copy the **Domain** (it has the form `abcd1234.tunnel.anthropic.com`), then click the eye icon next to **Token** to fetch the tunnel token and use the copy icon to copy it.232233        Set both as shell variables for the rest of the guide:234235        ```bash236        export TUNNEL_DOMAIN=YOUR_TUNNEL_DOMAIN_HERE237        export TUNNEL_TOKEN='eyJ...'238        ```239      </Step>240241      <Step title="Scaffold and generate certificates">242        ```bash243        mkdir -p mcp-tunnel/{data,config}244        cd mcp-tunnel245        ```246247        The proxy listens on `:8080` over plain WebSocket; the [inner TLS](https://platform.claude.com/docs/en/agents-and-tools/mcp-tunnels/concepts#components) handshake happens **inside** that WebSocket stream using these certificates. Anthropic verifies the inner handshake against the CA you register in the Console. The server certificate's Subject Alternative Name (SAN) must include `*.<tunnel-domain>` per the [certificate requirements](https://platform.claude.com/docs/en/agents-and-tools/mcp-tunnels/reference#certificate-requirements).248249        ```bash250        # Self-signed CA. Explicit extensions so it satisfies the certificate251        # requirements regardless of distro openssl.cnf defaults.252        openssl req -x509 -newkey rsa:2048 -nodes \253          -keyout data/ca.key -out data/ca.crt \254          -days 3650 -subj "/CN=mcp-tunnel-ca" \255          -addext "basicConstraints=critical,CA:TRUE" \256          -addext "keyUsage=critical,keyCertSign,cRLSign" \257          -addext "subjectKeyIdentifier=hash"258259        # Extension file for the server certificate. Using -extfile (instead of260        # -copy_extensions, which is OpenSSL 3.0+ only) keeps this working on261        # OpenSSL 1.1.x.262        cat > data/tls.ext <<EOF263        subjectAltName = DNS:${TUNNEL_DOMAIN},DNS:*.${TUNNEL_DOMAIN}264        authorityKeyIdentifier = keyid,issuer265        extendedKeyUsage = serverAuth266        EOF267268        # Server certificate signed by the CA269        openssl req -newkey rsa:2048 -nodes \270          -keyout data/tls.key -out /tmp/server.csr \271          -subj "/CN=${TUNNEL_DOMAIN}"272        openssl x509 -req -in /tmp/server.csr \273          -CA data/ca.crt -CAkey data/ca.key -CAcreateserial \274          -out data/tls.crt -days 90 \275          -extfile data/tls.ext276277        # Allow the non-root proxy container (UID 65532) to read the key from278        # the bind mount. Without the world-read bit the container cannot open279        # a host-owned file.280        chmod 644 data/tls.key281        ```282      </Step>283284      <Step title="Register the CA certificate in the Console">285        On the tunnel detail page, scroll to the **Certificates** section and click **Add certificate**. Upload `data/ca.crt` directly with **Choose file** (the modal accepts `.pem`, `.crt`, and `.cer`), or paste its contents:286287        ```bash288        cat data/ca.crt289        ```290291        The tunnel's status flips to **Active** once a certificate is registered. See [Add a CA certificate](https://platform.claude.com/docs/en/agents-and-tools/mcp-tunnels/console#add-a-ca-certificate).292      </Step>293294      <Step title="Write the proxy config">295        `tunnel_domain` is **required**: the proxy uses it to strip the domain suffix from incoming hostnames before looking up the subdomain in `routes`. `routes` is a flat map from subdomain to upstream URL, not a list.296297        ```bash298        cat > config/mcp-proxy.yaml <<EOF299        listen_addr: ":8080"300        log_level: info301        tunnel_domain: ${TUNNEL_DOMAIN}302        tls:303          cert_file: /data/tls.crt304          key_file: /data/tls.key305        routes:306          echo: http://hello-mcp:9000307        EOF308        ```309310        The `echo:` route targets the [sample MCP server](https://platform.claude.com/docs/en/agents-and-tools/mcp-tunnels/deploy-compose#optional-use-a-sample-mcp-server); replace it with (or add) your own routes. See the [proxy configuration](https://platform.claude.com/docs/en/agents-and-tools/mcp-tunnels/reference#proxy-configuration) reference for all available fields.311      </Step>312313      <Step title="Write docker-compose.yaml">314        The `network_mode: "service:mcp-proxy"` setting places [cloudflared](https://platform.claude.com/docs/en/agents-and-tools/mcp-tunnels/concepts#components) in the proxy's network namespace so that `localhost:8080` inside the cloudflared container reaches the proxy. The `--url http://localhost:8080` flag gives cloudflared its forwarding target; without that flag, cloudflared has no route for incoming requests and returns a 503.315316        ```bash317        cat > docker-compose.yaml <<'EOF'318        services:319          cloudflared:320            image: cloudflare/cloudflared@sha256:6b599ca3e974349ead3286d178da61d291961182ec3fe9c505e1dd02c8ac31b0321            # --url is required: no ingress rules are pushed in the manual flow,322            # so without it cloudflared 503s every request.323            command: tunnel --no-autoupdate run --url http://localhost:8080324            environment:325              - TUNNEL_TOKEN326            # Share the proxy's netns so localhost:8080 reaches it.327            network_mode: "service:mcp-proxy"328            restart: unless-stopped329            user: "65532:65532"330            read_only: true331            security_opt:332              - no-new-privileges:true333            cap_drop:334              - ALL335            stop_grace_period: 30s336            logging:337              options:338                max-size: "10m"339                max-file: "3"340341          mcp-proxy:342            image: us-docker.pkg.dev/anthropic-public-registry/images/mcp-proxy@sha256:efb27b299d627e4134815663cb8896641eeaee025d734c0f695582b4df38f013343            volumes:344              - ./config/mcp-proxy.yaml:/etc/mcp-gateway/config.yaml:ro345              - ./data:/data:ro346            restart: unless-stopped347            user: "65532:65532"348            read_only: true349            security_opt:350              - no-new-privileges:true351            cap_drop:352              - ALL353            stop_grace_period: 30s354            logging:355              options:356                max-size: "10m"357                max-file: "3"358        EOF359        ```360361        If you're using the [sample MCP server](https://platform.claude.com/docs/en/agents-and-tools/mcp-tunnels/deploy-compose#optional-use-a-sample-mcp-server), append it as a service:362363        ```bash364        cat >> docker-compose.yaml <<'EOF'365366          hello-mcp:367            image: python:3.13-slim368            working_dir: /app369            volumes:370              - ./hello_server.py:/app/hello_server.py:ro371            command: sh -c "pip install --quiet mcp && python hello_server.py"372            restart: unless-stopped373        EOF374        ```375      </Step>376377      <Step title="Start the deployment">378        ```bash379        docker compose up -d380        ```381      </Step>382    </Steps>383  </Tab>384</Tabs>385386The compose file reads `TUNNEL_TOKEN` from the host environment with no default, so the export must be repeated in every fresh shell and after a reboot.387388For a multi-VM deployment, copy the `mcp-tunnel/` directory to each host, set `TUNNEL_TOKEN`, and run `docker compose up -d`. In the programmatic flow `TUNNEL_TOKEN` is `$(sudo cat data/tunnel-token)`; in the manual flow it's the value you copied from the Console. The same tunnel token and certificates work across all replicas.389390## Verify the deployment391392Verify end to end by calling an [upstream MCP server](https://platform.claude.com/docs/en/agents-and-tools/mcp-tunnels/concepts#components) from Anthropic's side: see [Use the tunneled MCP servers](https://platform.claude.com/docs/en/agents-and-tools/mcp-tunnels/overview#use-the-tunneled-mcp-servers). With the [sample MCP server](https://platform.claude.com/docs/en/agents-and-tools/mcp-tunnels/deploy-compose#optional-use-a-sample-mcp-server), the routed URL is `https://echo.<your-tunnel-domain>/mcp`. If verification fails, see [Troubleshooting](https://platform.claude.com/docs/en/agents-and-tools/mcp-tunnels/troubleshooting).393394## Upgrades395396Run the commands in this section from inside the `mcp-tunnel/` deployment directory.397398### Rotate the tunnel token399400With programmatic access, increment `--token-version` in the `setup` service command, set the Workload Identity Federation identifiers, mint a fresh OIDC JWT, and re-run the setup component:401402```bash403# Edit docker-compose.yaml: increment the integer in the setup service's404# --token-version argument (for example, --token-version=1 to405# --token-version=2). The setup binary refuses to rotate when the value406# hasn't changed.407408# export TUNNEL_ID=tnl_...   # set only if you set it during install409export ANTHROPIC_FEDERATION_RULE_ID=fdrl_...410export ANTHROPIC_ORGANIZATION_ID=00000000-0000-0000-0000-000000000000411# export ANTHROPIC_WORKSPACE_ID=wrkspc_...   # if your rule is workspace-scoped412# Re-mint ANTHROPIC_IDENTITY_TOKEN per the WIF provider guide for your413# environment (it will have expired since install).414export ANTHROPIC_IDENTITY_TOKEN=...415416docker compose run --rm setup417418export TUNNEL_TOKEN=$(sudo cat data/tunnel-token)419docker compose up -d cloudflared420```421422The `--token-version` argument is edited in `docker-compose.yaml` rather than passed on the command line so the new value persists for future runs of the setup component. The setup component authenticates with Workload Identity Federation; there is no API token to revoke.423424Without programmatic access, click **Rotate token** on the tunnel detail page in the Console, then update the `TUNNEL_TOKEN` environment variable on each host and restart cloudflared (`docker compose up -d cloudflared`).425426<Warning>427  Clicking **Rotate token** invalidates the current token immediately. Between that moment and updating `TUNNEL_TOKEN` on every host and restarting cloudflared, any host whose cloudflared restarts (crash, host reboot) cannot reconnect. Update each host promptly after rotating.428</Warning>429430### Certificate renewal431432You're responsible for monitoring expiry and renewing the server certificate before it expires.433434With programmatic access:435436```bash437docker compose run --rm setup renew-cert --output=dir:/data438```439440The CLI arguments replace the `setup` service's `command` (the `init` arguments) but keep its `entrypoint`, so this runs `/setup renew-cert --output=dir:/data`.441442<Tip>443  Pass `--renew-before=720h` to make the command a no-op when more than 30 days of validity remain. This makes it safe to run on a fixed schedule.444</Tip>445446Without programmatic access, sign a new server certificate with your existing CA (the CA registered in the Console doesn't change) and replace `data/tls.crt`. Set `TUNNEL_DOMAIN` first if you're running this from a fresh shell.447448```bash449export TUNNEL_DOMAIN=YOUR_TUNNEL_DOMAIN_HERE450openssl req -new -key data/tls.key -out /tmp/server.csr \451  -subj "/CN=${TUNNEL_DOMAIN}"452openssl x509 -req -in /tmp/server.csr \453  -CA data/ca.crt -CAkey data/ca.key -CAcreateserial \454  -out data/tls.crt -days 90 \455  -extfile data/tls.ext456```457458In either flow the proxy polls `tls.cert_file` and reloads it automatically, so no restart is required.459460## Next steps461462<CardGroup cols={2}>463  <Card title="Use the tunneled MCP servers" icon="link" href="https://platform.claude.com/docs/en/agents-and-tools/mcp-tunnels/overview#use-the-tunneled-mcp-servers">464    Attach an upstream MCP server to a Managed Agent or the Messages API.465  </Card>466467  <Card title="Security" icon="lock" href="https://platform.claude.com/docs/en/agents-and-tools/mcp-tunnels/security">468    Hardening guidance, credential rotation, and breach response.469  </Card>470471  <Card title="Troubleshooting" icon="wrench" href="https://platform.claude.com/docs/en/agents-and-tools/mcp-tunnels/troubleshooting">472    Diagnose connectivity, TLS, and routing issues.473  </Card>474</CardGroup>475
Files main
Menu

Theme