- LICENSE: AGPL-3.0 - install.sh: curl-pipeable bootstrap for Linux/macOS (VPS/LXC) — installs Docker if missing, clones, generates strong LWSS_API_KEY + SearXNG secret, compose up, prints the ready-to-run 'claude mcp add' command; idempotent and preserves .env on re-run - auth: optional bearer token (LWSS_API_KEY) on all orchestrator MCP + REST requests via middleware; /health exempt; empty key disables auth (LAN only); constant-time compare - compose: configurable bind address (ORCHESTRATOR_BIND, default 0.0.0.0) so the endpoint can stay localhost-only behind a tunnel; API key plumbed through - docker-compose.override.yml pattern (gitignored) + .example for machine-local config like LAN SearXNG extra_hosts - README: install one-liner, auth + security (SSRF/tunnel) notes, license - PRD: auth documented in §8; multi-tenant non-goal clarified Verified: auth rejects unauthenticated REST + MCP (401), passes with a valid bearer token, /health stays open; full dockerized stack healthy; MCP client connects only with the Authorization header. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
105 lines
3.5 KiB
Python
105 lines
3.5 KiB
Python
"""Orchestrator: the only externally exposed service (REST now, MCP in M4)."""
|
|
|
|
from contextlib import asynccontextmanager
|
|
|
|
import httpx
|
|
from fastapi import FastAPI, HTTPException
|
|
from pydantic import BaseModel
|
|
|
|
from . import config, pipeline
|
|
from .auth import BearerAuthMiddleware
|
|
from .cache import Cache
|
|
from .logging_setup import setup
|
|
from .mcp_server import mcp, runtime
|
|
|
|
log = setup()
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI):
|
|
app.state.client = httpx.AsyncClient()
|
|
app.state.cache = Cache(config.REDIS_URL)
|
|
runtime["client"] = app.state.client
|
|
runtime["cache"] = app.state.cache
|
|
async with mcp.session_manager.run():
|
|
yield
|
|
await app.state.cache.close()
|
|
await app.state.client.aclose()
|
|
|
|
|
|
app = FastAPI(title="LWSS Orchestrator", lifespan=lifespan)
|
|
app.add_middleware(BearerAuthMiddleware, api_key=config.API_KEY)
|
|
app.mount("/mcp", mcp.streamable_http_app())
|
|
|
|
|
|
class ScrapeRequest(BaseModel):
|
|
url: str
|
|
|
|
|
|
class SearchRequest(BaseModel):
|
|
query: str
|
|
max_results: int = 10
|
|
|
|
|
|
@app.get("/health")
|
|
async def health() -> dict:
|
|
"""Aggregate health across all downstream services."""
|
|
client: httpx.AsyncClient = app.state.client
|
|
services = {}
|
|
for name, base in [
|
|
("searcher", config.SEARCHER_URL),
|
|
("renderer", config.RENDERER_URL),
|
|
("extractor", config.EXTRACTOR_URL),
|
|
]:
|
|
try:
|
|
resp = await client.get(f"{base}/health", timeout=5)
|
|
services[name] = resp.json() if resp.status_code == 200 else {"status": "error"}
|
|
except httpx.HTTPError:
|
|
services[name] = {"status": "unreachable"}
|
|
overall = "ok" if all(s.get("status") == "ok" for s in services.values()) else "degraded"
|
|
return {
|
|
"status": overall,
|
|
"service": "orchestrator",
|
|
"redis": await app.state.cache.is_ready(),
|
|
"services": services,
|
|
}
|
|
|
|
|
|
@app.post("/search")
|
|
async def search(req: SearchRequest) -> dict:
|
|
trace = pipeline.Trace()
|
|
try:
|
|
results = await pipeline.search(app.state.client, req.query, req.max_results, trace)
|
|
except pipeline.StageError as exc:
|
|
log.error("search failed: %s", exc.detail)
|
|
raise HTTPException(status_code=502, detail={"stage": exc.stage, "error": exc.detail}) from exc
|
|
return {"results": results, "trace": trace.as_dict()}
|
|
|
|
|
|
@app.post("/search/contents")
|
|
async def search_contents(req: SearchRequest) -> dict:
|
|
try:
|
|
data = await pipeline.search_contents(app.state.client, req.query, req.max_results, app.state.cache)
|
|
except pipeline.StageError as exc:
|
|
log.error("search/contents failed at %s: %s", exc.stage, exc.detail)
|
|
raise HTTPException(status_code=502, detail={"stage": exc.stage, "error": exc.detail}) from exc
|
|
log.info(
|
|
"search/contents %r -> %d results (%d failed)",
|
|
req.query,
|
|
len(data["results"]),
|
|
len(data["failed_urls"]),
|
|
)
|
|
return data
|
|
|
|
|
|
@app.post("/scrape")
|
|
async def scrape(req: ScrapeRequest) -> dict:
|
|
if not req.url.startswith(("http://", "https://")):
|
|
raise HTTPException(status_code=400, detail="url must be http(s)")
|
|
try:
|
|
result = await pipeline.scrape_url(app.state.client, req.url, app.state.cache)
|
|
except pipeline.StageError as exc:
|
|
log.error("scrape failed at %s: %s", exc.stage, exc.detail)
|
|
raise HTTPException(status_code=502, detail={"stage": exc.stage, "error": exc.detail}) from exc
|
|
log.info("scraped %s (%d chars)", req.url, len(result["content"]))
|
|
return result
|