From 5ca58735ebc8ca56f3aa1fea74023825e96ff53c Mon Sep 17 00:00:00 2001 From: Piers Date: Sun, 15 Feb 2026 03:54:43 +0000 Subject: [PATCH] Add Streamable HTTP transport, bearer auth, and Docker deployment - Enable stateless_http + json_response on FastMCP for scalable HTTP serving without sticky sessions (Traefik-friendly) - Add MCP_TRANSPORT env var to select stdio (default) vs streamable-http - Add bearer token auth middleware (MCP_AUTH_TOKEN) with /health bypass - Add Dockerfile (Python 3.12-slim + uv) and docker-compose.yml with Traefik v2/v3 labels, ACME TLS, and health check routing - Add .env.example with multi-instance config for mini/tn-sb/tn-mr2/p-mba - Add uvicorn + starlette as runtime dependencies Co-Authored-By: Claude Opus 4.6 --- .env.example | 23 ++++++++++++++++++++ .gitignore | 1 + Dockerfile | 25 +++++++++++++++++++++ docker-compose.yml | 37 +++++++++++++++++++++++++++++++ pyproject.toml | 2 ++ src/syncthing_mcp/__main__.py | 41 +++++++++++++++++++++++++++++++++-- src/syncthing_mcp/auth.py | 33 ++++++++++++++++++++++++++++ src/syncthing_mcp/server.py | 16 +++++++++++++- 8 files changed, 175 insertions(+), 3 deletions(-) create mode 100644 .env.example create mode 100644 Dockerfile create mode 100644 docker-compose.yml create mode 100644 src/syncthing_mcp/auth.py diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..0c93b0d --- /dev/null +++ b/.env.example @@ -0,0 +1,23 @@ +# ── Syncthing MCP — environment variables ────────────────────────── +# +# Copy this file to .env and fill in real values before deployment. + +# Domain used by Traefik for the ACME certificate and Host() rule. +DOMAIN=example.com + +# Bearer token that clients must send as "Authorization: Bearer ". +# Generate one with: openssl rand -hex 32 +MCP_AUTH_TOKEN=CHANGEME + +# ── Syncthing instances ───────────────────────────────────────────── +# JSON object keyed by friendly name. Each entry needs url + api_key. +# +# NOTE: From inside the Docker network, use the Docker hostname or +# host-gateway IP for instances running on the same machine. +# For remote instances, use their LAN / Tailscale / WireGuard address. +SYNCTHING_INSTANCES='{ + "mini": {"url": "http://mini.local:8384", "api_key": "MINI_API_KEY"}, + "tn-sb": {"url": "http://host.docker.internal:8384", "api_key": "SB_API_KEY"}, + "tn-mr2": {"url": "http://tn-mr2.local:8384", "api_key": "MR2_API_KEY"}, + "p-mba": {"url": "http://p-mba.local:8384", "api_key": "MBA_API_KEY"} +}' diff --git a/.gitignore b/.gitignore index 861787f..aea4ba1 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,4 @@ dist/ .DS_Store *.old .pytest_cache/ +.env diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..392748a --- /dev/null +++ b/Dockerfile @@ -0,0 +1,25 @@ +FROM python:3.12-slim AS base + +WORKDIR /app + +# Install uv for fast dependency resolution. +COPY --from=ghcr.io/astral-sh/uv:latest /uv /usr/local/bin/uv + +# Copy project metadata first for layer caching. +COPY pyproject.toml ./ +COPY src/ src/ + +# Install the package and all runtime dependencies. +RUN uv pip install --system --no-cache . + +# Default to streamable-http transport in container. +ENV MCP_TRANSPORT=streamable-http +ENV MCP_HOST=0.0.0.0 +ENV MCP_PORT=8000 + +EXPOSE 8000 + +HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \ + CMD ["python", "-c", "import httpx; httpx.get('http://localhost:8000/health').raise_for_status()"] + +ENTRYPOINT ["syncthing-mcp"] diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..273ae33 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,37 @@ +--- +# Syncthing MCP — Streamable HTTP deployment behind Traefik +# +# Deploy on tn-sb (or any Docker host with Traefik already running). +# Copy .env.example to .env and fill in API keys before starting. + +services: + syncthing-mcp: + build: . + container_name: syncthing-mcp + restart: unless-stopped + env_file: .env + environment: + MCP_TRANSPORT: streamable-http + MCP_HOST: "0.0.0.0" + MCP_PORT: "8000" + # MCP_AUTH_TOKEN is set in .env + # SYNCTHING_INSTANCES is set in .env + expose: + - "8000" + networks: + - traefik + labels: + # --- Traefik v2 / v3 labels --- + traefik.enable: "true" + traefik.http.routers.syncthing-mcp.rule: Host(`syncthing-mcp.${DOMAIN:?set DOMAIN in .env}`) + traefik.http.routers.syncthing-mcp.entrypoints: websecure + traefik.http.routers.syncthing-mcp.tls.certresolver: letsencrypt + traefik.http.services.syncthing-mcp.loadbalancer.server.port: "8000" + + # Health check route (Traefik can use this for backends). + traefik.http.services.syncthing-mcp.loadbalancer.healthcheck.path: /health + traefik.http.services.syncthing-mcp.loadbalancer.healthcheck.interval: 30s + +networks: + traefik: + external: true diff --git a/pyproject.toml b/pyproject.toml index dedcadd..2b578ab 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -7,6 +7,8 @@ dependencies = [ "mcp[cli]>=1.0.0", "httpx>=0.27.0", "pydantic>=2.0.0", + "uvicorn>=0.30.0", + "starlette>=0.37.0", ] [project.scripts] diff --git a/src/syncthing_mcp/__main__.py b/src/syncthing_mcp/__main__.py index c9e1fd3..e894736 100644 --- a/src/syncthing_mcp/__main__.py +++ b/src/syncthing_mcp/__main__.py @@ -1,10 +1,47 @@ """Entry point for `python -m syncthing_mcp` and the `syncthing-mcp` console script.""" -from syncthing_mcp.server import mcp +import os +import sys def main() -> None: - mcp.run() + transport = os.environ.get("MCP_TRANSPORT", "stdio").strip().lower() + + if transport == "streamable-http": + _run_http() + else: + from syncthing_mcp.server import mcp + + mcp.run() + + +def _run_http() -> None: + """Start the Streamable HTTP server with optional bearer-token auth.""" + from syncthing_mcp.server import mcp + + host = os.environ.get("MCP_HOST", "0.0.0.0") + port = int(os.environ.get("MCP_PORT", "8000")) + token = os.environ.get("MCP_AUTH_TOKEN", "").strip() + + if token: + # Wrap the ASGI app with bearer-token middleware and run via + # uvicorn directly so we keep the session-manager lifespan intact. + import uvicorn + + from syncthing_mcp.auth import BearerAuthMiddleware + + app = mcp.streamable_http_app() + app.add_middleware(BearerAuthMiddleware, token=token) + + print("Bearer-token authentication enabled", file=sys.stderr) + print(f"Listening on {host}:{port} (streamable-http)", file=sys.stderr) + uvicorn.run(app, host=host, port=port, log_level="info") + else: + print( + "WARNING: MCP_AUTH_TOKEN not set — server is unauthenticated", + file=sys.stderr, + ) + mcp.run(transport="streamable-http", host=host, port=port) if __name__ == "__main__": diff --git a/src/syncthing_mcp/auth.py b/src/syncthing_mcp/auth.py new file mode 100644 index 0000000..f1d22fe --- /dev/null +++ b/src/syncthing_mcp/auth.py @@ -0,0 +1,33 @@ +"""Bearer token authentication middleware for Streamable HTTP transport.""" + +from starlette.middleware.base import BaseHTTPMiddleware +from starlette.requests import Request +from starlette.responses import JSONResponse + + +class BearerAuthMiddleware(BaseHTTPMiddleware): + """Validate ``Authorization: Bearer `` on every request. + + Requests without a valid token receive a 401 response. Health-check + probes hitting ``/health`` are allowed through unauthenticated so that + Docker / Traefik health checks work without token configuration. + """ + + def __init__(self, app, token: str) -> None: + super().__init__(app) + self.token = token + + async def dispatch(self, request: Request, call_next): + # Allow unauthenticated health checks. + if request.url.path == "/health": + return await call_next(request) + + auth = request.headers.get("authorization", "") + if not auth.startswith("Bearer ") or auth[7:] != self.token: + return JSONResponse( + {"error": "Invalid or missing bearer token"}, + status_code=401, + headers={"WWW-Authenticate": "Bearer"}, + ) + + return await call_next(request) diff --git a/src/syncthing_mcp/server.py b/src/syncthing_mcp/server.py index 7d7d127..f904edf 100644 --- a/src/syncthing_mcp/server.py +++ b/src/syncthing_mcp/server.py @@ -3,6 +3,8 @@ from contextlib import asynccontextmanager from mcp.server.fastmcp import FastMCP +from starlette.requests import Request +from starlette.responses import JSONResponse from syncthing_mcp.registry import get_all_instances @@ -23,7 +25,19 @@ async def app_lifespan(app): yield {} -mcp = FastMCP("syncthing_mcp", lifespan=app_lifespan) +mcp = FastMCP( + "syncthing_mcp", + lifespan=app_lifespan, + stateless_http=True, + json_response=True, +) + + +@mcp.custom_route("/health", methods=["GET"]) +async def health(request: Request) -> JSONResponse: + """Unauthenticated health-check endpoint for Docker / Traefik probes.""" + return JSONResponse({"status": "ok"}) + # Import all tool modules so they register with `mcp` via decorators. import syncthing_mcp.tools # noqa: E402, F401