diffmem-mcp-server 0.1.2__tar.gz → 0.1.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. {diffmem_mcp_server-0.1.2 → diffmem_mcp_server-0.1.3}/CHANGELOG.md +9 -1
  2. {diffmem_mcp_server-0.1.2 → diffmem_mcp_server-0.1.3}/CONTEXT.md +6 -0
  3. {diffmem_mcp_server-0.1.2 → diffmem_mcp_server-0.1.3}/PKG-INFO +1 -1
  4. {diffmem_mcp_server-0.1.2 → diffmem_mcp_server-0.1.3}/diffmem_mcp/api_client.py +31 -1
  5. {diffmem_mcp_server-0.1.2 → diffmem_mcp_server-0.1.3}/diffmem_mcp/asgi.py +8 -2
  6. {diffmem_mcp_server-0.1.2 → diffmem_mcp_server-0.1.3}/diffmem_mcp/server.py +26 -0
  7. {diffmem_mcp_server-0.1.2 → diffmem_mcp_server-0.1.3}/diffmem_mcp/tools/memory.py +24 -3
  8. diffmem_mcp_server-0.1.3/docs/adr/0001-mcp-artifact-versioning-and-transport-restarts.md +36 -0
  9. {diffmem_mcp_server-0.1.2 → diffmem_mcp_server-0.1.3}/pyproject.toml +1 -1
  10. {diffmem_mcp_server-0.1.2 → diffmem_mcp_server-0.1.3}/tests/test_memory_tools.py +109 -2
  11. {diffmem_mcp_server-0.1.2 → diffmem_mcp_server-0.1.3}/uv.lock +1 -1
  12. {diffmem_mcp_server-0.1.2 → diffmem_mcp_server-0.1.3}/.gitignore +0 -0
  13. {diffmem_mcp_server-0.1.2 → diffmem_mcp_server-0.1.3}/Dockerfile +0 -0
  14. {diffmem_mcp_server-0.1.2 → diffmem_mcp_server-0.1.3}/PRODUCTION_DEPLOYMENT.md +0 -0
  15. {diffmem_mcp_server-0.1.2 → diffmem_mcp_server-0.1.3}/README.md +0 -0
  16. {diffmem_mcp_server-0.1.2 → diffmem_mcp_server-0.1.3}/diffmem_mcp/__init__.py +0 -0
  17. {diffmem_mcp_server-0.1.2 → diffmem_mcp_server-0.1.3}/diffmem_mcp/auth.py +0 -0
  18. {diffmem_mcp_server-0.1.2 → diffmem_mcp_server-0.1.3}/diffmem_mcp/context.py +0 -0
  19. {diffmem_mcp_server-0.1.2 → diffmem_mcp_server-0.1.3}/diffmem_mcp/copy.py +0 -0
  20. {diffmem_mcp_server-0.1.2 → diffmem_mcp_server-0.1.3}/diffmem_mcp/router.py +0 -0
  21. {diffmem_mcp_server-0.1.2 → diffmem_mcp_server-0.1.3}/diffmem_mcp/scopes.py +0 -0
  22. {diffmem_mcp_server-0.1.2 → diffmem_mcp_server-0.1.3}/diffmem_mcp/security.py +0 -0
  23. {diffmem_mcp_server-0.1.2 → diffmem_mcp_server-0.1.3}/diffmem_mcp/settings.py +0 -0
  24. {diffmem_mcp_server-0.1.2 → diffmem_mcp_server-0.1.3}/diffmem_mcp/tools/__init__.py +0 -0
  25. {diffmem_mcp_server-0.1.2 → diffmem_mcp_server-0.1.3}/diffmem_mcp/tools/files.py +0 -0
  26. {diffmem_mcp_server-0.1.2 → diffmem_mcp_server-0.1.3}/diffmem_mcp/tools/project.py +0 -0
  27. {diffmem_mcp_server-0.1.2 → diffmem_mcp_server-0.1.3}/diffmem_mcp/tools/spaces.py +0 -0
  28. {diffmem_mcp_server-0.1.2 → diffmem_mcp_server-0.1.3}/tests/__init__.py +0 -0
  29. {diffmem_mcp_server-0.1.2 → diffmem_mcp_server-0.1.3}/tests/test_auth.py +0 -0
  30. {diffmem_mcp_server-0.1.2 → diffmem_mcp_server-0.1.3}/tests/test_capture_copy_contract.py +0 -0
  31. {diffmem_mcp_server-0.1.2 → diffmem_mcp_server-0.1.3}/tests/test_fire_and_forget_contract.py +0 -0
  32. {diffmem_mcp_server-0.1.2 → diffmem_mcp_server-0.1.3}/tests/test_http_auth_gate.py +0 -0
  33. {diffmem_mcp_server-0.1.2 → diffmem_mcp_server-0.1.3}/tests/test_router.py +0 -0
  34. {diffmem_mcp_server-0.1.2 → diffmem_mcp_server-0.1.3}/tests/test_scope_enforcement.py +0 -0
  35. {diffmem_mcp_server-0.1.2 → diffmem_mcp_server-0.1.3}/tests/test_security.py +0 -0
  36. {diffmem_mcp_server-0.1.2 → diffmem_mcp_server-0.1.3}/tests/test_self_containment.py +0 -0
  37. {diffmem_mcp_server-0.1.2 → diffmem_mcp_server-0.1.3}/tests/test_space_allowlist.py +0 -0
  38. {diffmem_mcp_server-0.1.2 → diffmem_mcp_server-0.1.3}/tests/test_spaces_tool_error_surface.py +0 -0
  39. {diffmem_mcp_server-0.1.2 → diffmem_mcp_server-0.1.3}/tests/test_tool_error_paths.py +0 -0
@@ -3,7 +3,15 @@
3
3
  All notable changes to the `diffmem-mcp-server` package are documented here.
4
4
  Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versions follow [SemVer](https://semver.org/).
5
5
 
6
- ## [Unreleased]
6
+ ## [0.1.3] — 2026-11-28
7
+
8
+ ### Changed
9
+ - **`retrieve_context` policy contract (#261):** only `"public"` is resolvable — empty policy defaults to `public`, unknown values are rejected locally (`invalid_policy`) with the valid value named, before any network call; the tool description no longer advertises policies the engine does not implement (`"recent"`, `"comprehensive"`).
10
+ - **Engine 4xx detail dialects surfaced:** bodies carrying no top-level `error` key are unwrapped — `{"detail": {"error", "message"}}` (engine handler 400s) and `{"detail": "<string>"}` (e.g. `Unknown policy: 'recent'. Supported policies: public`) map to `invalid_request` with the clean detail intact, instead of the generic `upstream_error` that left callers with no corrective signal (2026-11-24 retrieval incident).
11
+ - **Version beacon (ADR-0001):** every transport entrypoint (stdio `main`, SSE `main_sse`, RP-hosted ASGI factory) logs `MCP_SERVER_START: version=…` at startup, with a loud `dev-source-unknown` fallback for the RP image's dist-info-less source bundle — stale-build skew is now a one-log-line diagnosis.
12
+
13
+ ### Added
14
+ - Tests pin both nested detail dialects and the version beacon; `docs/adr/0001-mcp-artifact-versioning-and-transport-restarts.md` records the pin/cache/no-restart/hosted-bundle decision.
7
15
 
8
16
  ### Removed
9
17
  - **Prototype copy harness retired (issue #229):** `diffmem_mcp/copy_prototype.py` and `PROTOTYPE-copy.md` are deleted — the copy landed in `diffmem_mcp/copy.py` (#227) and the save→poll dogfood smoke replaces the probe workflow as the integration check (spec 10-mcp-memory-capture §11). Wayfinder ticket 017 remains the wording's primary record; the contract tests now pin the live wire to `copy.py` directly.
@@ -18,8 +18,14 @@ Standalone MCP (Model Context Protocol) server that exposes DiffMem's public mem
18
18
  - **MCP:** Model Context Protocol — standardized protocol for LLM tool use
19
19
  - **stdio transport:** MCP transport over stdin/stdout (current implementation)
20
20
  - **SSE transport:** MCP transport over HTTP Server-Sent Events (implemented via asgi.py with AuthHeaderMiddleware)
21
+ - **Bare space id vs SpaceRef:** MCP tools take **bare space ids** (`"default"`, `"spc_abc123"`); the regional plane builds the full **SpaceRef** (`"project/space"`). Clients never send slash-bearing refs to `/v1/memory/context` — the RP rejects them (`invalid_space_id`)
22
+ - **retrieve_context wire contract:** the RP body is `{query, spaces: [bare ids] | policy}` — exactly one mode, never `conversation`, never dict-shaped spaces. Any other shape is a contract violation (the 2026-11-24 incident class)
21
23
  - **Smart routing:** When `space_id` is omitted for ingest, the regional-plane's router agent classifies content and selects the best public space
24
+ - **Policy-mode retrieval:** Context retrieval without explicit spaces — the body carries `policy` instead of a `spaces` list. The only resolvable policy is `"public"`; empty defaults to `"public"`; any other value is rejected locally by the MCP tool before any network call
25
+ - **Public route vs engine route (two-hop path split):** the same retrieval operation has two different path names — the RP's public surface is `/p/{pid}/v1/memory/context`, which the RP proxies to the ENGINE at `/p/{pid}/v1/context`. Logs showing `/v1/context` are the second hop, not a stale MCP client. Never "unify" these paths
26
+ - **Error detail dialects:** RP-generated 4xx bodies carry their clean detail under `detail`; engine-proxied bodies (passed through verbatim) carry it under `message`. The MCP error mapper accepts both dialects and re-emits the clean detail verbatim (ADR-038: never echo response bodies or exception strings)
22
27
  - **Distributed package:** `diffmem-mcp-server` on PyPI (OIDC trusted publishing via `publish-mcp-server.yml`; operator checklist `docs/PUBLISH-mcp-server.md`) — the artifact external users consume, invoked as `uvx diffmem-mcp-server` (stdio) or `uvx diffmem-mcp-server --sse` (HTTP). Nothing about the server's operation requires a repo checkout.
28
+ - **Version skew:** three build lineages can drift apart silently — the published PyPI wheel (stdio clients), the RP image's bundled `diffmem_mcp` source (hosted MCP at `/p/{pid}/mcp`, frozen at RP build time), and repo HEAD. Every lineage announces its version at startup (`MCP_SERVER_START` log) so skew is diagnosable from logs alone. See ADR-0001
23
29
  - **Dev-only checkout invocation:** running `python -m diffmem_mcp.server` or `pip install -e .` from this monorepo — for developing the bridge inside the platform. Never an onboarding or user path; docs must not present it as one.
24
30
 
25
31
  ## Key Files
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: diffmem-mcp-server
3
- Version: 0.1.2
3
+ Version: 0.1.3
4
4
  Summary: DiffMem MCP Server — exposes DiffMem memory APIs as MCP tools with security-first design
5
5
  Requires-Python: >=3.12
6
6
  Requires-Dist: httpx>=0.27.0
@@ -46,13 +46,43 @@ def map_upstream_http_error(exc: httpx.HTTPStatusError) -> Dict[str, Any]:
46
46
  body = None
47
47
 
48
48
  code = body.get("error") if isinstance(body, dict) else None
49
+ # Two upstream detail-key dialects, both curated clean strings: the
50
+ # regional plane's own 4xx bodies use "detail"; engine-proxied bodies
51
+ # (passed through verbatim by the RP) use "message". Accept either.
49
52
  detail = body.get("detail") if isinstance(body, dict) else None
53
+ if not (isinstance(detail, str) and detail):
54
+ detail = body.get("message") if isinstance(body, dict) else None
55
+
56
+ # Two NESTED dialects (engine handler-raised 4xx, proxied verbatim by the
57
+ # RP — no top-level "error" key):
58
+ # {"detail": {"error": <code>, "message": <str>}} — HTTPException with a
59
+ # mapping detail (e.g. neither-mode invalid_request)
60
+ # {"detail": "<string>"} — HTTPException with a
61
+ # plain detail (e.g. _resolve_policy "Unknown policy")
62
+ # Both carry curated-clean strings (ADR-038); unwrap to the same envelope
63
+ # instead of degrading every engine 400 to the generic upstream_error.
64
+ if isinstance(body, dict) and not (isinstance(code, str) and code):
65
+ nested = body.get("detail")
66
+ if isinstance(nested, dict):
67
+ nested_code = nested.get("error")
68
+ if isinstance(nested_code, str) and nested_code:
69
+ code = nested_code
70
+ if not (isinstance(detail, str) and detail):
71
+ nested_msg = nested.get("message")
72
+ if isinstance(nested_msg, str) and nested_msg:
73
+ detail = nested_msg
74
+ elif isinstance(nested, str) and nested:
75
+ # The plain-detail dialect carries no machine code; "invalid_request"
76
+ # is the engine's own code for this rejection class.
77
+ code = "invalid_request"
78
+ detail = nested
50
79
 
51
80
  if isinstance(code, str) and code:
52
81
  logger.warning(
53
- "MCP_UPSTREAM_HTTP_ERROR: status=%s upstream_code=%s",
82
+ "MCP_UPSTREAM_HTTP_ERROR: status=%s upstream_code=%s detail=%s",
54
83
  exc.response.status_code,
55
84
  code,
85
+ detail,
56
86
  )
57
87
  message = detail if isinstance(detail, str) and detail else GENERIC_ERROR_MESSAGE
58
88
  return {"status": "error", "code": code, "message": message}
@@ -154,12 +154,18 @@ def create_mcp_asgi_app() -> Starlette:
154
154
  Returns:
155
155
  A Starlette ASGI application with both HTTP transports.
156
156
  """
157
- from diffmem_mcp.server import mcp
157
+ from diffmem_mcp.server import MCP_SERVER_VERSION, mcp
158
158
  from diffmem_mcp.tools import register_tools
159
159
 
160
160
  register_tools(mcp)
161
161
 
162
- logger.info("Creating MCP ASGI app with streamable HTTP + SSE transports")
162
+ # Skew beacon (ADR-0001): the RP image bundles this source at RP build
163
+ # time, so the hosted MCP can lag the published wheel — this line is how
164
+ # a stale bundled build announces itself in RP logs.
165
+ logger.info(
166
+ "Creating MCP ASGI app with streamable HTTP + SSE transports (version=%s)",
167
+ MCP_SERVER_VERSION,
168
+ )
163
169
  sse_app = mcp.sse_app()
164
170
  http_app = mcp.streamable_http_app() # instantiates the session manager
165
171
 
@@ -32,6 +32,28 @@ from diffmem_mcp.copy import SERVER_INSTRUCTIONS
32
32
 
33
33
  logger = logging.getLogger(__name__)
34
34
 
35
+
36
+ def _resolve_version() -> str:
37
+ """Package version, or a loud fallback when metadata is absent.
38
+
39
+ The RP image COPYs the diffmem_mcp source tree without dist-info, so
40
+ importlib.metadata finds nothing there; a stale bundled source (the
41
+ failure mode behind the 2026-11-24 retrieval incident) must still be
42
+ identifiable in logs.
43
+ """
44
+ try:
45
+ from importlib.metadata import PackageNotFoundError, version
46
+
47
+ try:
48
+ return version("diffmem-mcp-server")
49
+ except PackageNotFoundError:
50
+ return "dev-source-unknown"
51
+ except Exception: # noqa: BLE001 — a version probe must never block startup
52
+ return "unknown"
53
+
54
+
55
+ MCP_SERVER_VERSION = _resolve_version()
56
+
35
57
  # ---------------------------------------------------------------------------
36
58
  # MCP server instance
37
59
  # ---------------------------------------------------------------------------
@@ -71,6 +93,9 @@ def main():
71
93
  format="%(asctime)s %(name)s %(levelname)s %(message)s",
72
94
  stream=sys.stderr,
73
95
  )
96
+ # Skew beacon (ADR-0001): uvx environments are cached and a new chat never
97
+ # restarts MCP servers — this line is how a stale build announces itself.
98
+ logger.info("MCP_SERVER_START: version=%s transport=stdio", MCP_SERVER_VERSION)
74
99
 
75
100
  # Import and register tools
76
101
  from diffmem_mcp.tools import register_tools
@@ -95,6 +120,7 @@ def main_sse(host: str = "0.0.0.0", port: int = 3001) -> None:
95
120
  level=logging.INFO,
96
121
  format="%(asctime)s %(name)s %(levelname)s %(message)s",
97
122
  )
123
+ logger.info("MCP_SERVER_START: version=%s transport=http", MCP_SERVER_VERSION)
98
124
 
99
125
  from diffmem_mcp.asgi import create_mcp_asgi_app
100
126
 
@@ -27,6 +27,11 @@ from diffmem_mcp.settings import get_settings
27
27
 
28
28
  logger = logging.getLogger(__name__)
29
29
 
30
+ # Policy contract (engine get_context_v2): a policy-mode retrieval resolves
31
+ # exactly one policy — "public". Empty defaults to "public"; anything else is
32
+ # rejected locally (deterministic validation, no HTTP round-trip, no 400).
33
+ VALID_RETRIEVAL_POLICIES = {"public"}
34
+
30
35
  # Spec 10-mcp-memory-capture §6.5: honest annotations on the write tool — a
31
36
  # write, not destructive, and a second call is a second save (no server
32
37
  # machinery; the copy cap + pipeline consolidation handle double-saves).
@@ -318,7 +323,9 @@ def register_memory_tools(mcp_server: FastMCP) -> None:
318
323
  query: The conversation or query to retrieve context for
319
324
  space_id: Optional. Search within a specific space only.
320
325
  spaces: Optional. Comma-separated list of space IDs to search.
321
- policy: Optional. Retrieval policy (e.g. "recent", "comprehensive").
326
+ policy: Optional. Retrieval policy. Only "public" is resolvable;
327
+ empty defaults to "public". Any other value is rejected
328
+ before any network call.
322
329
 
323
330
  Returns synthesized context with source references and retrieval metadata.
324
331
  """
@@ -333,6 +340,18 @@ def register_memory_tools(mcp_server: FastMCP) -> None:
333
340
  requested_spaces = [s.strip() for s in spaces.split(",") if s.strip()] if spaces else []
334
341
  target_spaces = ([space_id] if space_id else []) + requested_spaces
335
342
 
343
+ # Deterministic policy validation (fails fast, no upstream call).
344
+ if policy and policy not in VALID_RETRIEVAL_POLICIES:
345
+ valid = ", ".join(sorted(VALID_RETRIEVAL_POLICIES))
346
+ return json.dumps({
347
+ "status": "error",
348
+ "code": "invalid_policy",
349
+ "message": (
350
+ f"Unknown retrieval policy {policy!r}. "
351
+ f"The only resolvable policy is: {valid}."
352
+ ),
353
+ })
354
+
336
355
  # Check pipeline (spec #77 §7.3): scope → space-allowlist → quota → handler.
337
356
  # Policy-based retrieval (no explicit spaces) is allowlist-enforced
338
357
  # at the regional plane (spec #80 site 2).
@@ -351,8 +370,10 @@ def register_memory_tools(mcp_server: FastMCP) -> None:
351
370
  body["spaces"] = [space_id]
352
371
  elif requested_spaces:
353
372
  body["spaces"] = requested_spaces
354
- elif policy:
355
- body["policy"] = policy
373
+ else:
374
+ # Empty policy defaults to "public" — the engine requires either
375
+ # policy or spaces, and policy-mode is this client's only mode.
376
+ body["policy"] = policy if policy else "public"
356
377
 
357
378
  # Stale MCP→RP path fixed per spec §7.5: /v1/context → /v1/memory/context
358
379
  result = await client.post(
@@ -0,0 +1,36 @@
1
+ # MCP artifact versioning: client configs pin, transport processes outlive config edits
2
+
3
+ Context: the 2026-11-24 retrieval incident. PyPI and the engine were healthy;
4
+ the stdio MCP server under Claude Desktop ran a stale build (v0.1.1, wire
5
+ contract predating #194) for two reasons stacked on top of each other. We
6
+ decided: client configs must **pin** the MCP package version
7
+ (`uvx diffmem-mcp-server@<version>`, never bare `uvx diffmem-mcp-server`),
8
+ and every build lineage announces its version at startup
9
+ (`MCP_SERVER_START: version=…` / the ASGI app factory log line) so skew is
10
+ diagnosable from logs alone.
11
+
12
+ Why the stack matters, operationally:
13
+
14
+ 1. **uvx environments are cached.** Installing a newer release does not
15
+ displace an already-cached environment; `uvx diffmem-mcp-server` keeps
16
+ serving whatever it resolved when first run. Only a version pin or an
17
+ explicit `--refresh` changes it.
18
+ 2. **A new chat does not restart MCP servers.** Claude Desktop spawns stdio
19
+ MCP servers at application launch and reuses them across chats; editing
20
+ `claude_desktop_config.json` mid-session has no effect until a **full
21
+ application quit and relaunch** (tray → Quit, not closing the window).
22
+ 3. **The hosted MCP (RP-colocated) bundles source, not the wheel.** The RP
23
+ Dockerfile `COPY`s `mcp-server/diffmem_mcp/` at RP build time, so the MCP
24
+ served at `/p/{project_id}/mcp` reflects whatever the mcp-server checkout
25
+ contained when the RP image was last built — it can lag both the published
26
+ wheel and repo HEAD. Redeploying the RP is the only way to refresh it.
27
+
28
+ Considered options: auto-updating clients (rejected — non-reproducible client
29
+ behavior, and the incident shows stale caches already defeat it); version in
30
+ `serverInfo` only (rejected — not visible in client logs where the skew is
31
+ observed).
32
+
33
+ Consequences: a stale build is now a one-log-line diagnosis instead of a
34
+ cross-repo archaeology session. Cost: client configs must be edited on every
35
+ deliberate upgrade (accepted — deliberate upgrades are rare; silent drift is
36
+ common). See `CONTEXT.md` → Version skew for the three lineages.
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "diffmem-mcp-server"
7
- version = "0.1.2"
7
+ version = "0.1.3"
8
8
  description = "DiffMem MCP Server — exposes DiffMem memory APIs as MCP tools with security-first design"
9
9
  requires-python = ">=3.12"
10
10
  dependencies = [
@@ -52,8 +52,10 @@ class _StubClient:
52
52
  """Regional-plane transport stub: scripted outcome per call."""
53
53
 
54
54
  outcome: object = None
55
+ last_body: object = None
55
56
 
56
57
  async def post(self, path, *, json_body, timeout=None):
58
+ self.last_body = json_body
57
59
  if isinstance(self.outcome, Exception):
58
60
  raise self.outcome
59
61
  return dict(self.outcome)
@@ -84,8 +86,8 @@ def tools(monkeypatch):
84
86
  monkeypatch.setattr(memory_module, "RegionalPlaneClient", lambda base_url, key: stub)
85
87
 
86
88
  def _sync(fn):
87
- def wrapper(*args):
88
- return asyncio.run(fn(*args))
89
+ def wrapper(*args, **kwargs):
90
+ return asyncio.run(fn(*args, **kwargs))
89
91
 
90
92
  return wrapper
91
93
 
@@ -308,3 +310,108 @@ class TestRetrieveSpaceContract:
308
310
 
309
311
  assert out["status"] == "ok"
310
312
  assert sent == {"query": "q", "spaces": expected}
313
+
314
+
315
+ # ---------------------------------------------------------------------------
316
+ # Policy contract (engine get_context_v2 requires policy or spaces)
317
+ # ---------------------------------------------------------------------------
318
+
319
+
320
+ class TestPolicyContract:
321
+ """Protected rules: the MCP tool's own schema default ("") must never
322
+ produce a bare {query}-only body — the engine 400s on that
323
+ ("Specify either 'policy' or 'spaces'"), and policy-mode retrieval is
324
+ this client's only mode. Empty → "public"; unknown → local deterministic
325
+ error, no upstream call."""
326
+
327
+ def test_empty_policy_defaults_to_public_in_body(self, tools):
328
+ ingest, retrieve, stub = tools
329
+ stub.outcome = {"context": "c", "session_metadata": {}}
330
+ out = json.loads(retrieve("query here"))
331
+ assert out["status"] == "ok"
332
+ assert stub.last_body.get("policy") == "public"
333
+ assert "spaces" not in stub.last_body
334
+
335
+ def test_explicit_public_policy_passthrough(self, tools):
336
+ _, retrieve, stub = tools
337
+ stub.outcome = {"context": "c", "session_metadata": {}}
338
+ assert json.loads(retrieve("q", policy="public"))["status"] == "ok"
339
+ assert stub.last_body.get("policy") == "public"
340
+
341
+ def test_spaces_still_override_policy_default(self, tools):
342
+ _, retrieve, stub = tools
343
+ stub.outcome = {"context": "c", "session_metadata": {}}
344
+ assert json.loads(retrieve("q", space_id="spc_1"))["status"] == "ok"
345
+ assert "policy" not in stub.last_body
346
+ assert stub.last_body["spaces"] == ["spc_1"]
347
+
348
+ def test_unknown_policy_fails_fast_without_upstream_call(self, tools):
349
+ _, retrieve, stub = tools
350
+ stub.outcome = {"context": "c", "session_metadata": {}}
351
+ out = json.loads(retrieve("q", policy="recent"))
352
+ assert out == {
353
+ "status": "error",
354
+ "code": "invalid_policy",
355
+ "message": "Unknown retrieval policy 'recent'. The only resolvable policy is: public.",
356
+ }
357
+ assert stub.last_body is None # no HTTP call reached the transport stub
358
+
359
+ def test_engine_message_key_bodies_surface_detail(self, tools):
360
+ """The engine's 4xx bodies use "message" (not "detail" like the RP's
361
+ own errors); the mapper must accept both dialects or the actionable
362
+ detail is masked by the generic incident message (regression: the
363
+ "Specify either 'policy' or 'spaces'" 400 arrived as uninterpretable)."""
364
+ _, retrieve, stub = tools
365
+ body = json.dumps(
366
+ {"error": "invalid_request", "message": "Specify either 'policy' or 'spaces'."}
367
+ ).encode()
368
+ stub.outcome = _http_status_error(400, body)
369
+ out = json.loads(retrieve("q"))
370
+ assert out == {
371
+ "status": "error",
372
+ "code": "invalid_request",
373
+ "message": "Specify either 'policy' or 'spaces'.",
374
+ }
375
+
376
+
377
+ class TestNestedDetailDialects:
378
+ """Engine handler-raised 4xx render WITHOUT a top-level "error" key —
379
+ HTTPException(detail=mapping) nests under "detail" as {"error","message"},
380
+ and HTTPException(detail=str) renders {"detail": "<string>"}. Both shapes
381
+ were observed live through the deployed RP (2026-11-24 incident follow-up:
382
+ "Unknown policy: 'recent'. Supported policies: public" mapped to the
383
+ generic upstream_error, denying the caller any corrective signal)."""
384
+
385
+ def test_nested_error_mapping_dict_unwrapped(self, tools):
386
+ _, retrieve, stub = tools
387
+ body = json.dumps(
388
+ {"detail": {"error": "invalid_request", "message": "Specify either 'policy' or 'spaces'."}}
389
+ ).encode()
390
+ stub.outcome = _http_status_error(400, body)
391
+ out = json.loads(retrieve("q"))
392
+ assert out == {
393
+ "status": "error",
394
+ "code": "invalid_request",
395
+ "message": "Specify either 'policy' or 'spaces'.",
396
+ }
397
+
398
+ def test_plain_string_detail_maps_to_invalid_request_with_detail_intact(self, tools):
399
+ _, retrieve, stub = tools
400
+ body = json.dumps(
401
+ {"detail": "Unknown policy: 'recent'. Supported policies: public"}
402
+ ).encode()
403
+ stub.outcome = _http_status_error(400, body)
404
+ out = json.loads(retrieve("q"))
405
+ assert out == {
406
+ "status": "error",
407
+ "code": "invalid_request",
408
+ "message": "Unknown policy: 'recent'. Supported policies: public",
409
+ }
410
+
411
+
412
+ def test_version_beacon_resolves():
413
+ """MCP_SERVER_VERSION must always be a non-empty string, including when
414
+ the package is installed from source without dist-info (RP-bundled)."""
415
+ from diffmem_mcp.server import MCP_SERVER_VERSION
416
+
417
+ assert isinstance(MCP_SERVER_VERSION, str) and MCP_SERVER_VERSION
@@ -201,7 +201,7 @@ wheels = [
201
201
 
202
202
  [[package]]
203
203
  name = "diffmem-mcp-server"
204
- version = "0.1.1"
204
+ version = "0.1.3"
205
205
  source = { editable = "." }
206
206
  dependencies = [
207
207
  { name = "httpx" },