fix: harden tool_checkpoint input validation
Address PR review: guard untrusted MCP client payloads in mempalace_checkpoint so a single malformed item cannot raise deep in sanitization and abort the whole batch. - coerce dedup_threshold to float - require wing/room/content to be non-empty strings (skip + record error) - validate the diary object and entry type, recording errors instead of silently ignoring a malformed diary On a genuine dedup-check error we still file the drawer rather than skip: verbatim recall is the priority and add_drawer's idempotency blocks exact duplicates. Adds tests for the non-string, dedup-error, and malformed-diary paths. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
co-authored by
Cursor
parent
4291fecfdf
commit
f3ed6f796e
+36
-9
@@ -2951,6 +2951,16 @@ def tool_checkpoint(items, diary=None, dedup_threshold=0.9):
|
||||
Reuses the existing single-item handlers so dedup/idempotency/WAL
|
||||
behaviour is identical to calling them directly.
|
||||
"""
|
||||
# Inputs come from MCP clients and handle_request does not validate
|
||||
# nested schemas, so guard every field here. A single malformed item
|
||||
# must record an error and be skipped, never raise and abort the whole
|
||||
# batch (the already-filed items in this call would otherwise be lost
|
||||
# from the response).
|
||||
try:
|
||||
dedup_threshold = float(dedup_threshold)
|
||||
except (ValueError, TypeError):
|
||||
return {"error": "dedup_threshold must be a number"}
|
||||
|
||||
out = {"added": [], "duplicates": [], "errors": []}
|
||||
if not isinstance(items, list):
|
||||
return {"error": "items must be a list of {wing, room, content} objects"}
|
||||
@@ -2961,25 +2971,42 @@ def tool_checkpoint(items, diary=None, dedup_threshold=0.9):
|
||||
wing = item.get("wing")
|
||||
room = item.get("room")
|
||||
content = item.get("content")
|
||||
if not (wing and room and content):
|
||||
out["errors"].append({"item": item, "error": "wing, room, content required"})
|
||||
# Non-empty strings only: a non-string here would raise deep in
|
||||
# sanitize_content / strip_lone_surrogates.
|
||||
if not all(isinstance(v, str) and v for v in (wing, room, content)):
|
||||
out["errors"].append(
|
||||
{"item": item, "error": "wing, room, content must be non-empty strings"}
|
||||
)
|
||||
continue
|
||||
dup = tool_check_duplicate(content, threshold=dedup_threshold)
|
||||
if dup.get("is_duplicate"):
|
||||
out["duplicates"].append({"room": room, "matches": dup.get("matches", [])})
|
||||
continue
|
||||
# On a dedup error (genuine index failure — content is guaranteed a
|
||||
# string by the guard above) we still file rather than drop the
|
||||
# memory: verbatim recall is the priority and add_drawer's own
|
||||
# idempotency blocks exact duplicates.
|
||||
res = tool_add_drawer(wing=wing, room=room, content=content, added_by="checkpoint")
|
||||
if res.get("success"):
|
||||
out["added"].append(res)
|
||||
else:
|
||||
out["errors"].append(res)
|
||||
if isinstance(diary, dict) and (diary.get("entry") or diary.get("content")):
|
||||
out["diary"] = tool_diary_write(
|
||||
agent_name=diary.get("agent_name", "cursor-ide"),
|
||||
entry=diary.get("entry") or diary.get("content"),
|
||||
topic=diary.get("topic", "session-checkpoint"),
|
||||
wing=diary.get("wing", ""),
|
||||
)
|
||||
if diary is not None:
|
||||
if not isinstance(diary, dict):
|
||||
out["errors"].append({"diary": diary, "error": "diary must be an object"})
|
||||
else:
|
||||
entry = diary.get("entry") or diary.get("content")
|
||||
if not isinstance(entry, str) or not entry:
|
||||
out["errors"].append(
|
||||
{"diary": diary, "error": "diary entry must be a non-empty string"}
|
||||
)
|
||||
else:
|
||||
out["diary"] = tool_diary_write(
|
||||
agent_name=diary.get("agent_name", "cursor-ide"),
|
||||
entry=entry,
|
||||
topic=diary.get("topic", "session-checkpoint"),
|
||||
wing=diary.get("wing", ""),
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
|
||||
@@ -1582,6 +1582,66 @@ class TestWriteTools:
|
||||
assert result["added"] == []
|
||||
assert len(result["errors"]) == 2
|
||||
|
||||
def test_checkpoint_rejects_non_string_fields_without_calling_handlers(
|
||||
self, monkeypatch, config, kg
|
||||
):
|
||||
"""A non-string content must be reported, never passed to the
|
||||
single-item handlers where it would raise deep in sanitization."""
|
||||
from mempalace import mcp_server
|
||||
|
||||
def _explode(*_a, **_k):
|
||||
raise AssertionError("handlers must not run for malformed items")
|
||||
|
||||
monkeypatch.setattr(mcp_server, "tool_check_duplicate", _explode)
|
||||
monkeypatch.setattr(mcp_server, "tool_add_drawer", _explode)
|
||||
|
||||
result = mcp_server.tool_checkpoint(
|
||||
items=[{"wing": "w", "room": "r", "content": {"not": "a string"}}]
|
||||
)
|
||||
assert result["added"] == []
|
||||
assert len(result["errors"]) == 1
|
||||
assert "non-empty strings" in result["errors"][0]["error"]
|
||||
|
||||
def test_checkpoint_files_when_dedup_check_errors(self, monkeypatch, config, kg):
|
||||
"""A dedup error is a genuine index failure (content is already
|
||||
validated as a string); we still file rather than drop the memory."""
|
||||
from mempalace import mcp_server
|
||||
|
||||
monkeypatch.setattr(
|
||||
mcp_server,
|
||||
"tool_check_duplicate",
|
||||
lambda *a, **k: {"error": "Duplicate check failed"},
|
||||
)
|
||||
filed = {}
|
||||
|
||||
def _add(**kwargs):
|
||||
filed.update(kwargs)
|
||||
return {"success": True, "drawer_id": "d1"}
|
||||
|
||||
monkeypatch.setattr(mcp_server, "tool_add_drawer", _add)
|
||||
|
||||
result = mcp_server.tool_checkpoint(
|
||||
items=[{"wing": "w", "room": "r", "content": "keep me"}]
|
||||
)
|
||||
assert len(result["added"]) == 1
|
||||
assert filed["content"] == "keep me"
|
||||
|
||||
def test_checkpoint_reports_malformed_diary(self, monkeypatch, config, kg):
|
||||
from mempalace import mcp_server
|
||||
|
||||
monkeypatch.setattr(
|
||||
mcp_server, "tool_check_duplicate", lambda *a, **k: {"is_duplicate": False}
|
||||
)
|
||||
|
||||
def _fail_diary(*_a, **_k):
|
||||
raise AssertionError("diary_write must not run for malformed diary")
|
||||
|
||||
monkeypatch.setattr(mcp_server, "tool_diary_write", _fail_diary)
|
||||
|
||||
result = mcp_server.tool_checkpoint(items=[], diary={"agent_name": "x"})
|
||||
assert "diary" not in result
|
||||
assert any("diary entry" in e.get("error", "") for e in result["errors"])
|
||||
|
||||
def test_checkpoint_registered_in_tools(self):
|
||||
from mempalace import mcp_server
|
||||
|
||||
|
||||
Reference in New Issue
Block a user