fix: map KeyError->404 and ValueError->400 for MCP clients

Tool functions raise KeyError for unknown ids and ValueError for invalid
state transitions. Without handlers, FastAPI returned a bare 500
"Internal Server Error" to MCP clients — useless for an agent that needs
to know whether the id was wrong vs the cluster was down.

KeyError -> 404 with the message ("Unknown job_id: foo").
ValueError -> 400 with the message (e.g. "pending_id p_xyz is in status
'CANCELLED', not PENDING").
This commit is contained in:
Claude
2026-06-24 14:59:00 +08:00
parent 6b9f278294
commit fad296591c
2 changed files with 85 additions and 1 deletions
+19 -1
View File
@@ -3,7 +3,8 @@
@Time :2026/6/24
@Author :tao.chen
"""
from fastapi import FastAPI
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from spark_executor.tools.connections import (
delete_connection,
@@ -34,6 +35,23 @@ from spark_executor.tools.submit import (
app = FastAPI(title="Spark Executor", version="0.0.1", description="Spark Executor MCP Server")
# --- Exception handlers: translate tool-layer errors into proper HTTP statuses ---
#
# Tool functions raise KeyError for "unknown id" (job_id, pending_id, connection
# name) and ValueError for invalid state transitions (e.g. confirming a
# CANCELLED pending). Without these handlers FastAPI would map them to a bare
# 500 "Internal Server Error" which is useless to MCP clients.
@app.exception_handler(KeyError)
async def _keyerror_handler(_request: Request, exc: KeyError) -> JSONResponse:
return JSONResponse(status_code=404, content={"detail": str(exc)})
@app.exception_handler(ValueError)
async def _valueerror_handler(_request: Request, exc: ValueError) -> JSONResponse:
return JSONResponse(status_code=400, content={"detail": str(exc)})
@app.get("/health")
def health_check():
return {"status": "ok"}