Merge pull request #1500 from mvalentsev/fix/mcp-typed-error-1351

fix(mcp): structured error for param-shape mismatch (#1351)
This commit is contained in:
Igor Lins e Silva
2026-05-14 17:25:53 -03:00
committed by GitHub
2 changed files with 181 additions and 7 deletions
+40 -7
View File
@@ -45,6 +45,7 @@ sys.stdout = sys.stderr
import argparse # noqa: E402 (deferred until after stdio protection above)
import json # noqa: E402
import logging # noqa: E402
import re # noqa: E402
import hashlib # noqa: E402
import sqlite3 # noqa: E402
import threading # noqa: E402
@@ -2155,6 +2156,15 @@ SUPPORTED_PROTOCOL_VERSIONS = [
]
def _internal_tool_error(req_id, tool_name: str) -> dict:
logger.exception(f"Tool error in {tool_name}")
return {
"jsonrpc": "2.0",
"id": req_id,
"error": {"code": -32000, "message": "Internal tool error"},
}
def handle_request(request):
if not isinstance(request, dict):
return {
@@ -2250,8 +2260,8 @@ def handle_request(request):
"id": req_id,
"error": {"code": -32602, "message": f"Invalid value for parameter '{key}'"},
}
tool_args.pop("wait_for_previous", None)
try:
tool_args.pop("wait_for_previous", None)
result = TOOLS[tool_name]["handler"](**tool_args)
return {
"jsonrpc": "2.0",
@@ -2262,13 +2272,36 @@ def handle_request(request):
]
},
}
except TypeError as e:
# Qualname match prevents leaking internal helper/param names raised
# inside the handler body — see test_handler_internal_signature_shape_stays_generic.
msg = str(e)
handler = TOOLS[tool_name]["handler"]
handler_qn = getattr(handler, "__qualname__", None) or getattr(handler, "__name__", "")
# Qualname can include "<locals>" for nested defs and "<lambda>"
# for lambdas — accept Python's TypeError emit verbatim.
m_missing = re.match(
r"^([\w\.<>]+)\(\) missing \d+ required "
r"(?:positional |keyword-only )?arguments?: (.+)$",
msg,
)
if m_missing and m_missing.group(1) == handler_qn:
names = re.findall(r"'(\w+)'", m_missing.group(2))
if names:
quoted = ", ".join(f"'{n}'" for n in names)
word = "parameter" if len(names) == 1 else "parameters"
logger.debug("Tool %s: missing required %s %s", tool_name, word, quoted)
return {
"jsonrpc": "2.0",
"id": req_id,
"error": {
"code": -32602,
"message": f"Missing required {word} {quoted} for tool {tool_name}",
},
}
return _internal_tool_error(req_id, tool_name)
except Exception:
logger.exception(f"Tool error in {tool_name}")
return {
"jsonrpc": "2.0",
"id": req_id,
"error": {"code": -32000, "message": "Internal tool error"},
}
return _internal_tool_error(req_id, tool_name)
# Notifications (missing id) must never get a response
if req_id is None:
+141
View File
@@ -1868,3 +1868,144 @@ class TestKGLazyCache:
with pytest.raises(_sqlite3.ProgrammingError):
mcp_server._call_kg(lambda kg: kg.query_entity("Alice"))
assert calls["count"] == 2, "expected exactly one retry beyond the initial attempt"
# ── Param-shape diagnostics on tools/call dispatch (#1351) ──────────────
class TestParamShapeDiagnostics:
"""Dispatch-level TypeError on tools/call should surface as JSON-RPC
-32602 (Invalid params) with the offending parameter named, instead of
the opaque -32000 Internal tool error. Handler-internal TypeError and
non-TypeError exceptions stay generic -32000 (no internals leak).
"""
def test_missing_required_returns_32602_with_param_name(self):
from mempalace.mcp_server import handle_request
resp = handle_request(
{
"method": "tools/call",
"id": 1,
"params": {
"name": "mempalace_diary_write",
"arguments": {"agent_name": "test"},
},
}
)
assert resp["error"]["code"] == -32602
assert "'entry'" in resp["error"]["message"]
assert "mempalace_diary_write" in resp["error"]["message"]
def test_handler_internal_typeerror_stays_generic_32000(self, monkeypatch):
from mempalace import mcp_server
def boom(**_kw):
raise TypeError("unsupported operand type(s) for +: 'int' and 'str'")
monkeypatch.setitem(mcp_server.TOOLS["mempalace_status"], "handler", boom)
resp = mcp_server.handle_request(
{
"method": "tools/call",
"id": 2,
"params": {"name": "mempalace_status", "arguments": {}},
}
)
assert resp["error"]["code"] == -32000
assert resp["error"]["message"] == "Internal tool error"
assert "unsupported operand" not in resp["error"]["message"]
def test_chromadb_exception_stays_generic_32000(self, monkeypatch):
from mempalace import mcp_server
def boom(**_kw):
raise RuntimeError("db schema mismatch at /private/path/chroma.sqlite3")
monkeypatch.setitem(mcp_server.TOOLS["mempalace_status"], "handler", boom)
resp = mcp_server.handle_request(
{
"method": "tools/call",
"id": 3,
"params": {"name": "mempalace_status", "arguments": {}},
}
)
assert resp["error"]["code"] == -32000
assert resp["error"]["message"] == "Internal tool error"
assert "db schema" not in resp["error"]["message"]
assert "/private/path" not in resp["error"]["message"]
def test_two_missing_required_lists_both_names(self):
"""For 2+ missing args Python emits 'a' and 'b'; the response should
list both quoted names, not return a syntactically broken string.
"""
from mempalace.mcp_server import handle_request
resp = handle_request(
{
"method": "tools/call",
"id": 4,
"params": {"name": "mempalace_diary_write", "arguments": {}},
}
)
assert resp["error"]["code"] == -32602
message = resp["error"]["message"]
assert "parameters" in message
assert "'agent_name'" in message
assert "'entry'" in message
assert " and " not in message.split("for tool")[0]
def test_handler_internal_signature_shape_stays_generic(self, monkeypatch):
"""A TypeError whose function name does not match the dispatched
handler — e.g. raised by a helper called inside the handler body —
must fall through to generic -32000, otherwise we'd leak internal
helper/parameter names as if they were public tool parameters.
"""
from mempalace import mcp_server
def calling_handler(**_kw):
def helper(req):
return req
helper()
monkeypatch.setitem(mcp_server.TOOLS["mempalace_status"], "handler", calling_handler)
resp = mcp_server.handle_request(
{
"method": "tools/call",
"id": 5,
"params": {"name": "mempalace_status", "arguments": {}},
}
)
assert resp["error"]["code"] == -32000
assert resp["error"]["message"] == "Internal tool error"
assert "'req'" not in resp["error"]["message"]
assert "helper" not in resp["error"]["message"]
def test_unexpected_kw_typeerror_inside_handler_stays_generic(self, monkeypatch):
"""The 'got an unexpected keyword argument' shape is unreachable from
real dispatch (schema-filter on line 2236 drops unknown kwargs for
normal handlers; **kwargs handlers per #684 accept anything). If a
handler raises that shape manually, the qualname mismatch must keep
it on the generic -32000 path so internal helper names cannot leak.
"""
from mempalace import mcp_server
def boom(**_kw):
raise TypeError("some_helper() got an unexpected keyword argument 'foo'")
monkeypatch.setitem(mcp_server.TOOLS["mempalace_status"], "handler", boom)
resp = mcp_server.handle_request(
{
"method": "tools/call",
"id": 6,
"params": {"name": "mempalace_status", "arguments": {}},
}
)
assert resp["error"]["code"] == -32000
assert resp["error"]["message"] == "Internal tool error"
assert "'foo'" not in resp["error"]["message"]
assert "some_helper" not in resp["error"]["message"]