π The fast, Pythonic way to build MCP servers and clients.
Require a startup-URL session for the fastmcp dev apps preview (#5417)
Jeremiah Lowin639a8d3327e4
diff --git a/docs/apps/development.mdx b/docs/apps/development.mdxindex f5c683d14..c27fab931 100644--- a/docs/apps/development.mdx+++ b/docs/apps/development.mdx@@ -23,7 +23,7 @@ Works with both [Interactive Tools](/apps/prefab) and [custom HTML apps](/apps/lfastmcp dev apps server.py```-The dev UI opens at `http://localhost:8080`. Your MCP server runs on port 8000 with auto-reload enabled by default β save a file and the server restarts automatically.+The dev UI opens in your browser on port 8080 through a startup URL that the terminal prints. Each run prints a new URL; open it to use the dev UI in another browser or after closing the tab. Your MCP server runs on port 8000 with auto-reload enabled by default β save a file and the server restarts automatically.## How it works@@ -31,7 +31,7 @@ The dev server does three things:The **picker page** connects to your MCP server, finds all tools with UI metadata, and renders a form for each one. The forms are auto-generated from the tool's input schema β text fields, dropdowns, checkboxes, all wired up.-When you submit a form, the dev server **calls your tool** via the MCP protocol and opens the result in a new tab. The result page loads the tool's UI resource (the Prefab renderer or your custom HTML) inside an AppBridge β the same protocol that real MCP hosts use.+When you submit a form, the dev server **calls your tool** via the MCP protocol and opens the result in a new tab. Each result page comes from a picker launch and stays available, including on reload, until the dev server stops. The result page loads the tool's UI resource (the Prefab renderer or your custom HTML) inside an AppBridge β the same protocol that real MCP hosts use. The resource runs in a sandboxed iframe, so it can't use `localStorage`, open popups, or show `alert` and `confirm` dialogs.A **reverse proxy** on `/mcp` forwards requests from the browser to your MCP server, avoiding CORS issues that would otherwise block the iframe-based renderer from talking to a different port.@@ -57,6 +57,8 @@ fastmcp dev apps server.py:mcp --mcp-port 9000 --dev-port 9090 --no-reload| Host | `--host` | `127.0.0.1` | Interface for both local servers to bind || Log Panel | `--log-panel` / `--no-log-panel` | On | Show or hide the log panel in the dev UI |+With `--host 0.0.0.0`, open the dev UI through `localhost` or an IP address. To reach it by hostname, pass that hostname to `--host`.+## Multiple toolsIf your server has multiple app tools, the picker shows a dropdown. Each tool gets its own form and launch button. The tool's `title` is displayed when available, falling back to the tool name.diff --git a/fastmcp_slim/fastmcp/cli/apps_dev.py b/fastmcp_slim/fastmcp/cli/apps_dev.pyindex 1c7547277..3c5784e44 100644--- a/fastmcp_slim/fastmcp/cli/apps_dev.py+++ b/fastmcp_slim/fastmcp/cli/apps_dev.py@@ -32,6 +32,7 @@ import jsonimport loggingimport osimport re+import secretsimport signalimport sysimport tarfile@@ -46,10 +47,13 @@ import httpcore2import httpx2import uvicornfrom starlette.applications import Starlette+from starlette.middleware import Middlewarefrom starlette.requests import Requestfrom starlette.responses import HTMLResponse, Response, StreamingResponsefrom starlette.routing import Route+from fastmcp.cli.apps_dev_security import DevSessionMiddleware+from fastmcp.utilities.json_schema_type import safe_create_modelfrom fastmcp.utilities.logging import get_loggerlogger = get_logger(__name__)@@ -310,7 +314,7 @@ _HOST_HTML_TEMPLATE = """\</head><body><div id="status">Launching {tool_name}β¦</div>- <iframe id="app-frame"></iframe>+ <iframe id="app-frame" sandbox="allow-scripts allow-forms"></iframe><script type="module">import {{ AppBridge, PostMessageTransport, getToolUiResourceUri }}from "/js/app-bridge.js";@@ -343,14 +347,12 @@ _HOST_HTML_TEMPLATE = """\// (synchronously, before React mounts) so it sends its ui/initialize// request very early β potentially before the iframe's load event fires.// Fix: create the AppBridge and call bridge.connect() BEFORE loading the- // iframe so our window.addEventListener is registered first. We pass- // null as the PostMessageTransport source so early messages from the- // not-yet-known renderer window are not filtered out. After the iframe- // loads we update transport.eventTarget / .eventSource to the real- // renderer window; the load-event microtask always runs before the- // message macrotask, so the response reaches the correct window.+ // iframe so our window.addEventListener is registered first. The+ // iframe's contentWindow stays the same object when the iframe+ // navigates, so the transport accepts messages only from the renderer+ // from the start.const serverCaps = client.getServerCapabilities();- const transport = new PostMessageTransport(iframe.contentWindow, null);+ const transport = new PostMessageTransport(iframe.contentWindow, iframe.contentWindow);const bridge = new AppBridge(client,{{ name: "fastmcp-dev", version: "1.0.0" }},@@ -372,7 +374,16 @@ _HOST_HTML_TEMPLATE = """\);bridge.onopenlink = async ({{ url }}) => {{- window.open(url, "_blank", "noopener,noreferrer");+ // Apps run in an isolated frame; only open external web links on+ // their behalf, never pages of the dev UI itself.+ const target = new URL(url, window.location.href);+ if (+ (target.protocol !== "https:" && target.protocol !== "http:") ||+ target.origin === window.location.origin+ ) {{+ return {{ isError: true }};+ }}+ window.open(target.href, "_blank", "noopener,noreferrer");return {{}};}};bridge.onmessage = async () => ({{}});@@ -384,8 +395,6 @@ _HOST_HTML_TEMPLATE = """\await bridge.sendToolResult(result);status.style.display = "none";iframe.style.display = "block";- // Prevent horizontal scrollbar when vertical scrollbar appears- try {{ iframe.contentDocument.documentElement.style.overflowX = "hidden"; }} catch(e) {{}}}};// Start listening before the iframe loads@@ -396,12 +405,6 @@ _HOST_HTML_TEMPLATE = """\const loaded = new Promise(r => {{ iframe.addEventListener("load", r, {{ once: true }}); }});iframe.src = frameUrl;await loaded;-- // Update transport to the real renderer window. This microtask runs- // before the ui/initialize message macrotask, ensuring the response- // is dispatched to the correct window.- transport.eventTarget = iframe.contentWindow;- transport.eventSource = iframe.contentWindow;}}main().catch(err => {{@@ -898,6 +901,8 @@ _LOG_PANEL_HTML = """\}window.addEventListener("message", function(event) {+ var frame = document.getElementById("app-frame");+ if (!frame || event.source !== frame.contentWindow) return;var data = event.data;if (typeof data === "string") {try { data = JSON.parse(data); } catch(e) { return; }@@ -1028,7 +1033,7 @@ def _model_from_schema(tool_name: str, input_schema: dict[str, Any]) -> type[Any),)- return pydantic.create_model(f"{tool_name.title()}Form", **field_definitions)+ return safe_create_model(f"{tool_name.title()}Form", field_definitions)def _build_picker_html(tools: list[dict[str, Any]]) -> str:@@ -1094,8 +1099,8 @@ def _build_picker_html(tools: list[dict[str, Any]]) -> str:model = _model_from_schema(name, input_schema)form_body: dict[str, Any] = {"tool": name}- for field_name in model.model_fields:- form_body[field_name] = Rx(field_name)+ for field_name, field_info in model.model_fields.items():+ form_body[field_info.alias or field_name] = Rx(field_name)json_body: dict[str, Any] = {"tool": name,@@ -1382,14 +1387,35 @@ async def _fetch_app_bridge_bundle(# ---------------------------------------------------------------------------+# The picker is part of the dev UI; it opens the launch pages /api/launch returns.+_PICKER_OPEN_LINK_JS = """bridge.onopenlink = async ({ url }) => {+ const target = new URL(url, window.location.href);+ if (target.protocol !== "https:" && target.protocol !== "http:") {+ return { isError: true };+ }+ window.location.href = target.href;+ return {};+ };"""++_UNFORWARDED_PROXY_HEADERS = frozenset(+ {"host", "content-length", "cookie", "origin", "referer"}+)++def _make_dev_app(mcp_url: str,app_bridge_js: str,import_map_tag: str,message_log: _MessageLog,log_panel: bool,+ *,+ host: str = "127.0.0.1",+ port: int = 8080,+ session_token: str | None = None,) -> Starlette:- """Build the Starlette dev server application."""+ """Build the authenticated Starlette development host."""+ token = session_token or secrets.token_urlsafe(32)+ launches: dict[str, tuple[str, dict[str, Any]]] = {}async def picker(request: Request) -> HTMLResponse:"""AppBridge host page β loads the picker app in an iframe and wires the bridge."""@@ -1401,7 +1427,7 @@ def _make_dev_app(frame_display="block",mcp_sdk_version=_MCP_SDK_VERSION,iframe_src_json=json.dumps("/picker-app"),- on_open_link="bridge.onopenlink = async ({ url }) => { window.location.href = url; return {}; };",+ on_open_link=_PICKER_OPEN_LINK_JS,on_initialized="bridge.oninitialized = async () => {};",)return (@@ -1415,17 +1441,20 @@ def _make_dev_app(try:raw_tools = await _list_tools(mcp_url)ui_tools = [t for t in raw_tools if _has_ui_resource(t)]- html = _build_picker_html(ui_tools)+ page_html = _build_picker_html(ui_tools)except Exception as exc:logger.exception("Error building picker UI")- html = f"<pre style='padding:2rem;color:red'>Error: {exc}</pre>"- return HTMLResponse(html)+ page_html = f"<pre style='padding:2rem;color:red'>Error: {html.escape(str(exc))}</pre>"+ return HTMLResponse(page_html)async def launch(request: Request) -> HTMLResponse:- """Host page: GET /launch?tool=name&args={...}"""- tool = request.query_params.get("tool", "")- args_raw = request.query_params.get("args", "{}")- tool_args = json.loads(args_raw)+ """Host page: GET /launch?id=... for a launch created by /api/launch."""+ launch = launches.get(request.query_params.get("id", ""))+ if launch is None:+ return HTMLResponse(+ "Unknown launch. Start tools from the dev UI picker.", status_code=404+ )+ tool, tool_args = launchhost_html = _HOST_HTML_TEMPLATE.format(tool_name=html.escape(tool, quote=True),import_map_tag=import_map_tag,@@ -1490,7 +1519,11 @@ def _make_dev_app(except (json.JSONDecodeError, TypeError):passtool_args[k] = v- url = "/launch?" + urlencode({"tool": tool, "args": json.dumps(tool_args)})+ # Launch pages run tools, so their URLs name a stored launch instead+ # of carrying the tool and arguments.+ launch_id = secrets.token_urlsafe(16)+ launches[launch_id] = (tool, tool_args)+ url = "/launch?" + urlencode({"id": launch_id})return Response(content=json.dumps(url),media_type="application/json",@@ -1537,10 +1570,14 @@ def _make_dev_app(except (json.JSONDecodeError, TypeError):pass+ # The dev server has already checked the browser's session and origin.+ # Forward the request as its own, without the browser's cookies or+ # origin headers.headers = {k: vfor k, v in request.headers.items()- if k.lower() not in ("host", "content-length")+ if k.lower() not in _UNFORWARDED_PROXY_HEADERS+ and not k.lower().startswith("sec-fetch-")}# Use a reasonable default timeout to prevent the proxy from hanging@@ -1661,7 +1698,10 @@ def _make_dev_app(proxy_mcp,methods=["GET", "POST", "DELETE", "PUT", "PATCH", "OPTIONS"],),- ]+ ],+ middleware=[+ Middleware(DevSessionMiddleware, host=host, port=port, token=token)+ ],)@@ -1697,6 +1737,8 @@ async def _start_user_server(else:cmd.append("--no-reload")env = {**os.environ, "FASTMCP_LOG_LEVEL": "WARNING"}+ # Validate Host and Origin on the spawned server unless the user chose a mode.+ env.setdefault("FASTMCP_HTTP_HOST_ORIGIN_PROTECTION", "auto")process = await asyncio.create_subprocess_exec(*cmd,env=env,@@ -1738,15 +1780,17 @@ async def run_dev_apps(on *dev_port* (with an /mcp proxy to the user's server), then opensthe browser."""+ # Reach servers bound to every interface through loopback.+ local_host = {"0.0.0.0": "127.0.0.1", "::": "::1"}.get(host, host) # noqa: S104mcp_url = (- f"http://{host}:{mcp_port}/mcp"- if ":" not in host- else f"http://[{host}]:{mcp_port}/mcp"+ f"http://{local_host}:{mcp_port}/mcp"+ if ":" not in local_host+ else f"http://[{local_host}]:{mcp_port}/mcp")dev_url = (- f"http://{host}:{dev_port}"- if ":" not in host- else f"http://[{host}]:{dev_port}"+ f"http://{local_host}:{dev_port}"+ if ":" not in local_host+ else f"http://[{local_host}]:{dev_port}")user_proc: asyncio.subprocess.Process | None = None@@ -1811,10 +1855,25 @@ async def run_dev_apps(if not ready:raise RuntimeError(f"User server did not start on port {mcp_port}")- logger.info(f"FastMCP dev UI at {dev_url}")+ session_token = secrets.token_urlsafe(32)+ startup_url = dev_url + "/?" + urlencode({"token": session_token})+ # Print the URL on its own line so log formatting never wraps it.+ print(f"\nFastMCP dev UI: {startup_url}\n", file=sys.stderr, flush=True)+ if host not in {"127.0.0.1", "localhost", "::1"}:+ logger.warning(+ "The dev UI is bound to a non-loopback interface. "+ "Keep its startup URL private; HTTP does not encrypt the session."+ )dev_app = _make_dev_app(- mcp_url, app_bridge_js, import_map_tag, _MessageLog(), log_panel+ mcp_url,+ app_bridge_js,+ import_map_tag,+ _MessageLog(),+ log_panel,+ host=host,+ port=dev_port,+ session_token=session_token,)config = uvicorn.Config(dev_app,@@ -1830,7 +1889,7 @@ async def run_dev_apps(async def _open_browser() -> None:await asyncio.sleep(0.8)- webbrowser.open(dev_url)+ webbrowser.open(startup_url)await asyncio.gather(server.serve(), _open_browser())diff --git a/fastmcp_slim/fastmcp/cli/apps_dev_security.py b/fastmcp_slim/fastmcp/cli/apps_dev_security.pynew file mode 100644index 000000000..8edb698cf--- /dev/null+++ b/fastmcp_slim/fastmcp/cli/apps_dev_security.py@@ -0,0 +1,168 @@+"""Browser session, Host, and Origin checks for the `fastmcp dev apps` host."""++from __future__ import annotations++import ipaddress+import secrets+from urllib.parse import urlsplit++from starlette.datastructures import Headers+from starlette.requests import Request+from starlette.responses import PlainTextResponse, RedirectResponse+from starlette.types import ASGIApp, Message, Receive, Scope, Send++SESSION_COOKIE = "fastmcp_dev_session"++_LOOPBACK_HOSTS = frozenset({"127.0.0.1", "localhost", "::1"})+_WILDCARD_HOSTS = frozenset({"0.0.0.0", "::"}) # noqa: S104++# Paths that serve server-supplied content. Browsers isolate it in an opaque+# origin with only these capabilities, matching the launch page's iframe.+_SANDBOXED_PATHS = frozenset({"/ui-resource", "/mcp"})+_SANDBOX = "sandbox allow-scripts allow-forms"+# Pages the dev host itself embeds in an iframe.+_FRAMEABLE_PATHS = frozenset({"/picker-app", "/ui-resource"})++# Response headers the dev host controls; backend values are dropped.+_HOST_HEADERS = frozenset(+ {+ b"content-security-policy",+ b"referrer-policy",+ b"cache-control",+ b"x-content-type-options",+ b"set-cookie",+ }+)+++class DevSessionMiddleware:+ """Require a browser session started from the private startup URL.++ `GET /?token=...` with the startup token sets an HttpOnly, SameSite=Strict+ cookie and redirects to `/`. Every other request needs that cookie. The+ cookie holds a separate session secret: browsers send cookies to every+ port on the host, and the startup token must not reach other services. Every+ request must also name this server in its Host header, and browser+ requests must come from this origin: cookies do not distinguish ports on+ the same host, so the Origin and Fetch Metadata headers are checked too.+ """++ def __init__(self, app: ASGIApp, *, host: str, port: int, token: str) -> None:+ self.app = app+ self.host = host.lower()+ self.port = port+ self.token = token+ self.session_secret = secrets.token_urlsafe(32)+ self.cookie_name = f"{SESSION_COOKIE}_{port}"++ def _valid_host(self, headers: Headers) -> bool:+ values = headers.getlist("host")+ if len(values) != 1:+ return False+ value = values[0]+ try:+ authority = urlsplit(f"http://{value}")+ port = authority.port+ except ValueError:+ return False+ if authority.netloc != value or authority.username or authority.password:+ return False+ # Browsers leave the scheme's default port out of the Host header.+ if (port if port is not None else 80) != self.port:+ return False+ hostname = authority.hostname or ""+ if self.host in _WILDCARD_HOSTS:+ # A server bound to every interface accepts literal addresses only;+ # a DNS name could point anywhere.+ if hostname == "localhost":+ return True+ try:+ ipaddress.ip_address(hostname)+ except ValueError:+ return False+ return True+ if self.host in _LOOPBACK_HOSTS:+ return hostname in _LOOPBACK_HOSTS+ return hostname == self.host++ def _same_origin(self, request: Request) -> bool:+ origin = request.headers.get("origin")+ if origin is not None and origin != f"http://{request.headers['host']}":+ return False+ fetch_site = request.headers.get("sec-fetch-site")+ return fetch_site is None or fetch_site in {"same-origin", "none"}++ @staticmethod+ def _matches(value: str, expected: str) -> bool:+ return secrets.compare_digest(value.encode(), expected.encode())++ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:+ if scope["type"] == "websocket":+ # The dev host has no WebSocket endpoints.+ await send({"type": "websocket.close", "code": 1008})+ return+ if scope["type"] != "http":+ await self.app(scope, receive, send)+ return++ request = Request(scope, receive)+ if not self._valid_host(request.headers):+ response = PlainTextResponse("Invalid Host header", status_code=400)+ await response(scope, receive, send)+ return+ if not self._same_origin(request):+ response = PlainTextResponse("Cross-origin request", status_code=403)+ await response(scope, receive, send)+ return++ path = request.url.path+ starting_session = False++ async def send_with_host_headers(message: Message) -> None:+ if message["type"] == "http.response.start":+ headers = [+ (key, value)+ for key, value in message.get("headers", [])+ if key.lower() not in _HOST_HEADERS+ or (starting_session and key.lower() == b"set-cookie")+ ]+ csp = "frame-ancestors " + (+ "'self'" if path in _FRAMEABLE_PATHS else "'none'"+ )+ if path in _SANDBOXED_PATHS:+ csp += f"; {_SANDBOX}"+ headers += [+ (b"content-security-policy", csp.encode()),+ (b"referrer-policy", b"no-referrer"),+ (b"cache-control", b"no-store"),+ (b"x-content-type-options", b"nosniff"),+ ]+ message = {**message, "headers": headers}+ await send(message)++ if path == "/" and request.method == "GET":+ startup_token = request.query_params.get("token")+ if startup_token is not None and self._matches(startup_token, self.token):+ response = RedirectResponse("/", status_code=303)+ response.set_cookie(+ self.cookie_name,+ self.session_secret,+ httponly=True,+ samesite="strict",+ path="/",+ )+ starting_session = True+ await response(scope, receive, send_with_host_headers)+ return++ session = request.cookies.get(self.cookie_name, "")+ if not self._matches(session, self.session_secret):+ response = PlainTextResponse(+ "No dev session. Open the dev UI with the startup URL printed "+ "by `fastmcp dev apps`.",+ status_code=403,+ )+ await response(scope, receive, send_with_host_headers)+ return++ await self.app(scope, receive, send_with_host_headers)diff --git a/loq.toml b/loq.tomlindex fb31aebe9..cce12967e 100644--- a/loq.toml+++ b/loq.toml@@ -24,7 +24,7 @@ max_lines = 2098[[rules]]path = "fastmcp_slim/fastmcp/cli/apps_dev.py"-max_lines = 1814+max_lines = 1933[[rules]]path = "fastmcp_slim/fastmcp/cli/cli.py"@@ -69,3 +69,7 @@ max_lines = 1154[[rules]]path = "fastmcp_slim/fastmcp/utilities/json_schema_type.py"max_lines = 1059++[[rules]]+path = "tests/cli/test_run.py"+max_lines = 1291diff --git a/tests/cli/test_apps_dev_server.py b/tests/cli/test_apps_dev_server.pynew file mode 100644index 000000000..13f48a04d--- /dev/null+++ b/tests/cli/test_apps_dev_server.py@@ -0,0 +1,657 @@+"""Sessions, launches, and app frames in the `fastmcp dev apps` server."""++import html+from typing import Any+from unittest.mock import AsyncMock++import httpx2+import pytest+from starlette.testclient import TestClient+from starlette.websockets import WebSocketDisconnect++import fastmcp.cli.apps_dev as apps_dev++TOKEN = "test-process-session-token"+COOKIE = "fastmcp_dev_session_8080"+++def build_client(*, host: str = "127.0.0.1", session: bool = False) -> TestClient:+ app = apps_dev._make_dev_app(+ "http://127.0.0.1:1/mcp",+ "",+ "",+ apps_dev._MessageLog(),+ False,+ host=host,+ port=8080,+ session_token=TOKEN,+ )+ client = TestClient(app, base_url="http://127.0.0.1:8080")+ if session:+ client.get("/", params={"token": TOKEN})+ return client+++def create_launch(client: TestClient, tool: str = "ping") -> str:+ response = client.post("/api/launch", json={"tool": tool, "value": "x"})+ return response.json()+++class TestSession:+ @pytest.mark.parametrize(+ "method,path",+ [+ ("get", "/"),+ ("get", "/launch?id=x"),+ ("get", "/picker-app"),+ ("get", "/ui-resource?uri=ui://app/view.html"),+ ("get", "/js/app-bridge.js"),+ ("get", "/api/logs"),+ ("post", "/api/logs/bridge"),+ ("post", "/api/logs/clear"),+ ("post", "/api/launch"),+ ("get", "/mcp"),+ ("post", "/mcp"),+ ("delete", "/mcp"),+ ],+ )+ def test_requests_without_session_are_rejected(self, method: str, path: str):+ response = build_client().request(method, path)+ assert response.status_code == 403++ def test_startup_url_starts_session_and_redirects(self):+ client = build_client()++ response = client.get("/", params={"token": TOKEN}, follow_redirects=False)++ assert response.status_code == 303+ assert response.headers["location"] == "/"+ cookie = response.headers["set-cookie"]+ assert cookie.startswith(f"{COOKIE}=")+ assert "HttpOnly" in cookie+ assert "SameSite=strict" in cookie+ assert response.headers["referrer-policy"] == "no-referrer"+ assert client.get("/").status_code == 200+ assert client.get(create_launch(client)).status_code == 200++ def test_session_cookie_differs_from_startup_token(self):+ client = build_client(session=True)++ session = client.cookies.get(COOKIE)++ assert session+ assert TOKEN not in session++ @pytest.mark.parametrize("token", ["wrong", "", "Γ©"])+ def test_wrong_startup_token_starts_no_session(self, token: str):+ response = build_client().get("/", params={"token": token})++ assert response.status_code == 403+ assert "set-cookie" not in response.headers++ @pytest.mark.parametrize(+ "token",+ [+ TOKEN.upper(),+ TOKEN[:-1],+ TOKEN + "x",+ f" {TOKEN}",+ f"{TOKEN} ",+ "εε",+ "wrong",+ "",+ ],+ ids=[+ "uppercase",+ "truncated",+ "extended",+ "leading_space",+ "trailing_space",+ "non_ascii",+ "wrong",+ "empty",+ ],+ )+ def test_startup_token_must_match_exactly(self, token: str):+ client = build_client()++ response = client.get("/", params={"token": token})++ assert response.status_code == 403+ assert "set-cookie" not in response.headers+ assert client.get("/").status_code == 403++ @pytest.mark.parametrize(+ "method,path",+ [("get", "/picker-app"), ("get", "/api/logs"), ("post", "/api/launch")],+ )+ def test_startup_token_only_starts_a_session_from_the_root_page(+ self, method: str, path: str+ ):+ client = build_client()++ response = client.request(method, path, params={"token": TOKEN})++ assert response.status_code == 403+ assert "set-cookie" not in response.headers++ @pytest.mark.parametrize(+ "cookie",+ [+ f"{COOKIE}=wrong",+ f"{COOKIE}=",+ f"{COOKIE}={TOKEN}",+ "fastmcp_dev_session_9999=anything",+ "fastmcp_dev_session=anything",+ ],+ ids=["wrong", "empty", "startup_token", "other_port", "no_port"],+ )+ def test_other_cookie_values_are_not_a_session(self, cookie: str):+ response = build_client().get("/", headers={"Cookie": cookie})++ assert response.status_code == 403++ def test_websocket_connections_are_closed(self):+ with pytest.raises(WebSocketDisconnect) as exc_info:+ with build_client(session=True).websocket_connect("/mcp"):+ pass+ assert exc_info.value.code == 1008+++class TestHostHeader:+ @pytest.mark.parametrize(+ "host",+ [+ "example.com:8080",+ "dev.example.com:8080",+ "127.0.0.1:9000",+ "127.0.0.1",+ "[::1]:9000",+ "192.0.2.2:8080",+ ],+ )+ def test_other_host_headers_are_rejected(self, host: str):+ response = build_client().get(+ "/", params={"token": TOKEN}, headers={"Host": host}+ )++ assert response.status_code == 400+ assert "set-cookie" not in response.headers++ @pytest.mark.parametrize(+ "host",+ [+ "other.example:8080",+ "127.0.0.1.other.example:8080",+ "localhost.other.example:8080",+ "127.0.0.1:9999",+ "127.0.0.1",+ "127.0.0.1:",+ "127.0.0.1:99999",+ "127.0.0.1:http",+ "[::1]:9999",+ "[::1]",+ "127.0.0.1:[email protected]:8080",+ "other.example:[email protected]:8080",+ "127.0.0.1:8080/path",+ "127.0.0.1:8080?name=value",+ "127.0.0.1:8080#fragment",+ "[invalid]:8080",+ "2130706433:8080",+ "127.1:8080",+ "0x7f.0.0.1:8080",+ "[::ffff:127.0.0.1]:8080",+ "localhost.:8080",+ "127.0.0.1.:8080",+ "localhost:8080:8080",+ "127.0.0.1:8080:8080",+ ],+ )+ def test_malformed_or_mismatched_host_values_are_rejected(self, host: str):+ response = build_client().get(+ "/", params={"token": TOKEN}, headers={"Host": host}+ )++ assert response.status_code == 400+ assert "set-cookie" not in response.headers++ @pytest.mark.parametrize("host", ["LOCALHOST:8080", "Localhost:8080"])+ def test_host_names_are_case_insensitive(self, host: str):+ response = build_client().get(+ "/", params={"token": TOKEN}, headers={"Host": host}, follow_redirects=False+ )++ assert response.status_code == 303++ def test_bound_host_name_is_case_insensitive(self):+ response = build_client(host="Dev.Example").get(+ "/",+ params={"token": TOKEN},+ headers={"Host": "DEV.example:8080"},+ follow_redirects=False,+ )++ assert response.status_code == 303++ @pytest.mark.parametrize(+ "second_host", ["127.0.0.1:8080", "other.example:8080"], ids=["same", "other"]+ )+ def test_multiple_host_headers_are_rejected(self, second_host: str):+ response = build_client().get(+ "/",+ params={"token": TOKEN},+ headers=[("Host", "127.0.0.1:8080"), ("Host", second_host)],+ )++ assert response.status_code == 400+ assert "set-cookie" not in response.headers++ @pytest.mark.parametrize(+ "host",+ [+ "other.example:8080",+ "localhost.other.example:8080",+ "192.0.2.2:9999",+ "192.0.2.2",+ "192.0.2.20:8080",+ "192.0.2.2.other.example:8080",+ "192.0.2.2:[email protected]:8080",+ "localhost:8080",+ "[::1]:8080",+ ],+ )+ def test_specific_bind_rejects_other_host_values(self, host: str):+ response = build_client(host="192.0.2.2").get(+ "/", params={"token": TOKEN}, headers={"Host": host}+ )++ assert response.status_code == 400+ assert "set-cookie" not in response.headers++ @pytest.mark.parametrize(+ "host",+ [+ "other.example:8080",+ "localhost.other.example:8080",+ "192.0.2.2:9999",+ "192.0.2.2",+ "2130706433:8080",+ "127.1:8080",+ "0x7f.0.0.1:8080",+ "localhost.:8080",+ "192.0.2.2:[email protected]:8080",+ "192.0.2.2:8080/path",+ ],+ )+ def test_wildcard_bind_rejects_non_literal_and_malformed_hosts(self, host: str):+ response = build_client(host="0.0.0.0").get(+ "/", params={"token": TOKEN}, headers={"Host": host}+ )++ assert response.status_code == 400+ assert "set-cookie" not in response.headers++ @pytest.mark.parametrize(+ "host", ["localhost:8080", "[::1]:8080", "[2001:db8::1]:8080"]+ )+ def test_wildcard_bind_accepts_loopback_names_and_ipv6_literals(self, host: str):+ response = build_client(host="::").get(+ "/", params={"token": TOKEN}, headers={"Host": host}, follow_redirects=False+ )++ assert response.status_code == 303++ def test_default_http_port_accepts_host_without_port(self):+ app = apps_dev._make_dev_app(+ "http://127.0.0.1:1/mcp",+ "",+ "",+ apps_dev._MessageLog(),+ False,+ port=80,+ session_token=TOKEN,+ )+ client = TestClient(app, base_url="http://127.0.0.1")++ startup = client.get("/", params={"token": TOKEN}, follow_redirects=False)+ page = client.get("/", headers={"Origin": "http://127.0.0.1"})++ assert startup.status_code == 303+ assert page.status_code == 200++ @pytest.mark.parametrize("host", ["127.0.0.1:8080", "localhost:8080", "[::1]:8080"])+ def test_loopback_names_are_accepted(self, host: str):+ response = build_client().get(+ "/", params={"token": TOKEN}, headers={"Host": host}, follow_redirects=False+ )+ assert response.status_code == 303++ def test_specific_bind_accepts_only_its_host(self):+ client = build_client(host="192.0.2.2")+ startup = {"token": TOKEN}++ own = client.get(+ "/",+ params=startup,+ headers={"Host": "192.0.2.2:8080"},+ follow_redirects=False,+ )+ other = client.get("/", params=startup, headers={"Host": "127.0.0.1:8080"})++ assert own.status_code == 303+ assert other.status_code == 400++ @pytest.mark.parametrize(+ "host,status",+ [+ ("192.0.2.2:8080", 303),+ ("127.0.0.1:8080", 303),+ ("example.com:8080", 400),+ ],+ )+ def test_wildcard_bind_accepts_literal_addresses(self, host: str, status: int):+ response = build_client(host="0.0.0.0").get(+ "/", params={"token": TOKEN}, headers={"Host": host}, follow_redirects=False+ )+ assert response.status_code == status+++class TestOrigin:+ @pytest.mark.parametrize(+ "headers",+ [+ {"Origin": "http://example.com"},+ {"Origin": "http://127.0.0.1:9000"},+ {"Origin": "null"},+ {"Sec-Fetch-Site": "cross-site"},+ {"Sec-Fetch-Site": "same-site"},+ ],+ )+ def test_launch_page_requires_same_origin(self, headers: dict[str, str]):+ client = build_client(session=True)+ launch_url = create_launch(client)++ response = client.get(launch_url, headers=headers)++ assert response.status_code == 403++ @pytest.mark.parametrize(+ "headers",+ [+ {"Origin": "http://example.com"},+ {"Origin": "http://127.0.0.1:9000"},+ {"Origin": "null"},+ {"Sec-Fetch-Site": "cross-site"},+ {"Sec-Fetch-Site": "same-site"},+ ],+ )+ def test_log_clear_requires_same_origin(self, headers: dict[str, str]):+ client = build_client(session=True)++ response = client.post("/api/logs/clear", content="{}", headers=headers)++ assert response.status_code == 403++ @pytest.mark.parametrize(+ "headers",+ [+ {"Origin": "http://other.example"},+ {"Origin": "http://127.0.0.1:9999"},+ {"Origin": "http://localhost:8080"},+ {"Origin": "http://127.0.0.1"},+ {"Origin": "https://127.0.0.1:8080"},+ {"Origin": "HTTP://127.0.0.1:8080"},+ {"Origin": "http://127.0.0.1:8080/"},+ {"Origin": "http://127.0.0.1:[email protected]"},+ {"Origin": "http://[email protected]:8080"},+ {"Origin": "http://127.0.0.1.other.example:8080"},+ {"Origin": ""},+ {"Origin": "null"},+ {"Origin": "http://127.0.0.1:8080", "Sec-Fetch-Site": "cross-site"},+ {"Origin": "http://127.0.0.1:8080", "Sec-Fetch-Site": "same-site"},+ {"Sec-Fetch-Site": "cross-site"},+ {"Sec-Fetch-Site": "same-site"},+ {"Sec-Fetch-Site": "Cross-Site"},+ {"Sec-Fetch-Site": ""},+ {"Sec-Fetch-Site": "same-origin, cross-site"},+ ],+ )+ @pytest.mark.parametrize(+ "method,path",+ [+ ("get", "/"),+ ("get", "/picker-app"),+ ("get", "/api/logs"),+ ("post", "/api/launch"),+ ("post", "/api/logs/clear"),+ ("post", "/mcp"),+ ],+ )+ def test_cross_origin_requests_are_rejected_on_every_route(+ self, method: str, path: str, headers: dict[str, str]+ ):+ response = build_client(session=True).request(method, path, headers=headers)++ assert response.status_code == 403++ def test_referer_does_not_replace_the_origin_check(self):+ response = build_client(session=True).post(+ "/api/launch",+ json={"tool": "ping", "value": "x"},+ headers={+ "Origin": "http://other.example",+ "Referer": "http://127.0.0.1:8080/",+ },+ )++ assert response.status_code == 403++ @pytest.mark.parametrize(+ "headers",+ [+ {"Origin": "http://127.0.0.1:8080"},+ {"Sec-Fetch-Site": "same-origin"},+ {"Sec-Fetch-Site": "none"},+ {},+ ],+ )+ def test_same_origin_requests_work(self, headers: dict[str, str]):+ response = build_client(session=True).post(+ "/api/launch", json={"tool": "ping", "value": "x"}, headers=headers+ )++ assert response.status_code == 200+ assert response.json().startswith("/launch?id=")++ def test_log_endpoints_work_for_the_session(self):+ client = build_client(session=True)++ client.post("/api/logs/bridge", json={"body": {"method": "legitimate"}})+ logged = client.get("/api/logs").text+ client.post("/api/logs/clear")++ assert "legitimate" in logged+ assert "legitimate" not in client.get("/api/logs").text+++class TestLaunch:+ def test_launch_url_from_picker_opens_launch_page(self):+ client = build_client(session=True)++ response = client.get(create_launch(client, tool="lookup"))++ assert response.status_code == 200+ assert 'const toolName = "lookup";' in response.text++ def test_launch_ignores_tool_and_args_parameters(self):+ client = build_client(session=True)++ response = client.get(+ "/launch",+ params={"tool": "ping", "args": '{"x": 1}'},+ headers={"Sec-Fetch-Site": "none"},+ )++ assert response.status_code == 404+ assert "toolName" not in response.text++ def test_unknown_launch_id_is_rejected(self):+ response = build_client(session=True).get("/launch", params={"id": "unknown"})++ assert response.status_code == 404+++class TestPages:+ def test_picker_error_shows_message_as_text(self, monkeypatch: pytest.MonkeyPatch):+ message = "Expected <list> of items"+ monkeypatch.setattr(+ apps_dev, "_list_tools", AsyncMock(side_effect=ValueError(message))+ )++ response = build_client(session=True).get("/picker-app")++ assert response.status_code == 200+ assert message not in response.text+ assert html.escape(message) in response.text++ def test_ui_resource_runs_sandboxed_when_opened_directly(+ self, monkeypatch: pytest.MonkeyPatch+ ):+ monkeypatch.setattr(+ apps_dev, "_read_mcp_resource", AsyncMock(return_value="<p>app</p>")+ )++ response = build_client(session=True).get("/ui-resource?uri=ui://app/view.html")++ assert response.status_code == 200+ csp = response.headers["content-security-policy"]+ assert "sandbox allow-scripts allow-forms" in csp+ assert "allow-same-origin" not in csp+ assert "frame-ancestors 'self'" in csp++ def test_host_pages_disallow_framing(self):+ response = build_client(session=True).get("/")+ assert response.headers["content-security-policy"] == "frame-ancestors 'none'"++ def test_launch_page_sandboxes_app_frame(self):+ client = build_client(session=True)+ page = client.get(create_launch(client)).text++ assert '<iframe id="app-frame" sandbox="allow-scripts allow-forms">' in page+ assert "new PostMessageTransport(iframe.contentWindow, null)" not in page+ assert "contentDocument" not in page++ def test_launch_page_opens_only_external_web_links(self):+ client = build_client(session=True)+ page = client.get(create_launch(client)).text++ assert 'target.protocol !== "https:"' in page+ assert "target.origin === window.location.origin" in page++ def test_picker_page_opens_only_web_links(self):+ page = build_client(session=True).get("/").text++ assert 'target.protocol !== "https:"' in page+ assert "window.location.href = url;" not in page++ def test_proxy_omits_browser_cookies_and_origin(+ self, monkeypatch: pytest.MonkeyPatch+ ):+ captured: list[httpx2.Request] = []+ original_client = httpx2.AsyncClient++ def backend(request: httpx2.Request) -> httpx2.Response:+ captured.append(request)+ return httpx2.Response(+ 200,+ json={"jsonrpc": "2.0", "id": 1, "result": {}},+ headers={+ "Set-Cookie": f"{COOKIE}=other",+ "Content-Security-Policy": "frame-ancestors *",+ },+ )++ def client_factory(**kwargs: Any) -> httpx2.AsyncClient:+ return original_client(transport=httpx2.MockTransport(backend), **kwargs)++ monkeypatch.setattr(apps_dev.httpx2, "AsyncClient", client_factory)++ response = build_client(session=True).post(+ "/mcp",+ json={"jsonrpc": "2.0", "id": 1, "method": "ping"},+ headers={+ "Origin": "http://127.0.0.1:8080",+ "Referer": "http://127.0.0.1:8080/",+ "Sec-Fetch-Site": "same-origin",+ },+ )++ assert response.status_code == 200+ forwarded = {key.lower() for key in captured[0].headers}+ assert forwarded.isdisjoint({"cookie", "origin", "referer", "sec-fetch-site"})+ assert "set-cookie" not in response.headers+ assert response.headers["content-security-policy"] == (+ "frame-ancestors 'none'; sandbox allow-scripts allow-forms"+ )+++class TestPickerForm:+ @pytest.mark.parametrize(+ "name,field_name",+ [+ ("__base__", "field_base_"),+ ("__config__", "field_config_"),+ ("model_config", "field_model_config"),+ ("_private", "field_private"),+ ("plain", "plain"),+ ],+ )+ def test_form_submits_original_property_names(self, name: str, field_name: str):+ schema = {+ "type": "object",+ "properties": {name: {"type": "string"}},+ "required": [name],+ }++ model = apps_dev._model_from_schema("probe", schema)+ page = apps_dev._build_picker_html(+ [+ {+ "name": "probe",+ "inputSchema": schema,+ "_meta": {"ui": {"resourceUri": "ui://probe/view.html"}},+ }+ ]+ )++ assert list(model.model_fields) == [field_name]+ assert model.model_validate({name: "value"}).model_dump(by_alias=True) == {+ name: "value"+ }+ assert f'"{name}":"{{{{ {field_name} }}}}"' in page+++class TestSpawnedServer:+ async def test_host_origin_protection_defaults_to_auto(+ self, monkeypatch: pytest.MonkeyPatch+ ):+ monkeypatch.delenv("FASTMCP_HTTP_HOST_ORIGIN_PROTECTION", raising=False)+ spawn = AsyncMock()+ monkeypatch.setattr(apps_dev.asyncio, "create_subprocess_exec", spawn)++ await apps_dev._start_user_server("server.py", 8000, reload=False)++ env = spawn.call_args.kwargs["env"]+ assert env["FASTMCP_HTTP_HOST_ORIGIN_PROTECTION"] == "auto"++ async def test_explicit_host_origin_protection_is_kept(+ self, monkeypatch: pytest.MonkeyPatch+ ):+ monkeypatch.setenv("FASTMCP_HTTP_HOST_ORIGIN_PROTECTION", "true")+ spawn = AsyncMock()+ monkeypatch.setattr(apps_dev.asyncio, "create_subprocess_exec", spawn)++ await apps_dev._start_user_server("server.py", 8000, reload=False)++ env = spawn.call_args.kwargs["env"]+ assert env["FASTMCP_HTTP_HOST_ORIGIN_PROTECTION"] == "true"diff --git a/tests/cli/test_run.py b/tests/cli/test_run.pyindex c89c87b17..81b8356d3 100644--- a/tests/cli/test_run.py+++ b/tests/cli/test_run.py@@ -1043,11 +1043,21 @@ class TestRunDevApps:import_map_tag="",message_log=_MessageLog(),log_panel=False,+ session_token="test-dev-session",)- client = TestClient(starlette_app, raise_server_exceptions=False)+ client = TestClient(+ starlette_app,+ base_url="http://127.0.0.1:8080",+ raise_server_exceptions=False,+ )++ client.get("/?token=test-dev-session")payload = "</title><script>alert(1)</script><img src=x onerror=alert(2)>"- response = client.get("/launch", params={"tool": payload, "args": "{}"})+ launch_url = client.post(+ "/api/launch", json={"tool": payload, "__json_args__": "{}"}+ ).json()+ response = client.get(launch_url)assert response.status_code == 200assert payload not in response.text@@ -1065,14 +1075,22 @@ class TestRunDevApps:import_map_tag="",message_log=_MessageLog(),log_panel=False,+ session_token="test-dev-session",+ )+ client = TestClient(+ starlette_app,+ base_url="http://127.0.0.1:8080",+ raise_server_exceptions=False,)- client = TestClient(starlette_app, raise_server_exceptions=False)++ client.get("/?token=test-dev-session")payload = {"name": "</script><script>alert(1)</script>&"}- response = client.get(- "/launch",- params={"tool": "safe_tool", "args": json.dumps(payload)},- )+ launch_url = client.post(+ "/api/launch",+ json={"tool": "safe_tool", "__json_args__": json.dumps(payload)},+ ).json()+ response = client.get(launch_url)assert response.status_code == 200assert json.dumps(payload) not in response.text@@ -1081,17 +1099,23 @@ class TestRunDevApps:'\\u003c/script\\u003e\\u0026"') in response.text- def test_api_launch_encodes_generated_launch_url(self):- """Test /api/launch encodes query parameters in the returned URL."""+ def test_api_launch_stores_launch_behind_generated_url(self):+ """Test /api/launch returns a launch URL that names a stored launch."""starlette_app = _make_dev_app(mcp_url="http://127.0.0.1:8000/mcp",app_bridge_js="// js",import_map_tag="",message_log=_MessageLog(),log_panel=False,+ session_token="test-dev-session",+ )+ client = TestClient(+ starlette_app,+ base_url="http://127.0.0.1:8080",+ raise_server_exceptions=False,)- client = TestClient(starlette_app, raise_server_exceptions=False)+ client.get("/?token=test-dev-session")response = client.post("/api/launch",json={@@ -1103,14 +1127,17 @@ class TestRunDevApps:assert response.status_code == 200url = response.json()query = parse_qs(urlsplit(url).query)- assert query["tool"] == ["tool&name=<script>"]- assert json.loads(query["args"][0]) == {"value": "</script>"}+ assert list(query) == ["id"]+ page = client.get(url).text+ assert "tool&name=<script>" in page+ assert '{"value": "\\u003c/script\\u003e"}' in page@pytest.mark.parametrize("host, expected_host",[- ("0.0.0.0", "0.0.0.0"),+ ("0.0.0.0", "127.0.0.1"),("127.0.0.1", "127.0.0.1"),+ ("192.0.2.2", "192.0.2.2"),],)async def test_run_dev_apps_with_host(self, host, expected_host):@@ -1161,6 +1188,8 @@ class TestRunDevApps:webbrowser_open_first_arg = mock_webbrowser_open.call_args[0][0]assert expected_host in webbrowser_open_first_arg+ assert mock_uvicorn.Config.call_args.kwargs["host"] == host+@pytest.mark.parametrize("log_panel, expected_log_panel",[@@ -1247,9 +1276,14 @@ class TestRunDevApps:import_map_tag="",message_log=mock_message_log,log_panel=log_panel,+ session_token="test-dev-session",+ )+ client = TestClient(+ starlette_app,+ base_url="http://127.0.0.1:8080",+ raise_server_exceptions=False,)- client = TestClient(starlette_app, raise_server_exceptions=False)- client.get("/")+ client.get("/?token=test-dev-session")if log_panel:mock_inject.assert_called_once()