""" The MCP server and its ASGI app (v2.15.0, ADR-075) Stateless Streamable HTTP with plain JSON responses: every request stands alone, so any number of uvicorn workers can serve it and nothing is lost on restart. """ from typing import Optional from urllib.parse import urlparse from flask import Flask from mcp.server import MCPServer from mcp.server.auth.settings import AuthSettings from mcp.server.transport_security import TransportSecuritySettings from pydantic import AnyHttpUrl from starlette.applications import Starlette from starpunk.mcp_server.auth import StarPunkTokenVerifier from starpunk.mcp_server.tools import register_tools INSTRUCTIONS = """\ StarPunk is an IndieWeb site: a personal blog of short notes and longer articles, owned by one person. Notes are Markdown. A note whose first line is '# Heading' is an article with that title. Notes can be drafts (unpublished) or published; publishing may crosspost them to social networks chosen with syndicate_to (see get_site_config). Prefer drafts unless the owner asked to publish. Deleting is a soft delete that undelete_note reverses. """ def _site(app: Flask) -> str: return app.config["SITE_URL"].rstrip("/") def create_mcp_server(app: Flask) -> MCPServer: """The MCP server, with StarPunk's tools and token checks""" site = _site(app) server = MCPServer( name="StarPunk", instructions=INSTRUCTIONS, website_url=site, version=app.config.get("VERSION", ""), token_verifier=StarPunkTokenVerifier(app), auth=AuthSettings( # Same string as the issuer in /.well-known/oauth-authorization-server issuer_url=AnyHttpUrl(site + "/"), resource_server_url=AnyHttpUrl(site + "/mcp"), # Tools check their own scopes; any StarPunk token may connect required_scopes=[], validate_token_resource=True, ), ) register_tools(server, app) return server def _transport_security(app: Flask) -> TransportSecuritySettings: """Only requests for this site's host and from its origin (DNS rebinding)""" site = urlparse(_site(app)) hosts = [site.netloc] origins = [f"{site.scheme}://{site.netloc}"] if app.config.get("DEV_MODE"): hosts += ["localhost:*", "127.0.0.1:*"] origins += ["http://localhost:*", "http://127.0.0.1:*"] return TransportSecuritySettings( enable_dns_rebinding_protection=True, allowed_hosts=hosts, allowed_origins=origins, ) def create_asgi_app(app: Optional[Flask] = None) -> Starlette: """ ASGI app serving /mcp and its protected resource metadata Args: app: The Flask app to call into. Built from the environment if not given, with background workers off (the main app runs those). """ if app is None: from starpunk import create_app app = create_app({"BACKGROUND_WORKERS_ENABLED": False}) server = create_mcp_server(app) return server.streamable_http_app( streamable_http_path="/mcp", stateless_http=True, json_response=True, # Base64 photos for upload_media: 10 MB of image is ~14 MB encoded max_request_body_size=16 * 1024 * 1024, transport_security=_transport_security(app), )