{"id":3137,"date":"2026-11-26T13:09:34","date_gmt":"2026-11-26T13:09:34","guid":{"rendered":"https:\/\/hostry.com\/blog\/?p=3137"},"modified":"2026-11-26T13:09:35","modified_gmt":"2026-11-26T13:09:35","slug":"remote-mcp-server-vps-nginx","status":"publish","type":"post","link":"https:\/\/hostry.com\/blog\/remote-mcp-server-vps-nginx\/","title":{"rendered":"Deploy a Remote MCP Server on a VPS: Python SDK, Nginx and TLS"},"content":{"rendered":"\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1200\" height=\"675\" src=\"https:\/\/hostry.com\/blog\/wp-content\/uploads\/2026\/11\/remote-mcp-server-vps-nginx-cover.webp\" alt=\"Deploy a remote MCP server on a VPS: a courier with a sealed envelope crosses to a server tower through a gatehouse with a padlock, the nginx and TLS layer\" class=\"wp-image-3129\" srcset=\"https:\/\/hostry.com\/blog\/wp-content\/uploads\/2026\/11\/remote-mcp-server-vps-nginx-cover.webp 1200w, https:\/\/hostry.com\/blog\/wp-content\/uploads\/2026\/11\/remote-mcp-server-vps-nginx-cover-300x169.webp 300w, https:\/\/hostry.com\/blog\/wp-content\/uploads\/2026\/11\/remote-mcp-server-vps-nginx-cover-1024x576.webp 1024w, https:\/\/hostry.com\/blog\/wp-content\/uploads\/2026\/11\/remote-mcp-server-vps-nginx-cover-450x253.webp 450w, https:\/\/hostry.com\/blog\/wp-content\/uploads\/2026\/11\/remote-mcp-server-vps-nginx-cover-768x432.webp 768w\" sizes=\"auto, (max-width: 1200px) 100vw, 1200px\" \/><\/figure>\n\n\n\n<pre class=\"wp-block-preformatted\" style=\"font-size:14px\"><em><strong>Your MCP server works on localhost, and you want Claude to reach it over HTTPS without leaving it open. To deploy a remote MCP server on a VPS, run it on 127.0.0.1 under systemd, put nginx with a certificate in front on port 443, and add the public name to the SDK's allowed hosts. A bearer token checked by nginx then works for Claude Code. claude.ai custom connectors offer only OAuth or no sign-in unless your organization has the limited Request headers beta, and the Python SDK, used as a resource server, has no authorization server to finish OAuth.<\/strong><\/em><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The walkthrough builds the token-protected path for Claude Code on one <strong><a href=\"https:\/\/hostry.com\/products\/vps\/\">Linux VPS with root access<\/a><\/strong>. For claude.ai it shows what you must add for OAuth, without completing that flow.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Run with a local test CA: the SDK server, nginx, MCP Inspector, the SDK client and the Claude Code CLI. Syntax-checked only: the systemd unit. From documentation only: certbot issuance, the claude.ai connector, the OAuth provider and the panel firewall. Versions: Ubuntu 24.04, Python 3.12.3, mcp 2.3.0 and 1.30.0, uvicorn 0.54.0, nginx 1.24.0, Inspector 2.16.0 on Node 22.23.4, Claude Code 2.1.332.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The name <span class=\"highlighted\">ops-mcp.example.net<\/span>, the user <code>srvinfo<\/code> and port 8710 are placeholders. The port appears in four places: twice in <code>server_v2.py<\/code> (the <code>resource_server_url<\/code> fallback and <code>run()<\/code>), in the unit&#8217;s <code>ExecStart<\/code> and in the nginx upstream.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"what-you-build\">What you will build, and which Claude client can reach it<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A self-hosted remote MCP server speaks Streamable HTTP, the MCP transport in which each request is an HTTPS POST to one URL and the answer comes back as JSON or an SSE stream. Here the URL is <code>https:\/\/ops-mcp.example.net\/mcp<\/code>. Which Claude client can use it depends on how the client proves who it is.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Client<\/th><th>Connects from<\/th><th>Static bearer token<\/th><th>OAuth sign-in<\/th><\/tr><\/thead><tbody><tr><td>Claude Code (<code>claude mcp add --transport http<\/code>)<\/td><td>Your machine<\/td><td>Yes, with <code>--header<\/code><\/td><td>Yes<\/td><\/tr><tr><td>claude.ai and the Claude apps (custom connector by URL)<\/td><td>Anthropic&#8217;s servers, public IPv4<\/td><td>Only with the Request headers beta, under No sign-in<\/td><td>Yes, through an authorization server you run or rent<\/td><\/tr><tr><td>MCP Inspector CLI (testing)<\/td><td>Your machine<\/td><td>Yes, with <code>--header<\/code><\/td><td>Yes, interactive<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">For most solo setups, Claude Code with a token at nginx fits best: it needs no extra service, and only you hold the token. That is the path built below.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The example tools are <code>uptime_and_load<\/code>, which reads <span class=\"highlighted\">\/proc\/uptime<\/span>, and <code>disk_usage<\/code> for four fixed mount points. Whatever auth you pick, never publish a tool that runs shell commands or accepts a free file path.<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1200\" height=\"800\" src=\"https:\/\/hostry.com\/blog\/wp-content\/uploads\/2026\/11\/remote-mcp-server-vps-nginx-path.webp\" alt=\"Remote MCP server on a VPS: Claude Code and claude.ai reach nginx on port 443, which forwards to the MCP server on 127.0.0.1:8710\" class=\"wp-image-3132\" srcset=\"https:\/\/hostry.com\/blog\/wp-content\/uploads\/2026\/11\/remote-mcp-server-vps-nginx-path.webp 1200w, https:\/\/hostry.com\/blog\/wp-content\/uploads\/2026\/11\/remote-mcp-server-vps-nginx-path-300x200.webp 300w, https:\/\/hostry.com\/blog\/wp-content\/uploads\/2026\/11\/remote-mcp-server-vps-nginx-path-1024x683.webp 1024w, https:\/\/hostry.com\/blog\/wp-content\/uploads\/2026\/11\/remote-mcp-server-vps-nginx-path-450x300.webp 450w, https:\/\/hostry.com\/blog\/wp-content\/uploads\/2026\/11\/remote-mcp-server-vps-nginx-path-768x512.webp 768w\" sizes=\"auto, (max-width: 1200px) 100vw, 1200px\" \/><figcaption>Claude Code sends its own bearer header; claude.ai needs an OAuth authorization server that you run or rent.<\/figcaption><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"requirements\">Requirements for a remote MCP server on a VPS<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">You need a VPS and a hostname you control.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Ubuntu 24.04 with sudo, SSH already locked down as in <strong><a href=\"https:\/\/hostry.com\/blog\/secure-new-linux-vps-first-30-minutes\/\">the first-half-hour hardening steps for a fresh Ubuntu server<\/a><\/strong>.<\/li><li>A DNS A record from <code>ops-mcp.example.net<\/code> to your VPS&#8217;s public IPv4 address. claude.ai connectors are IPv4-only. Any DNS host works, including <strong><a href=\"https:\/\/hostry.com\/products\/dns\/\">Hostry&#8217;s free DNS hosting<\/a><\/strong>.<\/li><li>Python 3.12, the Ubuntu 24.04 default (PyPI lists <code>&gt;=3.10<\/code>).<\/li><li>Node.js 22.23.4+ or 24.22.1+ for MCP Inspector 2.16.0, on the machine you test from. Ubuntu&#8217;s apt Node 18.19.1 fails at run time.<\/li><li>Inbound 22, 80 and 443 only, set in the built-in firewall of the Hostry VPS control panel (or your provider&#8217;s equivalent); 80 serves the certificate check and the HTTPS redirect. Containers can publish ports around UFW, as shown in <strong><a href=\"https:\/\/hostry.com\/blog\/ai-agent-exposed-to-internet-vps\/\">what UFW does not see when an AI agent runs on a VPS<\/a><\/strong>. Not reproduced in the lab.<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">If you still need a server, a <strong><a href=\"https:\/\/hostry.com\/products\/vps\/\">KVM VPS from $6 a month<\/a><\/strong> in any of 18+ locations is enough. The MCP process used about 70-77 MB of memory across two runs.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"write-server\">Write the server with the MCP Python SDK 2.x<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Version 2.0 of the official Python SDK (July 28, 2026) renamed the main class, so v1 examples no longer import. Write against 2.3.0 and set the allowed host names now, because the default rejects every request that comes through a proxy.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>sudo apt update &amp;&amp; sudo apt install -y python3.12-venv nginx certbot python3-certbot-nginx\nsudo useradd --system --home-dir \/opt\/srvinfo-mcp --shell \/usr\/sbin\/nologin srvinfo\nsudo mkdir -p \/opt\/srvinfo-mcp \/etc\/srvinfo-mcp\ncd \/opt\/srvinfo-mcp\nsudo python3.12 -m venv venv2\nsudo venv2\/bin\/pip install \"mcp==2.3.0\"<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Save the server as <span class=\"highlighted\">\/opt\/srvinfo-mcp\/server_v2.py<\/span>. It reads its settings from environment variables, so one file serves every auth path below.<\/p>\n\n\n\n<details class=\"wp-block-details is-layout-flow wp-block-details-is-layout-flow\"><summary>Full file: server_v2.py (109 lines)<\/summary>\n\n<pre class=\"wp-block-code\"><code>\"\"\"srvinfo: a read-only MCP server that reports this VPS's uptime, load and disk use.\n\nmcp==2.3.0 (v2 line). Nothing here runs shell commands or reads arbitrary paths.\nSettings come from environment variables (set in \/etc\/srvinfo-mcp\/env):\n  SRVINFO_ALLOWED_HOSTS   comma list for the Host check, e.g. \"ops-mcp.example.net,ops-mcp.example.net:*\"\n                          empty -&gt; SDK default (localhost-only auto allowlist)\n                          \"off\" -&gt; disable the Host\/Origin check (not recommended)\n  SRVINFO_STATELESS       \"1\" -&gt; stateless_http=True\n  SRVINFO_TOKEN           if set, a static bearer token is required (TokenVerifier)\n  SRVINFO_PUBLIC_URL      public URL of \/mcp, used for OAuth protected-resource metadata\n  SRVINFO_ISSUER          authorization server URL advertised in that metadata\n  SRVINFO_MAX_BODY        max_request_body_size in bytes (SDK default 4 MiB)\n\"\"\"\n\nimport hmac\nimport os\nimport shutil\nimport time\n\nfrom mcp.server.auth.provider import AccessToken, TokenVerifier\nfrom mcp.server.auth.settings import AuthSettings\nfrom mcp.server.mcpserver import MCPServer\nfrom mcp.server.transport_security import TransportSecuritySettings\nfrom starlette.requests import Request\nfrom starlette.responses import JSONResponse\n\n# Only these mount points can be queried; the caller picks from a fixed list.\nALLOWED_MOUNTS = (\"\/\", \"\/var\", \"\/home\", \"\/tmp\")\n\n\nclass StaticTokenVerifier(TokenVerifier):\n    \"\"\"Accept one long random token. Good for Claude Code \/ Inspector, not an OAuth flow.\"\"\"\n\n    def __init__(self, token: str) -&gt; None:\n        self._token = token\n\n    async def verify_token(self, token: str) -&gt; AccessToken | None:\n        if hmac.compare_digest(token, self._token):\n            return AccessToken(token=token, client_id=\"static\", scopes=[\"srvinfo:read\"], expires_at=None)\n        return None\n\n\ntoken = os.environ.get(\"SRVINFO_TOKEN\", \"\")\npublic_url = os.environ.get(\"SRVINFO_PUBLIC_URL\", \"\")\nissuer = os.environ.get(\"SRVINFO_ISSUER\", \"https:\/\/auth.example.net\")\n\nkwargs = {}\nif token:\n    kwargs[\"token_verifier\"] = StaticTokenVerifier(token)\n    kwargs[\"auth\"] = AuthSettings(\n        issuer_url=issuer,\n        resource_server_url=public_url or \"http:\/\/127.0.0.1:8710\/mcp\",\n        required_scopes=[\"srvinfo:read\"],\n    )\n\nmcp = MCPServer(\"srvinfo\", instructions=\"Read-only status of this server.\", **kwargs)\n\n\n@mcp.tool()\ndef uptime_and_load() -&gt; dict:\n    \"\"\"Return uptime in seconds and the 1\/5\/15-minute load averages.\"\"\"\n    with open(\"\/proc\/uptime\") as f:\n        up = float(f.read().split()[0])\n    l1, l5, l15 = os.getloadavg()\n    return {\"uptime_seconds\": round(up), \"load\": [l1, l5, l15], \"cpus\": os.cpu_count(), \"checked_at\": int(time.time())}\n\n\n@mcp.tool()\ndef disk_usage(mount: str = \"\/\") -&gt; dict:\n    \"\"\"Disk use for one of the allowed mount points: \/, \/var, \/home, \/tmp.\"\"\"\n    if mount not in ALLOWED_MOUNTS:\n        raise ValueError(f\"mount must be one of {ALLOWED_MOUNTS}\")\n    u = shutil.disk_usage(mount)\n    return {\"mount\": mount, \"total_gb\": round(u.total \/ 1e9, 1), \"used_pct\": round(100 * u.used \/ u.total, 1)}\n\n\n@mcp.custom_route(\"\/health\", methods=[\"GET\"])\nasync def health(_: Request) -&gt; JSONResponse:\n    return JSONResponse({\"ok\": True})\n\n\ndef _security() -&gt; TransportSecuritySettings | None:\n    raw = os.environ.get(\"SRVINFO_ALLOWED_HOSTS\", \"\").strip()\n    if not raw:\n        return None  # SDK default: auto allowlist for 127.0.0.1\/localhost only\n    if raw == \"off\":\n        return TransportSecuritySettings(enable_dns_rebinding_protection=False)\n    hosts = [h.strip() for h in raw.split(\",\") if h.strip()]\n    origins = [f\"https:\/\/{h}\" for h in hosts if not h.endswith(\":*\")]\n    return TransportSecuritySettings(allowed_hosts=hosts, allowed_origins=origins)\n\n\n# ASGI app for uvicorn (needed for --workers and --proxy-headers)\napp = mcp.streamable_http_app(\n    stateless_http=os.environ.get(\"SRVINFO_STATELESS\") == \"1\",\n    transport_security=_security(),\n    max_request_body_size=int(os.environ.get(\"SRVINFO_MAX_BODY\", 4 * 1024 * 1024)),\n)\n\nif __name__ == \"__main__\":\n    # Simple path without uvicorn CLI flags: host\/port only on run() in v2.\n    # run() builds its own app, so pass the same settings again (the module-level app is not used here).\n    mcp.run(\n        transport=\"streamable-http\",\n        host=\"127.0.0.1\",\n        port=8710,\n        stateless_http=os.environ.get(\"SRVINFO_STATELESS\") == \"1\",\n        transport_security=_security(),\n    )<\/code><\/pre>\n\n<\/details>\n\n\n\n<p class=\"wp-block-paragraph\" style=\"font-size:14px\"><strong>mcp.server.mcpserver vs mcp.server.fastmcp<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Copy a v1 example into a 2.x install and it stops at the first import:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>$ venv2\/bin\/python -c \"from mcp.server.fastmcp import FastMCP\"\nModuleNotFoundError: No module named 'mcp.server.fastmcp'. This is mcp 2.x, where FastMCP was renamed to MCPServer (from mcp.server.mcpserver import MCPServer) and other APIs changed; see the migration guide at https:\/\/py.sdk.modelcontextprotocol.io\/v2\/migration\/#fastmcp-renamed-to-mcpserver or pin 'mcp&lt;2' to keep running v1 code.<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The v1 file (mcp 1.30.0) differs in four places. Besides the import, the v2 constructor takes no host, port or transport options, and <code>transport_security<\/code> moves from <code>mcp.settings<\/code> into <code>streamable_http_app()<\/code>. Host and port go to <code>run()<\/code>; <code>port=<\/code> anywhere else raises <code>TypeError<\/code>. Pin <code>mcp&gt;=2.3,&lt;3<\/code> for this file and <code>mcp&lt;2<\/code> for unmigrated v1 code.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In v2, <code>python server_v2.py<\/code> calls <code>run()<\/code>, which builds a fresh app and ignores settings given to <code>streamable_http_app()<\/code>. The file passes them twice for that reason; the service uses uvicorn and the module-level app.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\" style=\"font-size:14px\"><strong>Set allowed_hosts before nginx<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The SDK checks the Host header to block DNS rebinding and by default accepts only <code>127.0.0.1<\/code>, <code>localhost<\/code> and <code>[::1]<\/code> with a port. Behind nginx with <code>proxy_set_header Host $host<\/code>, requests arrive with the bare public name, so the default answers 421. <strong>The bare name in <code>allowed_hosts<\/code> fixes port 443; <code>ops-mcp.example.net:*<\/code> alone still gets 421<\/strong>, because <code>:*<\/code> needs a port in the header and <code>$host<\/code> never has one:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>v2  | allowed=[ops-mcp.example.net:*] | Host $host      | :443  | HTTP\/2 421 | host_sent=ops-mcp.example.net | Invalid Host header<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">List both forms; mcp 1.30.0 behaved the same. The full matrix sits in the errors section. Do not pass <code>host=\"0.0.0.0\"<\/code> to the SDK: that switches the check off, and any Host got 200.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"service\">Run it as a service on 127.0.0.1<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The service runs as the unprivileged <code>srvinfo<\/code> user and restarts after a crash. It listens on the loopback address only, so nothing outside the VPS can reach port 8710.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>sudo install -m 640 -o root -g srvinfo \/dev\/null \/etc\/srvinfo-mcp\/env\nsudoedit \/etc\/srvinfo-mcp\/env<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code># \/etc\/srvinfo-mcp\/env   chown root:srvinfo, chmod 640\nSRVINFO_ALLOWED_HOSTS=ops-mcp.example.net,ops-mcp.example.net:*\n# SRVINFO_TOKEN=&lt;token from openssl rand -hex 32&gt;\n# SRVINFO_PUBLIC_URL=https:\/\/ops-mcp.example.net\/mcp\n# SRVINFO_ISSUER=https:\/\/auth.example.net\n# SRVINFO_STATELESS=1<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Save the unit as <span class=\"highlighted\">\/etc\/systemd\/system\/srvinfo-mcp.service<\/span>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>[Unit]\nDescription=srvinfo MCP server (read-only status tools)\nAfter=network.target\n\n[Service]\nUser=srvinfo\nGroup=srvinfo\nWorkingDirectory=\/opt\/srvinfo-mcp\nEnvironmentFile=\/etc\/srvinfo-mcp\/env\nExecStart=\/opt\/srvinfo-mcp\/venv2\/bin\/uvicorn server_v2:app --host 127.0.0.1 --port 8710\nRestart=on-failure\nRestartSec=3\nNoNewPrivileges=true\nProtectSystem=strict\nProtectHome=read-only\nPrivateTmp=true\n\n[Install]\nWantedBy=multi-user.target<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>sudo systemctl daemon-reload\nsudo systemctl enable --now srvinfo-mcp\ncurl -s -w \" %{http_code}\\n\" http:\/\/127.0.0.1:8710\/health<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{\"ok\":true} 200<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">After any later change to the env file or the unit, run <code>sudo systemctl daemon-reload &amp;&amp; sudo systemctl restart srvinfo-mcp<\/code>. To confirm the loopback-only bind, <code>sudo ss -ltnp | grep 8710<\/code> should list <code>127.0.0.1:8710<\/code> and nothing on <code>0.0.0.0<\/code>. The unit passed <code>systemd-analyze verify<\/code> but was never started: the lab had no systemd, so the same command ran as <code>srvinfo<\/code> via <code>runuser<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>\/health<\/code> is a custom route and skips the Host check. An MCP request to <code>127.0.0.1<\/code> does not, because an explicit <code>allowed_hosts<\/code> list removes the localhost defaults. For local checks, send the public name:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>curl -i http:\/\/127.0.0.1:8710\/mcp -H \"Host: ops-mcp.example.net\" \\\n  -H 'Content-Type: application\/json' -H 'Accept: application\/json, text\/event-stream' \\\n  -d '{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2025-11-25\",\"capabilities\":{},\"clientInfo\":{\"name\":\"curl\",\"version\":\"8\"}}}'<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>(without -H \"Host: ...\")\nHTTP\/1.1 421 Misdirected Request\nInvalid Host header\n\n(with it)\nHTTP\/1.1 200 OK\ncontent-type: text\/event-stream\nmcp-session-id: 75df211e02254b089adacd900fa4ef5a\nx-accel-buffering: no<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"nginx-tls\">Nginx reverse proxy and TLS for the MCP server<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">nginx holds the certificate, answers on 443 and passes each request to <code>127.0.0.1:8710<\/code>. The site goes live with the token check already on. Get the certificate first, because the site file points at files certbot creates.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>sudo certbot certonly --nginx -d ops-mcp.example.net\nsudo certbot renew --dry-run<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Issuance was not reproduced (no public DNS in the lab); the commands follow the certbot documentation. Next, generate a token with <code>openssl rand -hex 32<\/code> and put it in <span class=\"highlighted\">\/etc\/nginx\/conf.d\/mcp-token.conf<\/span>, readable by root only:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># \/etc\/nginx\/conf.d\/mcp-token.conf   chmod 600, owner root (nginx master reads it as root)\nmap_hash_bucket_size 128;\nmap $http_authorization $mcp_token_ok {\n    default 0;\n    \"Bearer &lt;token from openssl rand -hex 32&gt;\" 1;\n}<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>sudo chmod 600 \/etc\/nginx\/conf.d\/mcp-token.conf<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Save the site as <span class=\"highlighted\">\/etc\/nginx\/sites-available\/srvinfo-mcp<\/span> and uncomment the <code>if ($mcp_token_ok = 0)<\/code> line in <code>location \/mcp<\/code> before you enable it. If you chose No sign-in or the OAuth path, leave that line commented and skip the token file.<\/p>\n\n\n\n<details class=\"wp-block-details is-layout-flow wp-block-details-is-layout-flow\"><summary>Full file: srvinfo-mcp nginx site (44 lines)<\/summary>\n\n<pre class=\"wp-block-code\"><code># \/etc\/nginx\/sites-available\/srvinfo-mcp   (nginx 1.24 from Ubuntu 24.04 apt)\n# The two ssl_ files are created by \"certbot certonly --nginx\" before this site is enabled.\nupstream srvinfo_mcp {\n    server 127.0.0.1:8710;\n    keepalive 16;\n}\n\nserver {\n    listen 80;\n    server_name ops-mcp.example.net;\n    return 301 https:\/\/$host$request_uri;\n}\n\nserver {\n    listen 443 ssl http2;              # \"http2 on;\" needs nginx 1.25.1+, 1.24 rejects it\n    server_name ops-mcp.example.net;\n\n    ssl_certificate     \/etc\/letsencrypt\/live\/ops-mcp.example.net\/fullchain.pem;\n    ssl_certificate_key \/etc\/letsencrypt\/live\/ops-mcp.example.net\/privkey.pem;\n\n    client_max_body_size 4m;           # nginx default is 1m; SDK's own limit is 4 MiB\n\n    location \/mcp {\n        # optional static token at nginx (map in \/etc\/nginx\/conf.d\/mcp-token.conf):\n        # if ($mcp_token_ok = 0) { add_header WWW-Authenticate \"Bearer\" always; return 401; }\n        proxy_pass http:\/\/srvinfo_mcp;\n        proxy_http_version 1.1;\n        proxy_set_header Connection \"\";\n        proxy_set_header Host $host;                 # bare name -&gt; matches allowed_hosts \"ops-mcp.example.net\"\n        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n        proxy_set_header X-Forwarded-Proto $scheme;  # keeps redirects on https; uvicorn trusts the loopback proxy\n        proxy_buffering off;                          # SDK SSE responses already send X-Accel-Buffering: no\n        proxy_cache off;\n        proxy_read_timeout 120s;                      # matters for json_response=True; SSE pings every 15 s\n    }\n\n    location = \/health { proxy_pass http:\/\/srvinfo_mcp; proxy_set_header Host $host; }\n\n    location \/.well-known\/oauth-protected-resource {\n        proxy_pass http:\/\/srvinfo_mcp;\n        proxy_set_header Host $host;\n        proxy_set_header X-Forwarded-Proto $scheme;\n    }\n}<\/code><\/pre>\n\n<\/details>\n\n\n\n<pre class=\"wp-block-code\"><code>sudo ln -s \/etc\/nginx\/sites-available\/srvinfo-mcp \/etc\/nginx\/sites-enabled\/\nsudo nginx -t &amp;&amp; sudo systemctl reload nginx<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Three lines in that file answer errors from the lab. <code>listen 443 ssl http2;<\/code> is there because nginx 1.24 rejects the newer form, which needs 1.25.1:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>nginx: [emerg] unknown directive \"http2\" in \/opt\/lab\/nginx\/sites\/srvinfo-mcp.conf:10\nnginx: configuration file \/opt\/lab\/nginx\/nginx.conf test failed<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>client_max_body_size 4m<\/code> matches the SDK&#8217;s own 4 MiB request limit. At nginx&#8217;s default of 1 MiB, a 2 MiB tool call never reached the server:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>### nginx client_max_body_size 1m\nbody 0.5 MiB -&gt; HTTP\/2 200\nbody 2 MiB   -&gt; HTTP\/2 413  server: nginx\/1.24.0 (Ubuntu) &lt;title&gt;413 Request Entity Too Large&lt;\/title&gt;\n### nginx client_max_body_size 8m\nbody 2 MiB   -&gt; HTTP\/2 200\nbody 5 MiB   -&gt; HTTP\/2 413  Request body too large        (plain text from the SDK)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>X-Forwarded-Proto<\/code> keeps redirects on HTTPS; uvicorn 0.54 trusts it from <code>127.0.0.1<\/code> without flags. If nginx connects from another address (a Docker bridge, another VM), add <code>--forwarded-allow-ips<\/code> with that address. Otherwise the trailing-slash redirect points to <code>http:\/\/<\/code> and the SDK client refuses it (seen with a lab variant mounted at <code>\/mcp\/<\/code>).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\" style=\"font-size:14px\"><strong>Streaming, buffering and the 60-second timeout<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">By default the SDK answers tool calls as SSE, a response that stays open and carries messages as they come. On those responses <code>proxy_buffering<\/code> made no difference, because the SDK sends <code>X-Accel-Buffering: no<\/code>. A 70-second tool also finished under nginx&#8217;s default 60-second <code>proxy_read_timeout<\/code>, thanks to a ping every 15 seconds. Only <code>json_response=True<\/code> hit the timeout:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>### json_response=True, proxy_read_timeout 60s, slow_check 70 s (with or without progress):\nt= 60.1s HTTP\/2 504\nnginx error log: upstream timed out (110: Connection timed out) while reading response header from upstream<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">With JSON responses, set the timeout above your slowest tool. The 120 s in the site file is an untested starting value. <code>proxy_buffering off<\/code> stays because it costs nothing.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Check the result from outside the VPS. The trailing-slash POST should come back as a redirect to <code>\/mcp<\/code> on HTTPS:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>curl -sI http:\/\/ops-mcp.example.net\/mcp\ncurl -s https:\/\/ops-mcp.example.net\/health\ncurl -si https:\/\/ops-mcp.example.net\/mcp\/ -H \"Authorization: Bearer &lt;token&gt;\" \\\n  -H 'Content-Type: application\/json' -H 'Accept: application\/json, text\/event-stream' \\\n  -d '{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2025-11-25\",\"capabilities\":{},\"clientInfo\":{\"name\":\"curl\",\"version\":\"8\"}}}'<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>$ curl -sI http:\/\/ops-mcp.example.net\/mcp\nHTTP\/1.1 301 Moved Permanently\nLocation: https:\/\/ops-mcp.example.net\/mcp\n$ curl -s https:\/\/ops-mcp.example.net\/health\n{\"ok\":true}\n(POST initialize to \/mcp\/)\nHTTP\/2 307\nlocation: https:\/\/ops-mcp.example.net\/mcp<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">These lines were recorded with the token check off; with the right header the request passes nginx the same way.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"auth\">Authentication: a bearer token for Claude Code, OAuth for claude.ai<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The token check you just enabled serves Claude Code and the Inspector, which can send a header. claude.ai needs OAuth or No sign-in, each with different settings.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Claude Code only: a token checked by nginx<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Keep the <code>map_hash_bucket_size 128<\/code> line.<\/strong> At nginx 1.24&#8217;s default of 64, any map key over 46 characters fails the config test. &#8220;Bearer &#8221; plus a hex token is 71 characters; with a base64 token it is 51:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>nginx: [emerg] could not build map_hash, you should increase map_hash_bucket_size: 64\nnginx: configuration file \/opt\/lab\/nginx\/nginx.conf test failed\n\nkey length 46 -&gt; successful\nkey length 47 -&gt; could not build map_hash\nkey length 51 (\"Bearer \" + openssl rand -base64 32) -&gt; could not build map_hash\nkey length 71 (\"Bearer \" + openssl rand -hex 32)    -&gt; could not build map_hash<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">With the line in place, no header got <code>401<\/code> with <code>www-authenticate: Bearer<\/code>, a wrong token 401, the right one 200. Read the <code>nginx -t<\/code> output every time: after a failed test the reload is refused and nginx keeps the old config, here one without any token check.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">An <code>if ($http_authorization != \"Bearer ...\")<\/code> test also works but leaves the token in a world-readable file.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">claude.ai: what the SDK gives and what you must add<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">claude.ai signs in with OAuth, and the SDK covers only the resource-server half. On this path the nginx token check must stay off: with it on, clients get nginx&#8217;s bare <code>www-authenticate: Bearer<\/code> 401 and never see the SDK&#8217;s <code>resource_metadata<\/code> pointer. Set <code>SRVINFO_TOKEN<\/code>, <code>SRVINFO_PUBLIC_URL<\/code> and <code>SRVINFO_ISSUER<\/code> in the env file and restart. <code>SRVINFO_TOKEN<\/code> switches the SDK&#8217;s auth on, and the demo verifier accepts only that value. The SDK then answers:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>POST \/mcp, no token \/ wrong token:\nHTTP\/2 401\nwww-authenticate: Bearer error=\"invalid_token\", error_description=\"Authentication required\", resource_metadata=\"https:\/\/ops-mcp.example.net\/.well-known\/oauth-protected-resource\/mcp\"\n\nGET \/.well-known\/oauth-protected-resource\/mcp -&gt; HTTP\/2 200, application\/json\n{ \"resource\": \"https:\/\/ops-mcp.example.net\/mcp\", \"authorization_servers\": [\"https:\/\/auth.example.net\"],\n  \"scopes_supported\": [\"srvinfo:read\"], \"bearer_methods_supported\": [\"header\"] }\nGET \/.well-known\/oauth-authorization-server    404\nGET \/.well-known\/openid-configuration          404\nGET \/register 404   GET \/authorize 404   GET \/token 404<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">An OAuth client follows that chain to the advertised authorization server and stops there (the Inspector: <code>getaddrinfo ENOTFOUND auth.example.net<\/code>). The <strong><a href=\"https:\/\/py.sdk.modelcontextprotocol.io\/run\/authorization\/\" target=\"_blank\" rel=\"noopener\">SDK&#8217;s authorization page<\/a><\/strong> confirms the server &#8220;never issues a token&#8221;, and advises new servers against its built-in <code>auth_server_provider<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">So claude.ai needs an identity provider you run or rent, such as Keycloak or Auth0. <strong><a href=\"https:\/\/claude.com\/docs\/connectors\/building\/troubleshooting\" target=\"_blank\" rel=\"noopener\">Anthropic&#8217;s connector troubleshooting page<\/a><\/strong> lists three groups of requirements. For registration, the provider needs Dynamic Client Registration, Client ID Metadata Documents or a pre-registered client. For the token flow, it must advertise S256 PKCE and answer <code>\/token<\/code> within 10 seconds. For the network, it must be reachable from Anthropic&#8217;s egress range.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Then replace <code>StaticTokenVerifier<\/code> with one that checks the provider&#8217;s tokens, and change the <code>if token:<\/code> condition that turns auth on. Set <code>validate_token_resource=True<\/code> if the provider binds tokens to your URL (otherwise check <code>aud<\/code> in the verifier); unset, 2.3.0 warns at startup and skips that check. This path was not built in the lab.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">No sign-in, and the Request headers beta<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">With No sign-in, anyone who learns the URL can call the tools. Choose it only if you accept that a stranger can read this server&#8217;s uptime, load and disk use. If your organization&#8217;s <strong><a href=\"https:\/\/claude.com\/docs\/connectors\/custom\/add-unlisted\" target=\"_blank\" rel=\"noopener\">Add custom connector dialog<\/a><\/strong> shows a Request headers section, keep the nginx token on instead. Choose No sign-in, pick the <code>authorization<\/code> header and enter <code>Bearer <\/code> plus the token, since Claude adds no prefix. That section is a beta &#8220;available to a limited set of organizations&#8221;.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"test\">Test with the Inspector CLI<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Run the Inspector from a machine outside the VPS before you add the server to Claude. It performs the MCP handshake and calls the tools through nginx and TLS.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>npm i @modelcontextprotocol\/inspector@2.16.0\nnpx mcp-inspector --cli https:\/\/ops-mcp.example.net\/mcp --transport http \\\n  --header \"Authorization: Bearer &lt;token&gt;\" --method tools\/list\nnpx mcp-inspector --cli https:\/\/ops-mcp.example.net\/mcp --transport http \\\n  --header \"Authorization: Bearer &lt;token&gt;\" --protocol-era modern \\\n  --method tools\/call --tool-name disk_usage --tool-arg mount=\/var<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>{ \"_meta\": { \"io.modelcontextprotocol\/serverInfo\": { \"name\": \"srvinfo\", \"version\": \"\" } },\n  \"content\": [ { \"type\": \"text\", \"text\": \"{\\n  \\\"mount\\\": \\\"\/var\\\",\\n  \\\"total_gb\\\": 270.6,\\n  \\\"used_pct\\\": 14.2\\n}\" } ], \"isError\": false }<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Without the header, the Inspector does not say the token is missing. It prints <code>{\"error\":{\"code\":\"auth_required\",\"message\":\"Interactive OAuth requires a TTY on stdin or stderr (or MCP_AUTO_OPEN_ENABLED=true). ...\"}}<\/code>. The lab set <code>NODE_EXTRA_CA_CERTS<\/code> for its local CA; a Let&#8217;s Encrypt certificate needs nothing. A mount outside the allowlist returns <code>\"Error executing tool disk_usage\"<\/code>. With apt Node 18 the Inspector stops at <code>Error running MCP Inspector: CustomEvent is not defined<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\" style=\"font-size:14px\"><strong>Optional: protocol diagnostics with the SDK client<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The SDK client is useful when you need to force a protocol era, as in the workers section. It takes the URL, a mode (<code>legacy<\/code>, <code>auto<\/code> or <code>2026-07-28<\/code>) and an optional token. Install the SDK in a venv on your own machine (<code>pip install \"mcp==2.3.0\"<\/code>), activate it, and run the script with that venv&#8217;s <code>python<\/code>.<\/p>\n\n\n\n<details class=\"wp-block-details is-layout-flow wp-block-details-is-layout-flow\"><summary>Full file: client_v2.py (34 lines)<\/summary>\n\n<pre class=\"wp-block-code\"><code>\"\"\"SDK client check (mcp==2.3.0): connect, list tools, call both tools.\n\nusage: client_v2.py URL [legacy|auto|2026-07-28] [TOKEN]\nCA file for the lab's local CA: env LAB_CA (on a real VPS with Let's Encrypt you do not need it).\n\"\"\"\n\nimport asyncio\nimport os\nimport ssl\nimport sys\n\nimport httpx2\nfrom mcp import Client\nfrom mcp.client.streamable_http import streamable_http_client\n\n\nasync def main() -&gt; None:\n    url = sys.argv[1]\n    mode = sys.argv[2] if len(sys.argv) &gt; 2 else \"auto\"\n    token = sys.argv[3] if len(sys.argv) &gt; 3 else \"\"\n    ctx = ssl.create_default_context(cafile=os.environ[\"LAB_CA\"]) if os.environ.get(\"LAB_CA\") else True\n    headers = {\"Authorization\": f\"Bearer {token}\"} if token else {}\n    http = httpx2.AsyncClient(verify=ctx, headers=headers, trust_env=False, timeout=httpx2.Timeout(30, read=300))\n    async with http:\n        async with Client(streamable_http_client(url, http_client=http), mode=mode) as client:\n            print(\"protocol_version:\", client.protocol_version)\n            tools = await client.list_tools()\n            print(\"tools:\", [t.name for t in tools.tools])\n            for name, args in ((\"uptime_and_load\", {}), (\"disk_usage\", {\"mount\": \"\/\"})):\n                r = await client.call_tool(name, args)\n                print(name, \"-&gt;\", r.structured_content or r.content[0].text)\n\n\nasyncio.run(main())<\/code><\/pre>\n\n<\/details>\n\n\n\n<pre class=\"wp-block-code\"><code>$ python client_v2.py https:\/\/ops-mcp.example.net\/mcp legacy\nprotocol_version: 2025-11-25\ntools: ['uptime_and_load', 'disk_usage']\nuptime_and_load -&gt; { \"uptime_seconds\": 701, \"load\": [0.39, 0.25, 0.12], \"cpus\": 2, \"checked_at\": 1795682723 }\ndisk_usage -&gt; { \"mount\": \"\/\", \"total_gb\": 270.6, \"used_pct\": 14.0 }<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The block is condensed; 2.3.0 prints each result as indented JSON. When something fails, read <code>journalctl -u srvinfo-mcp<\/code> first: on a 421 the client printed only <code>Server returned an error response<\/code>, while the server log named the rejected Host.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"connect\">Connect the remote MCP server to Claude<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Claude Code connects from your machine with one command. claude.ai connects from Anthropic&#8217;s servers, so the VPS must pass public-reachability checks first.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>claude mcp add --transport http srvinfo https:\/\/ops-mcp.example.net\/mcp \\\n  --header \"Authorization: Bearer &lt;token from openssl rand -hex 32&gt;\"\nclaude mcp list<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>srvinfo: https:\/\/ops-mcp.example.net\/mcp (HTTP) - \u221a Connected<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">That line came from Claude Code 2.1.332 against this setup with the nginx token on. The <strong><a href=\"https:\/\/code.claude.com\/docs\/en\/mcp\" target=\"_blank\" rel=\"noopener\">Claude Code MCP documentation<\/a><\/strong> covers the scopes and the <code>\/mcp<\/code> status view. Avoid <code>--scope project<\/code> with a token, because it writes a shared <code>.mcp.json<\/code>. If Claude Code itself lives on a headless server, <strong><a href=\"https:\/\/hostry.com\/blog\/claude-code-codex-login-headless-vps\/\">signing in to Claude Code without a browser on the VPS<\/a><\/strong> comes first.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">claude.ai was not tested; these steps follow Anthropic&#8217;s docs. Open Customize &gt; Connectors &gt; Add custom connector, enter the URL without a trailing slash and choose the authentication mode. On Team and Enterprise an Owner adds it under Organization settings &gt; Connectors; Free allows one custom connector. Before you click Add, check:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li><code>dig +short ops-mcp.example.net<\/code> from outside returns only your public IPv4; a private, CGNAT or IPv6-only answer fails before nginx sees anything.<\/li><li><code>curl -sI https:\/\/ops-mcp.example.net\/mcp<\/code> shows no redirect to another host. Claude drops the <code>Authorization<\/code> header on such a redirect.<\/li><li>nginx serves MCP on 443. In <strong><a href=\"https:\/\/github.com\/anthropics\/claude-ai-mcp\/issues\/373\" target=\"_blank\" rel=\"noopener\">issue #373 of the claude-ai-mcp tracker<\/a><\/strong>, a maintainer said the claude.ai backend only egresses on port 443; the official pages say nothing about ports.<\/li><li>A CDN, WAF or IP allowlist in front of nginx lets in 160.79.104.0\/21 and 153.61.208.0\/20, Anthropic&#8217;s outbound ranges on its IP address reference page.<\/li><li>For OAuth, <code>\/.well-known\/oauth-protected-resource\/mcp<\/code> returns 200, and so does the authorization server&#8217;s metadata.<\/li><\/ol>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"workers\">When to run more than one MCP worker<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Keep one uvicorn worker on a personal server. More workers break older clients, because each worker keeps its sessions in its own memory and a follow-up on another worker is unknown there.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">With <code>--workers 2<\/code>, clients on the 2025-11-25 protocol (the legacy era) failed at random, while 2026-07-28 clients, which send no session ID at all, passed:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>mode=legacy runs=10 ok=6 fail=4\n  first error: mcp.shared.exceptions.MCPError: Session not found\nmode=2026-07-28 runs=10 ok=10 fail=0\nserver log: Rejected request with unknown or expired session ID: b877bab0f1dd4c1aac9ee4acabdf305a\n            INFO:     127.0.0.1:0 - \"POST \/mcp HTTP\/1.1\" 404 Not Found<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Hashing on the session header in nginx across two processes <strong>does not give sticky sessions<\/strong>: <code>initialize<\/code> carries no <code>Mcp-Session-Id<\/code> yet, so it lands on any process, and later requests may hash to the other one.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>### upstream { hash $http_mcp_session_id consistent; ... }\nmode=legacy runs=10 ok=9 fail=1\ninspector era=legacy runs=10 ok=4 fail=6<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">If you do need several workers, stateless mode fixed the error in the lab. It has a price for legacy clients: the <strong><a href=\"https:\/\/py.sdk.modelcontextprotocol.io\/run\/deploy\/\" target=\"_blank\" rel=\"noopener\">SDK deployment page<\/a><\/strong> says &#8220;the cost is the server-to-client back-channel (sampling, push elicitation, <code>roots\/list<\/code>) and resumability&#8221;. These two tools use none of that. Set <code>SRVINFO_STATELESS=1<\/code> in the env file, add <code>--workers 2<\/code> to <code>ExecStart<\/code>, then reload and restart the unit:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>mode=legacy runs=10 ok=10 fail=0\nmode=2026-07-28 runs=5 ok=5 fail=0\ninspector era=legacy runs=20 ok=20 fail=0<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>ip_hash<\/code> also passed, but only because every test came from one address. Which protocol era claude.ai speaks is not documented, so plan for legacy clients.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"errors\">Fix MCP 421 and Session not found errors<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Each row is a message from the lab with its cause and the fix that worked there.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Symptom<\/th><th>Cause<\/th><th>Fix<\/th><\/tr><\/thead><tbody><tr><td><code>421 Misdirected Request<\/code>, <code>Invalid Host header<\/code><\/td><td>Public name missing from <code>allowed_hosts<\/code>, only the <code>:*<\/code> form listed, or no <code>Host<\/code> line in nginx<\/td><td>List the bare name and <code>name:*<\/code>; keep <code>proxy_set_header Host $host<\/code><\/td><\/tr><tr><td><code>404<\/code>, <code>-32600<\/code> <code>Session not found<\/code><\/td><td>Several workers or processes, legacy-era client<\/td><td>One worker, or <code>stateless_http=True<\/code>; header hashing does not help<\/td><\/tr><tr><td><code>could not build map_hash<\/code><\/td><td>Token key over 46 characters at bucket size 64<\/td><td><code>map_hash_bucket_size 128;<\/code><\/td><\/tr><tr><td>HTML <code>413 Request Entity Too Large<\/code><\/td><td>nginx default 1 MiB body limit<\/td><td><code>client_max_body_size 4m;<\/code><\/td><\/tr><tr><td><code>504 Gateway Time-out<\/code> at 60 s<\/td><td><code>json_response=True<\/code> with a slow tool<\/td><td>Keep SSE, or raise <code>proxy_read_timeout<\/code><\/td><\/tr><tr><td><code>CustomEvent is not defined<\/code><\/td><td>Inspector 2.16.0 on Node 18<\/td><td>Node 22.23.4+ or 24.22.1+<\/td><\/tr><tr><td><code>No module named 'mcp.server.fastmcp'<\/code><\/td><td>v1 code on mcp 2.x<\/td><td>Port to <code>MCPServer<\/code>, or pin <code>mcp&lt;2<\/code><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">The full 421 matrix below sends initialize through nginx on 443 and on a test listener at 8443; 1.30.0 and 2.3.0 gave identical rows. With no <code>proxy_set_header Host<\/code> line at all, nginx sends the upstream name and the log prints <code>Invalid Host header: srvinfo_mcp<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>allowed_hosts                                Host var     :443          :8443\n[] (SDK default, localhost only)             $host        421           421\n[]                                           $http_host   421           421   (sent \"ops-mcp.example.net:8443\")\n[ops-mcp.example.net]                        $host        200           200   (port stripped)\n[ops-mcp.example.net]                        $http_host   200           421   (sent \"ops-mcp.example.net:8443\")\n[ops-mcp.example.net:*]                      $host        421           421   (\":*\" needs a port to be present)\n[ops-mcp.example.net:*]                      $http_host   421           200\n[ops-mcp.example.net, ops-mcp.example.net:*] $host        200           200\n[ops-mcp.example.net, ops-mcp.example.net:*] $http_host   200           200<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"upkeep\">Keep it running<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">To rotate the token, put a new value in <span class=\"highlighted\">mcp-token.conf<\/span>, run <code>sudo nginx -t &amp;&amp; sudo systemctl reload nginx<\/code>, then remove and re-add the server in Claude Code with the new header. Keep the SDK pinned to <code>mcp&gt;=2.3,&lt;3<\/code>. Upgrade inside the venv, restart the unit and repeat the Inspector check before you rely on it again.<\/p>\n<!-- AddThis Advanced Settings generic via filter on the_content --><!-- AddThis Share Buttons generic via filter on the_content -->","protected":false},"excerpt":{"rendered":"<p>A read-only MCP server on Python SDK 2.3.0 behind nginx 1.24 and TLS, with the auth path chosen by client: a token at nginx for Claude Code, OAuth or &#8230;<\/p>\n","protected":false},"author":6,"featured_media":3130,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"hb_lab_versions":"","hb_offer_kicker":"","hb_offer_title":"","hb_offer_text":"","footnotes":""},"categories":[1,131],"tags":[],"class_list":["post-3137","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-virtual-private-server","category-ai-automation"],"read_time":15,"_links":{"self":[{"href":"https:\/\/hostry.com\/blog\/wp-json\/wp\/v2\/posts\/3137","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/hostry.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/hostry.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/hostry.com\/blog\/wp-json\/wp\/v2\/users\/6"}],"replies":[{"embeddable":true,"href":"https:\/\/hostry.com\/blog\/wp-json\/wp\/v2\/comments?post=3137"}],"version-history":[{"count":1,"href":"https:\/\/hostry.com\/blog\/wp-json\/wp\/v2\/posts\/3137\/revisions"}],"predecessor-version":[{"id":3140,"href":"https:\/\/hostry.com\/blog\/wp-json\/wp\/v2\/posts\/3137\/revisions\/3140"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/hostry.com\/blog\/wp-json\/wp\/v2\/media\/3130"}],"wp:attachment":[{"href":"https:\/\/hostry.com\/blog\/wp-json\/wp\/v2\/media?parent=3137"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hostry.com\/blog\/wp-json\/wp\/v2\/categories?post=3137"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hostry.com\/blog\/wp-json\/wp\/v2\/tags?post=3137"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}