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 <noreply@anthropic.com>
This commit is contained in:
PiersandClaude Opus 4.6 committed 2026-02-15 03:54:43 +00:00
1 parent 3a33d34bd1
commit 5ca58735eb
8 files changed
+175 -3

No files matched your search

+23
View File
@@ -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 <token>".
# 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"}
}'
+1
View File
@@ -6,3 +6,4 @@ dist/
.DS_Store
*.old
.pytest_cache/
.env
+25
View File
@@ -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"]
+37
View File
@@ -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
+2
View File
@@ -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]
+39 -2
View File
@@ -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__":
+33
View File
@@ -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 <token>`` 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)
+15 -1
View File
@@ -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