Skip to content

Commit 4a1de26

Browse files
authored
fix: move CORS config to utils and suppress warning on --version (#19)
- Move configure_cors function from api.py to utils.py to break circular import - Add sys.argv check to suppress CORS warnings during --version command - Call configure_cors during FastAPI app creation instead of lifespan
1 parent e53ddcf commit 4a1de26

File tree

2 files changed

+31
-21
lines changed

2 files changed

+31
-21
lines changed

src/ollama_mcp_bridge/api.py

Lines changed: 5 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,13 @@
11
"""FastAPI application"""
2-
import os
32
from typing import Dict, Any
43
import httpx
54
from fastapi import FastAPI, HTTPException, Body, status, Request
65
from fastapi.responses import JSONResponse
7-
from fastapi.middleware.cors import CORSMiddleware
86
from loguru import logger
97

108
from .lifecycle import lifespan, get_proxy_service
119
from .schemas import CHAT_EXAMPLE
12-
from .utils import check_for_updates
10+
from .utils import check_for_updates, configure_cors
1311
from . import __version__
1412

1513

@@ -21,24 +19,8 @@
2119
lifespan=lifespan
2220
)
2321

24-
# Configure CORS
25-
cors_origins = os.getenv("CORS_ORIGINS", "*").split(",")
26-
cors_origins = [origin.strip() for origin in cors_origins]
27-
28-
# Log CORS configuration
29-
if cors_origins == ["*"]:
30-
logger.warning("CORS is configured to allow ALL origins (*). This is not recommended for production.")
31-
else:
32-
logger.info(f"CORS configured to allow origins: {cors_origins}")
33-
34-
app.add_middleware(
35-
CORSMiddleware,
36-
allow_origins=cors_origins,
37-
allow_credentials=True,
38-
allow_methods=["*"],
39-
allow_headers=["*"],
40-
)
41-
22+
# Configure CORS middleware
23+
configure_cors(app)
4224

4325
@app.get("/health", summary="Health check", description="Check the health status of the MCP Proxy and Ollama server.")
4426
async def health():
@@ -74,6 +56,7 @@ async def chat(
7456
logger.error(f"/api/chat failed: {e}")
7557
raise HTTPException(status_code=500, detail=f"/api/chat failed: {str(e)}") from e
7658

59+
7760
@app.get("/version", summary="Version information", description="Get version information and check for updates.")
7861
async def version():
7962
"""Version information endpoint."""
@@ -84,6 +67,7 @@ async def version():
8467
"latest_version": latest_version
8568
}
8669

70+
8771
@app.api_route("/{path_name:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS", "HEAD"],
8872
summary="Transparent proxy", description="Transparent proxy to any Ollama endpoint.",
8973
include_in_schema=False)

src/ollama_mcp_bridge/utils.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,32 @@
77
from typer import BadParameter
88
from loguru import logger
99
from packaging import version as pkg_version
10+
from fastapi.middleware.cors import CORSMiddleware
11+
import sys
12+
13+
14+
def configure_cors(app):
15+
"""Configure CORS middleware for the FastAPI app."""
16+
17+
cors_origins = os.getenv("CORS_ORIGINS", "*").split(",")
18+
cors_origins = [origin.strip() for origin in cors_origins]
19+
20+
# Don't log CORS config if the user is checking the version
21+
is_version_check = any('--version' in arg for arg in sys.argv)
22+
23+
if not is_version_check:
24+
if cors_origins == ["*"]:
25+
logger.warning("CORS is configured to allow ALL origins (*). This is not recommended for production.")
26+
else:
27+
logger.info(f"CORS configured to allow origins: {cors_origins}")
28+
29+
app.add_middleware(
30+
CORSMiddleware,
31+
allow_origins=cors_origins,
32+
allow_credentials=True,
33+
allow_methods=["*"],
34+
allow_headers=["*"],
35+
)
1036

1137

1238
def check_ollama_health(ollama_url: str, timeout: int = 3) -> bool:

0 commit comments

Comments
 (0)