Merge PR #795: fix: handle empty choices in MCP sampling callback
Adds defensive guard against empty/None/missing choices in SamplingHandler.__call__ before accessing response.choices[0]. Returns proper ErrorData instead of crashing with IndexError/TypeError on content filtering, provider errors, or rate limits. Authored by 0xbyt4. Co-authored-by: 0xbyt4 <0xbyt4@users.noreply.github.com>
This commit is contained in:
@@ -538,6 +538,14 @@ class SamplingHandler:
|
||||
f"Sampling LLM call failed: {_sanitize_error(str(exc))}"
|
||||
)
|
||||
|
||||
# Guard against empty choices (content filtering, provider errors)
|
||||
if not getattr(response, "choices", None):
|
||||
self.metrics["errors"] += 1
|
||||
return self._error(
|
||||
f"LLM returned empty response (no choices) for server "
|
||||
f"'{self.server_name}'"
|
||||
)
|
||||
|
||||
# Track metrics
|
||||
choice = response.choices[0]
|
||||
self.metrics["requests"] += 1
|
||||
|
||||
Reference in New Issue
Block a user