Loading spec file using filesystem, and api key header
Describe the solution you'd like loading local spec file
def load_openapi(self, openapi_url: str) -> Tuple[Dict[str, Any], str, Dict[str, Dict[str, Any]]]:
try:
if openapi_url.startswith("/"):
if openapi_url.endswith(".yaml"):
spec = yaml.safe_load(open(openapi_url))
else:
spec = json.load(open(openapi_url))
else:
resp = httpx.get(openapi_url)
resp.raise_for_status()
if resp.headers.get("Content-Type", "").startswith("application/json"):
spec = resp.json()
else:
spec = yaml.safe_load(resp.text)
except Exception as e:
logging.error("Could not load OpenAPI spec: %s", e)
return {}, "", {}
if not isinstance(spec, dict) or "paths" not in spec or "info" not in spec:
logging.error("Invalid OpenAPI spec: Missing required properties")
return {}, "", {}
support for other auth method like api key. (custom headers will do the trick) client = httpx.Client(headers=env.MCP_AUTH_HEADERS)
Hi @niradler! Thanks for the detailed feature request and code examples. Both of these features would definitely improve the flexibility of the tool. Let me address each one:
Local File Loading
Your approach for local file loading looks solid! I can see you're checking if the URL starts with "/" to detect local files. The current codebase already has some of this logic in src/openapi_loader.py, but your implementation is cleaner.
A few thoughts on making it even more robust:
def load_spec(openapi_url: str) -> Dict[str, Any]:
try:
# Check if it's a local file (your approach + some additions)
if not openapi_url.startswith(('http://', 'https://')):
file_path = Path(openapi_url).resolve()
if not file_path.exists():
raise FileNotFoundError(f"OpenAPI spec file not found: {openapi_url}")
with open(file_path, 'r', encoding='utf-8') as f:
if file_path.suffix.lower() in ['.yml', '.yaml']:
spec = yaml.safe_load(f)
else:
spec = json.load(f)
else:
# Your existing HTTP logic here
resp = httpx.get(openapi_url)
# ... rest of HTTP handling
This would support relative paths like ./specs/api.yaml and ../api.json in addition to absolute paths.
Custom Authentication Headers
Your idea about MCP_AUTH_HEADERS is really smart! Custom headers would indeed handle API keys and other auth methods that aren't OAuth2 or basic auth.
Here's how I think we could implement it:
# In config.py
@property
def auth_headers(self) -> Dict[str, str]:
"""Parse custom authentication headers from environment."""
headers_env = os.getenv("MCP_AUTH_HEADERS", "")
if not headers_env:
return {}
try:
# Support JSON format: {"X-API-Key": "secret", "Authorization": "Bearer token"}
return json.loads(headers_env)
except json.JSONDecodeError:
# Support simple format: X-API-Key=secret,Authorization=Bearer token
headers = {}
for pair in headers_env.split(','):
if '=' in pair:
key, value = pair.split('=', 1)
headers[key.strip()] = value.strip()
return headers
# In openapi_loader.py
def _load_remote_url(self, url: str) -> Dict[str, Any]:
headers = self.config.auth_headers
client = httpx.Client(headers=headers)
resp = client.get(url)
# ... rest of loading logic
This would allow users to set authentication like:
JSON format
MCP_AUTH_HEADERS='{"X-API-Key": "my-secret-key"}'
Simple format
MCP_AUTH_HEADERS='X-API-Key=my-secret-key,Authorization=Bearer token123'
Implementation Plan
Would you be interested in submitting a PR for these features? Here's what I think would make a complete implementation:
- Update OpenAPILoader to handle local files more robustly
- Add auth headers support to the config and HTTP client
- Update README with examples of both features
- Add tests for local file loading and custom headers
The changes would mainly touch:
- src/config.py (add auth headers parsing)
- src/openapi_loader.py (enhance file loading logic)
- src/auth.py (integrate custom headers with existing auth)
Questions
A couple of questions to make sure I understand your use case:
- For local files, do you mainly need absolute paths, or would relative paths be useful too?
- For auth headers, would the JSON format work for your needs, or do you prefer a different format?
- Should custom headers override OAuth/basic auth, or work alongside them?
I think these are both excellent additions that would make the tool much more flexible for different development workflows. Let me know if you'd like to work on this together!
Hi @niradler!
Thanks for the excellent feature request and detailed implementation suggestions! Since I didn't hear back from you after my initial response, I went ahead and implemented both features based on your ideas.
Local File Loading
Your approach was spot-on! I've implemented robust local file loading that supports:
- JSON and YAML files (auto-detection by extension)
- Both relative (
./specs/api.yaml) and absolute paths - Path traversal protection and proper error handling
- Full backward compatibility
# Examples
OPENAPI_URL="./specs/my-api.json" SERVER_NAME="local_api" python src/fastmcp_server.py
OPENAPI_URL="../shared/api.yaml" SERVER_NAME="local_api" python src/fastmcp_server.py
Custom Authentication Headers
Implemented exactly as you suggested with MCP_AUTH_HEADERS! Supports both formats:
JSON: MCP_AUTH_HEADERS='{"X-API-Key": "secret"}'
Simple: MCP_AUTH_HEADERS='X-API-Key=secret,X-Client-ID=client123'
The headers are applied to:
- OpenAPI spec loading (for protected specs)
- All API requests
- Works alongside existing OAuth/basic auth
Implementation Details
Following your suggestions and my earlier response, the implementation covers:
- Enhanced
src/openapi_loader.pywith local file detection - Added
MCP_AUTH_HEADERSparsing tosrc/config.py - Integrated
CustomHeaderAuthenticatorinsrc/auth.py - Comprehensive test coverage (30+ tests)
- Updated documentation with examples
Quick Example
OPENAPI_URL="./specs/api.json" \
MCP_AUTH_HEADERS='{"X-API-Key": "dev-key"}' \
SERVER_NAME="dev_api" \
python src/fastmcp_server.py
Both features are now live in the main branch! Your initial code examples really helped guide the implementation. Thanks again for the thoughtful feature request - even though you didn't follow up, your suggestions made this tool much more flexible for different development workflows.
Feel free to test it out if you're still interested!