"""Test the FastAPI MCP server."""
import json
import asyncio
from fastapi_mcp_server.server import (
load_app,
get_app,
format_route_info,
get_model_info,
)
async def test_mcp_server():
"""Test the MCP server functionality."""
print("🧪 Testing FastAPI MCP Server\n")
# Test 1: Load the example app
print("1️⃣ Loading example FastAPI app...")
try:
app = load_app("example_app:app")
print(f"✅ Loaded: {app.title} v{app.version}")
print(f" Routes: {len([r for r in app.routes if hasattr(r, 'methods')])}\n")
except Exception as e:
print(f"❌ Error: {e}\n")
return
# Test 2: List all routes
print("2️⃣ Listing all routes:")
from fastapi.routing import APIRoute
routes = [r for r in app.routes if isinstance(r, APIRoute)]
for route in routes[:5]: # Show first 5
print(f" • {', '.join(route.methods)} {route.path} - {route.name}")
print(f" ... and {len(routes) - 5} more\n")
# Test 3: Get route details
print("3️⃣ Getting details for /users/{user_id} GET:")
user_route = None
for route in routes:
if route.path == "/users/{user_id}" and "GET" in route.methods:
user_route = route
break
if user_route:
details = format_route_info(user_route)
print(f" Summary: {details['summary']}")
print(f" Parameters: {len(details['parameters'])}")
for param in details['parameters']:
print(f" - {param['name']} ({param['type']}): {param['annotation']}")
print()
# Test 4: Get OpenAPI schema
print("4️⃣ Getting OpenAPI schema:")
schema = app.openapi()
print(f" OpenAPI Version: {schema['openapi']}")
print(f" Paths: {len(schema['paths'])}")
print(f" Components: {len(schema.get('components', {}).get('schemas', {}))}\n")
# Test 5: Find models
print("5️⃣ Finding Pydantic models:")
models = set()
for route in routes:
if route.response_model and hasattr(route.response_model, "model_json_schema"):
models.add(route.response_model)
for model in sorted(list(models)[:3], key=lambda m: m.__name__):
print(f" • {model.__name__}")
model_info = get_model_info(model)
print(f" Fields: {', '.join(model_info['fields'].keys())}")
print()
# Test 6: Search routes
print("6️⃣ Searching routes with 'user' in path:")
user_routes = [r for r in routes if 'user' in r.path.lower()]
for route in user_routes[:5]:
print(f" • {', '.join(route.methods)} {route.path}")
print()
# Test 7: Analyze dependencies
print("7️⃣ Analyzing dependencies:")
dependencies = {}
for route in routes:
if route.dependant and route.dependant.dependencies:
for dep in route.dependant.dependencies:
dep_name = dep.call.__name__ if hasattr(dep.call, "__name__") else str(dep.call)
if dep_name not in dependencies:
dependencies[dep_name] = []
dependencies[dep_name].append(f"{', '.join(route.methods)} {route.path}")
for dep_name, dep_routes in list(dependencies.items())[:3]:
print(f" • {dep_name}: used in {len(dep_routes)} route(s)")
print()
print("✅ All tests passed! The FastAPI MCP server is working correctly.\n")
# Show usage instructions
print("📚 To use with Claude Desktop, add to your config:")
print("""
{
"mcpServers": {
"fastapi": {
"command": "python",
"args": ["-m", "fastapi_mcp_server.server"],
"cwd": "/path/to/your/fastapi/project"
}
}
}
""")
if __name__ == "__main__":
asyncio.run(test_mcp_server())