import os import sys import zipfile import uvicorn from fastapi import FastAPI, HTTPException, Request from fastapi.responses import JSONResponse # --- 1️⃣ Décompression du zip MCP --- ZIP_PATH = "MistralHackathonMCP.zip" EXTRACT_DIR = "app/MistralHackathonMCP" if os.path.exists(ZIP_PATH) and not os.path.exists(EXTRACT_DIR): with zipfile.ZipFile(ZIP_PATH, 'r') as zip_ref: zip_ref.extractall("app") print(f"✅ Décompressé {ZIP_PATH} dans app/") # --- 2️⃣ Ajouter le dossier MCP au PYTHONPATH --- sys.path.append(EXTRACT_DIR) # --- Patch rapide pour corriger les f-strings avec strftime --- main_path = os.path.join(EXTRACT_DIR, "main.py") if os.path.exists(main_path): with open(main_path, "r", encoding="utf-8") as f: lines = f.readlines() fixed_lines = [] for line in lines: fixed_lines.append(line.replace('strftime("%Y-%m-%d %H:%M:%S")', "strftime('%Y-%m-%d %H:%M:%S')")) with open(main_path, "w", encoding="utf-8") as f: f.writelines(fixed_lines) print("✅ Patch f-strings strftime appliqué sur main.py") # --- 3️⃣ Importer FastMCP instance --- try: from main import get_mcp_instance mcp = get_mcp_instance() print("✅ FastMCP initialisé avec succès") except Exception as e: print(f"❌ Impossible d'initialiser FastMCP : {e}") mcp = None # --- 4️⃣ Créer l'application FastAPI --- app = FastAPI(title="Atlas-MCP Server") # --- Route GET racine --- @app.get("/") def root(): return { "status": "MCP Atlas actif 🚀", "endpoints": ["/mcp/list_tools", "/mcp/call_tool", "/health"] } # --- Route POST racine (pour front HF) --- @app.post("/") async def root_post(request: Request): return {"status": "MCP Atlas actif 🚀 (POST OK)"} # --- 5️⃣ Route pour lister les outils MCP --- @app.get("/mcp/list_tools") async def list_tools(): if not mcp: raise HTTPException(status_code=500, detail="MCP non initialisé") try: tools = await mcp.list_tools() # await la coroutine return JSONResponse(tools) except Exception as e: raise HTTPException(status_code=500, detail=f"Erreur list_tools(): {e}") # --- 6️⃣ Route pour appeler un outil MCP --- @app.get("/mcp/call_tool") def call_tool(name: str): if not mcp: raise HTTPException(status_code=500, detail="MCP non initialisé") try: # passer arguments vides si outil n'en requiert pas result = mcp.call_tool(name, arguments=[]) return JSONResponse(result) except Exception as e: raise HTTPException(status_code=500, detail=f"Erreur call_tool(): {e}") # --- 7️⃣ Route healthcheck --- @app.get("/health") async def health(): if not mcp: return {"status": "error", "detail": "MCP non initialisé"} try: tools = await mcp.list_tools() return {"status": "ok", "mcp_tools_count": len(tools)} except Exception as e: return {"status": "error", "detail": f"Healthcheck failed: {e}"} # --- 8️⃣ Point d'entrée pour lancer l'API --- if __name__ == "__main__": uvicorn.run("app:app", host="0.0.0.0", port=7860)