fastapi_mcp
fastapi_mcp copied to clipboard
feature: add automatic operation ID shortening for LLM compatibility
Describe your changes
Add max_operation_id_length parameter to FastApiMCP that automatically shortens long operation IDs to fit within LLM character limits. The implementation preserves semantic meaning by prioritizing the most specific path segments and using MD5 hashing for uniqueness.
- Add shorten_operation_id() utility function with intelligent truncation
- Add max_operation_id_length parameter (default: 60) to FastApiMCP
- Implement collision detection with warning logs
- Store operation ID mappings for debugging
- Add comprehensive unit and integration tests
- Fully compliant operator_id's by default for all routes -- manual operator_id overrides are an option not a requirement
This ensures compatibility with LLMs that have strict limits on function/tool names (e.g., 60-64 characters) while maintaining readability and preventing collisions.
Issue ticket number and link (if applicable)
#161 (replicate of ->) #64 #69
Before/After Example
Before
from fastapi import FastAPI
from fastapi_mcp import FastApiMCP
app = FastAPI()
@app.post("/api/v1/users/profile/settings/update/notification/preferences")
def update_user_notification_preferences(user_id: str, preferences: dict):
return {"status": "updated"}
mcp = FastApiMCP(app)
# Generated operation ID (88 characters):
# update_user_notification_preferences_api_v1_users_profile_settings_update_notification_preferences_post
❌ LLM Error: Function name exceeds 64 character limit
After
mcp = FastApiMCP(app, max_operation_id_length=60)
# Shortened operation ID (60 characters):
# update_user_notification_preferences_preferences_post_a3c4f9
# Original → Shortened mapping logged:
# DEBUG: Shortened operation ID:
# update_user_notification_preferences_api_v1_users_profile_settings_update_notification_preferences_post
# → update_user_notification_preferences_preferences_post_a3c4f9
✅ LLM Compatible: Function name fits within limits while preserving semantic meaning
Checklist before requesting a review
- [X] Added relevant tests
- [X] Run ruff & mypy
- [X] All tests pass
do we have a sense of when these changes will be merged?