| 8 | from .mcp_sse import handle_sse, handle_messages |
| 9 | |
| 10 | def create_app() -> FastAPI: |
| 11 | # Log whether API-key auth is active. Emits a prominent security warning |
| 12 | # when the gateway is running unauthenticated (CGC_API_KEY unset). |
| 13 | log_auth_status() |
| 14 | |
| 15 | app = FastAPI( |
| 16 | title="CodeGraphContext Gateway", |
| 17 | description="HTTP API gateway for CodeGraphContext MCP server. Enables integration with ChatGPT Actions, Claude, and web frontends.", |
| 18 | version="0.1.0" |
| 19 | ) |
| 20 | |
| 21 | # Enable CORS for the website/frontend |
| 22 | app.add_middleware( |
| 23 | CORSMiddleware, |
| 24 | allow_origins=["*"], # In production, restrict this |
| 25 | # Credentials must stay disabled while origins is a wildcard; the |
| 26 | # combination is rejected by browsers and would leak cookie-authed |
| 27 | # responses to any site. |
| 28 | allow_credentials=False, |
| 29 | allow_methods=["*"], |
| 30 | allow_headers=["*"], |
| 31 | ) |
| 32 | |
| 33 | app.include_router(router, prefix="/api/v1") |
| 34 | |
| 35 | @app.get("/health") |
| 36 | async def health(): |
| 37 | """Liveness probe for load balancers and k8s.""" |
| 38 | return {"status": "ok"} |
| 39 | |
| 40 | # MCP-over-SSE Endpoints. These dispatch to the same tools as the REST |
| 41 | # router (execute_cypher_query, add_code_to_graph, delete_repository), so |
| 42 | # they need the same API-key dependency the router applies — without it, |
| 43 | # setting CGC_API_KEY left the SSE transport as an unauthenticated path to |
| 44 | # every tool. |
| 45 | app.add_api_route( |
| 46 | "/api/v1/mcp/sse", |
| 47 | handle_sse, |
| 48 | methods=["GET"], |
| 49 | dependencies=[Depends(require_api_key)], |
| 50 | ) |
| 51 | app.add_api_route( |
| 52 | "/api/v1/mcp/messages", |
| 53 | handle_messages, |
| 54 | methods=["POST"], |
| 55 | dependencies=[Depends(require_api_key)], |
| 56 | ) |
| 57 | |
| 58 | @app.get("/", response_class=HTMLResponse) |
| 59 | async def root(): |
| 60 | return """ |
| 61 | <!DOCTYPE html> |
| 62 | <html> |
| 63 | <head> |
| 64 | <title>CGC Gateway</title> |
| 65 | <style> |
| 66 | body { font-family: sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; background: #0f172a; color: white; margin: 0; } |
| 67 | .card { background: #1e293b; padding: 2rem; border-radius: 1rem; box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1); text-align: center; max-width: 400px; border: 1px solid #334155; } |