Host a remote MCP server over Streamable HTTP.
A remote MCP server is an ordinary web app with one endpoint, usually /mcp, that accepts JSON-RPC over HTTP POST and answers with JSON or a short SSE stream. Build it with the official TypeScript or Python SDK, allow your public hostname so the SDK’s rebinding check doesn’t reject it, require a token, and deploy it like any other app.
Facts checked
What the current spec asks of a server
The MCP specification’s 2026-07-28 revision changed Streamable HTTP in ways that make hosting simpler. Protocol-level sessions and the standalone GET stream are gone: every request is its own POST and carries its own protocol version. A server that keeps nothing in memory between requests survives a restart or a cold start without the client noticing. Most tutorials still describe the 2025 shape, with Mcp-Session-Id and a GET stream.
| Rule (2026-07-28) | What it means for your server |
|---|---|
| One MCP endpoint that accepts POST † | Usually /mcp. Each JSON-RPC request is a separate POST. |
Reply with application/json or text/event-stream † | A plain JSON object, or an SSE stream scoped to that one request (progress first, then the result). |
Headers MCP-Protocol-Version, Mcp-Method, Mcp-Name † | Mirrors of the body; a mismatch is 400 with JSON-RPC error -32020 (HeaderMismatch). The SDKs handle this. |
| No sessions, no GET stream † | A server that speaks only this revision answers GET or DELETE with 405 and ignores Mcp-Session-Id and Last-Event-ID. |
Validate Origin † | A present but invalid Origin must get 403, to block DNS rebinding. |
Send X-Accel-Buffering: no on SSE † | Tells proxies not to buffer the stream. Long streams should send a : comment line as a keep-alive. |
| Authorization is optional; over HTTP it’s OAuth 2.1 † | If you implement it: Protected Resource Metadata (RFC 9728), 401 with WWW-Authenticate, tokens checked for your server as audience, never passed through. |
† Competitor details come from each vendor’s own published pages on the dates shown; prices and plans change, so check the vendor before you decide. One MCP endpoint that accepts POST (2026-11-23) · Reply with `application/json` or `text/event-stream` (2026-11-23) · Headers `MCP-Protocol-Version`, `Mcp-Method`, `Mcp-Name` (2026-11-23) · No sessions, no GET stream (2026-11-23) · Validate `Origin` (2026-11-23) · Send `X-Accel-Buffering: no` on SSE (2026-11-23) · Authorization is optional; over HTTP it’s OAuth 2.1 (2026-11-23)
The two official SDKs
Both SDKs still serve 2025-era clients, which open with initialize; we tested that both examples below answer it. createMcpHandler() answers them without sessions. In Python, stateless_http only affects that 2025 path: without it, the SDK keeps a 2025 session in process memory. The example passes stateless_http=True, so a restart breaks nothing and a one-off curl works without a session ID.
| SDK | Packages | HTTP entry point | Default host check |
|---|---|---|---|
| TypeScript v2 † † | @modelcontextprotocol/server, plus /express, /node, /hono or /fastify | createMcpHandler() builds a fresh server per request (stateless) | createMcpExpressApp() binds 127.0.0.1 and accepts only localhost Host and Origin values; anything else gets 403. Set allowedHosts and allowedOrigins for a public hostname |
Python v2 (mcp) † † | mcp (the class is MCPServer, formerly FastMCP) | mcp.streamable_http_app() for uvicorn, or mcp.run(transport="streamable-http") | Accepts only localhost Host values; anything else gets 421 Misdirected Request. A disallowed Origin gets 403 |
† Competitor details come from each vendor’s own published pages on the dates shown; prices and plans change, so check the vendor before you decide. TypeScript v2 (2026-11-23) · TypeScript v2 (2026-11-23) · Python v2 (`mcp`) (2026-11-23) · Python v2 (`mcp`) (2026-11-23)
A Node server
This is the Express example from the TypeScript SDK’s docs with two additions: the public hostname in allowedHosts and allowedOrigins, and a bearer-token check. Versions are the ones this example was tested with. Canner runs the start script and passes the port in PORT (Node docs).
npm install @modelcontextprotocol/server@2.4.0 @modelcontextprotocol/express@2.0.2 \
@modelcontextprotocol/node@2.1.2 express@5.3.0 zod@4.6.7
# package.json needs: "type": "module", "scripts": { "start": "node server.js" }
// server.js
import { timingSafeEqual } from 'node:crypto';
import { createMcpExpressApp } from '@modelcontextprotocol/express';
import { toNodeHandler } from '@modelcontextprotocol/node';
import { createMcpHandler, McpServer } from '@modelcontextprotocol/server';
import * as z from 'zod/v4';
// A fresh server per request: nothing to lose on a restart or a wake-up.
const handler = createMcpHandler(() => {
const server = new McpServer({ name: 'notes', version: '1.0.0' });
server.registerTool(
'add-note',
{ description: 'Append a note', inputSchema: z.object({ text: z.string() }) },
async ({ text }) => ({ content: [{ type: 'text', text: `Saved: ${text}` }] })
);
return server;
});
// The proxy forwards the public Host header, so allow it explicitly.
// CANNER_URL is https://your-project.canner.app (or the preview's URL).
const publicHost = new URL(process.env.CANNER_URL ?? 'http://localhost').hostname;
const extraHosts = (process.env.MCP_HOSTS ?? '').split(',').filter(Boolean); // custom domains
const hosts = [publicHost, ...extraHosts];
const app = createMcpExpressApp({ host: '0.0.0.0', allowedHosts: hosts, allowedOrigins: hosts });
if (!process.env.MCP_TOKEN) throw new Error('MCP_TOKEN is not set');
const expected = Buffer.from(`Bearer ${process.env.MCP_TOKEN}`);
function requireToken(req, res, next) {
const got = Buffer.from(req.headers.authorization ?? '');
if (got.length !== expected.length || !timingSafeEqual(got, expected)) {
return res.status(401).set('WWW-Authenticate', 'Bearer').end();
}
next();
}
const node = toNodeHandler(handler);
app.all('/mcp', requireToken, (req, res) => void node(req, res, req.body));
app.listen(Number(process.env.PORT ?? 3000));A Python server
With uvicorn in requirements.txt and the app in main.py, Canner detects an ASGI app and starts uvicorn main:app on the assigned port. The SDK’s ASGI app is wrapped in a few lines that check the token.
# requirements.txt
mcp==2.3.0
uvicorn==0.54.0
# main.py (Canner starts it with: python -m uvicorn main:app --host 127.0.0.1 --port $PORT)
import hmac
import os
from urllib.parse import urlparse
from mcp.server import MCPServer
from mcp.server.transport_security import TransportSecuritySettings
mcp = MCPServer("Bookshop")
@mcp.tool()
def search_books(query: str) -> str:
"""Search the catalog by title or author."""
return f"Found 3 books matching {query!r}."
# Without this, every request through the proxy gets 421 "Invalid Host header".
host = urlparse(os.environ.get("CANNER_URL", "http://localhost")).hostname
security = TransportSecuritySettings(allowed_hosts=[host, f"{host}:*"])
# stateless_http=True: 2025-era clients get no session either, so a restart loses nothing.
mcp_app = mcp.streamable_http_app(stateless_http=True, transport_security=security)
TOKEN = os.environ["MCP_TOKEN"].encode()
async def app(scope, receive, send):
"""Check a bearer token on /mcp, pass everything else (lifespan included) through."""
if scope["type"] == "http" and scope["path"].startswith("/mcp"):
auth = dict(scope["headers"]).get(b"authorization", b"")
if not hmac.compare_digest(auth, b"Bearer " + TOKEN):
await send({"type": "http.response.start", "status": 401,
"headers": [(b"www-authenticate", b"Bearer")]})
await send({"type": "http.response.body", "body": b""})
return
await mcp_app(scope, receive, send)The 421 that only happens once deployed
Both SDKs protect against DNS rebinding by checking the Host header, and by default they accept only localhost. That is right on a laptop and wrong behind any reverse proxy. A request to your-project.canner.app arrives with that hostname in Host, and it is rejected before any MCP code runs. The Python SDK answers 421 Misdirected Request with a plain-text “Invalid Host header” body and logs the hostname. The TypeScript Express app answers 403 with a JSON-RPC error, “Invalid Host: your-project.canner.app”. Either way the client usually reports only a generic transport error.
The fix is to list the hostnames you serve: allowedHosts (and allowedOrigins, for browser clients) in TypeScript, TransportSecuritySettings(allowed_hosts=[...]) in Python, where host and host:* are separate entries. Read the hostname from CANNER_URL rather than hard-coding it, so previews work too, and add custom domains through an environment variable such as MCP_HOSTS (environment variables).
Auth: a token now, OAuth when other people sign in
The spec makes authorization optional. For a server only you or your team use, a long random token in an environment variable, sent as Authorization: Bearer …, is enough, provided the client lets you set a header. Generate it with openssl rand -hex 32, store it as MCP_TOKEN, and compare it in constant time as the examples do. Canner’s own remote MCP server works this way, with a scoped cnr_ token.
When other people connect with their own accounts, follow the spec’s OAuth 2.1 profile. Your server becomes a resource server: it publishes Protected Resource Metadata at /.well-known/oauth-protected-resource, answers 401 with a WWW-Authenticate header pointing there, and accepts only tokens issued for it as the audience. It must never forward a client’s token to another API. The TypeScript SDK ships helpers for this (requireBearerAuth and mcpAuthMetadataRouter); the authorization server itself can be any OAuth provider.
Deploy it on Canner
- Create a project and push the repo, or upload the folder. No Dockerfile: Canner detects Node or Python from
package.jsonorrequirements.txt. - Set `MCP_TOKEN` in the project’s environment variables before the first deploy, or both examples stop at startup (Python with a
KeyError). - Leave `/` unrouted if you like. The health check requests
/and accepts any status below 500, so the404an MCP-only app returns there counts as up. To check a real route instead, set the health check path in Settings → Build (health check). - Point the client at
https://your-project.canner.app/mcpwith the bearer token, and test with curl first:
curl -s -X POST https://your-project.canner.app/mcp \
-H "Authorization: Bearer $MCP_TOKEN" \
-H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
# 200 with your tools in an SSE "message" event: working
# 401: the token in MCP_TOKEN and the one you sent differ
# 421 "Invalid Host header" (Python) or 403 "Invalid Host" (Node): the Host check (see above)What happens when a sleeping server gets a tool call
On Starter, a project sleeps after 3 hours without a request. Any request wakes it, POST included. For a POST, Canner starts the app, waits up to about 10 seconds for it to answer, then forwards the original request, body intact (up to 2 MB), and streams the reply back. The client sees one slow response, not a redirect. If the app isn’t up in time, the client gets 503 with Retry-After: 5.
That works well with a stateless server, because nothing was lost while it slept. One thing to keep in mind: the first call after a wake is cut if the app sends nothing for 30 seconds, so return a quick result or stream progress. If you leave sessions on for 2025-era clients, they lose them on every wake and have to start over.
If an agent depends on the server answering right away, use Live: it keeps 2 projects always on, and more cost $4 a month each. Every production deploy still stops the old process before starting the new one, so expect a short gap during a deploy (deploy docs).
Long tools, private back ends, and a model of your own
- Tools that run for minutes belong on a job queue, not in one long request. Have the tool call enqueue the work and return an ID, and a second tool report the result. A separate Worker project (no web server, no health check) can run the queue, with Postgres as the queue (background jobs). MCP also defines an optional Tasks extension for long-running operations, if your clients support it.
- An MCP server in front of an internal API. Projects in one organization can call each other over the server without the public internet: each deploy gets
CANNER_PRIVATE_URL_<PROJECT>for the others (private connections). Keep checking a shared secret on the private side, and remember a sleeping Starter project doesn’t answer there until its public address wakes it. - Tools that need a language model can use Canner’s AI endpoints: attach one to the project and
OPENAI_BASE_URLandOPENAI_API_KEYare set on the next deploy. The models run on processors in Montréal, so a tool that summarises or classifies should stream progress or go through the job queue above.
When Canner is the wrong host for it
Canner runs one process per project in one region, with no Redis. A stateless MCP server fits that, and one process doesn’t need a shared event bus: the SDK’s default in-process bus delivers subscriptions/listen notifications. A server that has to run as several instances sharing those notifications needs a pub/sub system behind the SDK’s ServerEventBus (its docs use Redis), and Canner doesn’t offer one. Neither does it offer failover to a second region.
Questions
What is the difference between Streamable HTTP and the old HTTP+SSE transport?
HTTP+SSE (2024-11-05) used a GET stream plus a separate POST endpoint and is deprecated. Streamable HTTP uses one endpoint; since 2026-07-28 every request is its own POST with no session, answered with JSON or a request-scoped SSE stream.
Why does my MCP server return 421 Misdirected Request after deploying?
The Python SDK’s DNS-rebinding protection accepts only localhost Host headers by default, and behind a proxy the Host is your public hostname. Add it to allowed_hosts. The TypeScript SDK’s Express app does the same check but answers 403; the fix there is allowedHosts.
Do I need OAuth for a remote MCP server?
No. Authorization is optional in the spec. A bearer token in an environment variable is fine for a server you and your team use; use the spec’s OAuth 2.1 flow when other people connect with their own accounts.
Can a remote MCP server run on a free plan that sleeps?
Yes, if it is stateless. On Canner Starter a tool call wakes the app and is forwarded once it answers, usually within seconds. Live keeps two projects always on for servers that must answer instantly.
Related
- GuideA support chatbot that answers from your docs
- GuideContent moderation and spam filtering with calibrated labels
- GuideSemantic and hybrid search in Postgres
- GuideRelated articles, recommendations and reranking
- GuideTriage support tickets and email automatically
- GuideExtract invoice and form data into Postgres
Host your MCP server in Montréal.
Deploy it like any web app, free on Starter. Move to Live to keep it always on.