diffmem-mcp-server 0.1.0__tar.gz → 0.1.2__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 (43) hide show
  1. diffmem_mcp_server-0.1.2/CHANGELOG.md +45 -0
  2. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.2}/CONTEXT.md +8 -8
  3. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.2}/PKG-INFO +1 -1
  4. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.2}/PRODUCTION_DEPLOYMENT.md +6 -8
  5. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.2}/README.md +14 -17
  6. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.2}/diffmem_mcp/api_client.py +4 -2
  7. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.2}/diffmem_mcp/asgi.py +41 -0
  8. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.2}/diffmem_mcp/auth.py +29 -20
  9. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.2}/diffmem_mcp/context.py +1 -1
  10. diffmem_mcp_server-0.1.2/diffmem_mcp/copy.py +64 -0
  11. diffmem_mcp_server-0.1.2/diffmem_mcp/router.py +59 -0
  12. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.2}/diffmem_mcp/server.py +9 -6
  13. diffmem_mcp_server-0.1.2/diffmem_mcp/settings.py +35 -0
  14. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.2}/diffmem_mcp/tools/files.py +12 -11
  15. diffmem_mcp_server-0.1.2/diffmem_mcp/tools/memory.py +424 -0
  16. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.2}/diffmem_mcp/tools/project.py +8 -8
  17. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.2}/diffmem_mcp/tools/spaces.py +14 -12
  18. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.2}/pyproject.toml +1 -1
  19. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.2}/tests/test_auth.py +10 -10
  20. diffmem_mcp_server-0.1.2/tests/test_capture_copy_contract.py +108 -0
  21. diffmem_mcp_server-0.1.2/tests/test_fire_and_forget_contract.py +356 -0
  22. diffmem_mcp_server-0.1.2/tests/test_http_auth_gate.py +94 -0
  23. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.2}/tests/test_memory_tools.py +67 -7
  24. diffmem_mcp_server-0.1.2/tests/test_router.py +103 -0
  25. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.2}/tests/test_space_allowlist.py +2 -2
  26. diffmem_mcp_server-0.1.2/tests/test_spaces_tool_error_surface.py +126 -0
  27. diffmem_mcp_server-0.1.2/tests/test_tool_error_paths.py +78 -0
  28. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.2}/uv.lock +7 -7
  29. diffmem_mcp_server-0.1.0/CHANGELOG.md +0 -16
  30. diffmem_mcp_server-0.1.0/diffmem_mcp/router.py +0 -108
  31. diffmem_mcp_server-0.1.0/diffmem_mcp/settings.py +0 -63
  32. diffmem_mcp_server-0.1.0/diffmem_mcp/tools/memory.py +0 -248
  33. diffmem_mcp_server-0.1.0/tests/test_router.py +0 -158
  34. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.2}/.gitignore +0 -0
  35. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.2}/Dockerfile +0 -0
  36. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.2}/diffmem_mcp/__init__.py +0 -0
  37. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.2}/diffmem_mcp/scopes.py +0 -0
  38. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.2}/diffmem_mcp/security.py +0 -0
  39. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.2}/diffmem_mcp/tools/__init__.py +0 -0
  40. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.2}/tests/__init__.py +0 -0
  41. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.2}/tests/test_scope_enforcement.py +0 -0
  42. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.2}/tests/test_security.py +0 -0
  43. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.2}/tests/test_self_containment.py +0 -0
@@ -0,0 +1,45 @@
1
+ # Changelog
2
+
3
+ All notable changes to the `diffmem-mcp-server` package are documented here.
4
+ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versions follow [SemVer](https://semver.org/).
5
+
6
+ ## [Unreleased]
7
+
8
+ ### Removed
9
+ - **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.
10
+
11
+ ### Changed
12
+ - **Capture copy package (issue #227):** `ingest_memory` now ships the trigger-shaped description and the server emits the normative-frame `instructions` on InitializeResult — both verbatim from the 017-validated, operator-tested prototype package (`diffmem_mcp/copy_prototype.py`, full treatment). All Claude-facing copy is single-sourced in `diffmem_mcp/copy.py`; `check_save_status`'s description moves there too (byte-identical to what already shipped in #226). Contract tests pin byte-equality to the prototype and assert the instructions reach InitializeResult. The proactivity effect was validated for the package as a whole — the marginal contribution of each copy element was not measured, so no copy or changelog text claims one.
13
+ - **Fire-and-forget ingest (issue #226):** smart-routed `ingest_memory` saves (no `space_id`) now hit the plane's async endpoint and ack `{"status": "accepted", "save_id"}` in under a second instead of blocking up to 120 s on the pipeline; synchronous preflight errors (quota, LLM-creds, content, space denial) still surface verbatim. The targeted `space_id` sync path is unchanged. `ingest_memory`'s name and signature stay frozen. Smart-routed results are no longer returned inline — poll `check_save_status`.
14
+
15
+ ### Added
16
+ - New tool `check_save_status(save_id)`: reads the plane's save-status endpoint (`GET /v1/memory/saves/{save_id}`, project-scoped by key) and maps the ladder — queued/processing/committed/failed, 404 → "no such save", other errors → degraded envelope, never raises raw. Requires `memory:write` (mirrors the plane's strictly-additive scope rule).
17
+ - Honest tool annotations: `ingest_memory` is `readOnlyHint/destructiveHint/idempotentHint` all false (a second call is a second save); `check_save_status` is a read (`readOnlyHint: true`).
18
+
19
+ ### Fixed
20
+ - HTTP transports reject bad credentials at the HTTP layer: missing/invalid key → 401 (`WWW-Authenticate: Bearer`), key for another project → 403 `project_mismatch`, validation outage → 503 `auth_unavailable`. Previously `initialize` succeeded for any caller and failures surfaced only inside tool results.
21
+ - `retrieve_context` spoke a stale contract: it sent `conversation` + `{project_id, space_id}` objects (engine 422 / RP `space_denied` for allowlisted keys) and read a non-existent `context` field. It now sends `{query, spaces: [bare ids]}`, returns the engine's `response` with `retrieval_status`, and reports engine `status=failed` as `retrieval_failed`.
22
+ - Tool denial handlers: `list_spaces`/`get_space_info` raised `NameError` (missing `SecurityError` import) and every tool's handler dereferenced a non-existent `ctx.auth`, turning auth and scope denials into `internal_error`. `AuthError` is now a `SecurityError`, so tools return the machine code (`invalid_api_key`, `insufficient_scope`, ...).
23
+
24
+ ## [0.1.1] — 2026-11-06
25
+
26
+ ### Changed
27
+ - **BREAKING (pre-1.0, not yet public):** stdio configuration takes a single `DIFFMEM_API_URL` (default `https://api.diffmem.com`) instead of the `DIFFMEM_API_URLS` region→URL JSON map (ADR-045). Region routing belongs to the service edge — the GLB path-routes `/p/{project_id}/*` by the `project_id` prefix — so client configuration no longer carries region knowledge or internal topology.
28
+ - `router.py` reduced to project_id format validation (`ROUTER_UNPARSEABLE_PROJECT`); the region→URL resolution and `ROUTER_REGION_NOT_DEPLOYED` code are gone with the map.
29
+ - Removed the deprecated `REGIONAL_PLANE_URLS` alias window (package had no external users yet).
30
+ - Auth validation targets the single base URL; the sorted-first-URL bootstrap is gone.
31
+
32
+ ### Fixed
33
+ - Example project IDs in docs/tests used a character outside the base32 suffix alphabet (`x7k2p9mz` → `x7k2p3mz`).
34
+
35
+ ## [0.1.0] — 2026-10-30
36
+
37
+ ### Added
38
+ - MCP server exposing DiffMem memory APIs as tools: `list_spaces`, `get_space_info`, `list_files`, `read_file`, `get_project_status`, `ingest_memory`, `retrieve_context`.
39
+ - Transports: stdio (desktop clients), streamable HTTP (stateless, recommended remote), legacy SSE (deprecated).
40
+ - Security-first design: API-key-derived project scope, server-side space access validation, pre-write quota enforcement, per-key token-bucket rate limiting, audit logging with hashed key IDs.
41
+ - Regional routing (ADR-030): region derived from `project_id` prefix; no fallback region, no cache — malformed/undeployed regions fail loud.
42
+ - Streamable HTTP is stateless (ADR-039): no session pinning, JSON responses, proxy-friendly.
43
+ - Auth bridge keys validated via the DiffMem API (ADR-008) — no local Firestore lookup.
44
+ - Console script `diffmem-mcp-server` (stdio by default; `--sse --host --port` for HTTP transports).
45
+ - Wheel self-containment test: build → scratch-env install → console script `--help` → standalone import with no repo context.
@@ -24,18 +24,19 @@ Standalone MCP (Model Context Protocol) server that exposes DiffMem's public mem
24
24
 
25
25
  ## Key Files
26
26
  - `diffmem_mcp/server.py` — MCP server instance; console-script entry `cli()` → `diffmem-mcp-server` (stdio default, `--sse` HTTP) and SSE entry (`main_sse`) kept for direct/local runs (the GLB never rewrites paths — remote traffic enters via the RP's project-scoped mount instead) + root `/health`
27
- - `diffmem_mcp/asgi.py` — ASGI app factory: AuthHeaderMiddleware (Bearer → per-request contextvar identity — NEVER os.environ; pre-ADR-030 env bridge was a cross-tenant race) + `/health` route + FastMCP SSE app mounted at `/`; **prefix-agnostic** (RP mounts it at `/p/{project_id}/mcp`)
27
+ - `diffmem_mcp/asgi.py` — ASGI app factory: AuthHeaderMiddleware (Bearer → per-request contextvar identity — NEVER os.environ; pre-ADR-030 env bridge was a cross-tenant race; validates the key on every `/mcp*` request: 401 missing/invalid, 403 `project_mismatch`, 503 `auth_unavailable`) + `/health` route + FastMCP SSE app mounted at `/`; **prefix-agnostic** (RP mounts it at `/p/{project_id}/mcp`)
28
28
  - `diffmem_mcp/context.py` — DiffMemContext: per-key-hash auth cache with 60s TTL re-validation (revocations/scope edits propagate within the bounded window); rejects key/project mismatch from the project-scoped mount (`project_mismatch`)
29
29
  - `diffmem_mcp/scopes.py` — scope vocabulary mirror + enforce_scope (fail-closed; mirrors regional-plane `app/core/scopes.py`)
30
- - `diffmem_mcp/auth.py` — API key validation via DiffMem API `GET /v1/auth/validate` (no local Firestore; 401 → `invalid_api_key`, 5xx/network → transient `auth_unavailable`)
30
+ - `diffmem_mcp/auth.py` — API key validation via regional-plane `GET /v1/auth/validate` (no local Firestore; 401 → `invalid_api_key`, 5xx/network → transient `auth_unavailable`; "DiffMem API" = regional-plane public surface — the control plane validates nothing)
31
31
  - `diffmem_mcp/security.py` — Space-allowlist gates, rate limiting, audit logging (space-existence/quota checks are plane-enforced)
32
- - `diffmem_mcp/router.py` — Region routing (project_id → region → API URL); public-language errors (`region_not_deployed` → "check the DIFFMEM_API_URLS setting")
33
- - `diffmem_mcp/settings.py` — Environment-based configuration; `DIFFMEM_API_URLS` env (JSON region→URL map; deprecated alias `REGIONAL_PLANE_URLS` warns and works until its window closes — de-topologized 2026-10-26 per ADR-037 vocabulary)
32
+ - `diffmem_mcp/router.py` — project_id format validation only (ADR-045: the GLB routes, the client doesn't); loud `ROUTER_UNPARSEABLE_PROJECT` errors; PROJECT_ID_PATTERN drift-tested against control-plane + GLB url-map
33
+ - `diffmem_mcp/settings.py` — Environment-based configuration; `DIFFMEM_API_URL` env (single base URL, default `https://api.diffmem.com`; ADR-045 collapsed the region→URL map — routing belongs to the GLB edge)
34
+ - `diffmem_mcp/copy.py` — single source of Claude-facing copy: server `instructions` (normative frame, emitted on InitializeResult) + `ingest_memory`/`check_save_status` descriptions. Every string is verbatim from the 017-validated package (VARIANTS["B"], issue #227; the prototype harness was retired post-ship in #229 — ticket 017 remains the wording's primary record); the live-wire contract tests in `tests/test_capture_copy_contract.py` pin what a real client sees to this module. No copy text attributes the proactivity effect to a specific copy element (the package was validated as a whole; spec §7)
34
35
  - `diffmem_mcp/tools/` — MCP tool implementations (spaces, memory, files, project)
35
36
 
36
37
  ## External Dependencies
37
38
  - Schema: `docs/schema.md` § Regional-Plane Data (high level only — regional collections `api_keys`/`tenant_configs`/`diffmem_spaces` have no dedicated sections yet; detail lives in `services/regional-plane/app/models/`)
38
- - APIs: Regional-plane public endpoints (`/p/{project_id}/v1/memory/process`, `/p/{project_id}/v1/context`, etc.)
39
+ - APIs: Regional-plane public endpoints (`/p/{project_id}/v1/memory/process`, `/p/{project_id}/v1/context`, etc.). Async ingest (issue #226): smart-routed saves POST `/p/{project_id}/v1/memory/process` and ack 202 `{"status": "accepted", "save_id"}` — preflight (allowlist/quota/LLM-creds/content) stays synchronous, the pipeline runs behind Cloud Tasks; the targeted `space_id` sync path (`/p/{project_id}/v1/spaces/{sid}/memory/process`) keeps its legacy 120 s behavior (spec 10-mcp-memory-capture §12). Save status: GET `/v1/memory/saves/{save_id}` — project-scoped by the API key, NOT the path (no `/p/{project_id}` prefix; spec §5.4); reachable because the co-located MCP talks to its own plane (RP loopback default) — the GLB would catch-all a bare `/v1/*` other than `/v1/auth/validate`.
39
40
 
40
41
  ## Constraints
41
42
  - `project_id` is NEVER a tool parameter — derived from the validated API key
@@ -46,7 +47,7 @@ Standalone MCP (Model Context Protocol) server that exposes DiffMem's public mem
46
47
  - All tool invocations are audit-logged with structured events
47
48
  - Distribution posture: external users get the **distributed package** (`uvx diffmem-mcp-server`); the checkout invocation is dev-only (see Terminology). Repo docs must never present the checkout form as a user/onboarding path — client configs use `command: uvx`.
48
49
  - The bridge has NO Firestore access and NO GCP dependencies: `diffmem_mcp` depends only on mcp/httpx/pydantic (all storage access lives behind the regional-plane API; the public `/v1/auth/validate`, `/p/{id}/v1/spaces`, and `/p/{id}/v1/project/status` routes serve the introspection surface the bridge used to read from Firestore directly)
49
- - ARCHITECTURE (ADR-030, implemented in SESSION_SPEC_2026-10-16-002): the MCP is co-located inside every regional plane at `/p/{project_id}/mcp` and edge-routed by the GLB's `/p/proj_{region}_*` rules. The standalone service, GLB `/mcp/*` rule, `RegionalRouter` Firestore machinery, and every `DEFAULT_REGION` fallback are DECOMMISSIONED. stdio keeps a pure prefix parser (`router.py`) that fails loud (`ROUTER_UNPARSEABLE_PROJECT` / `ROUTER_REGION_NOT_DEPLOYED`). Do NOT write `region` into `tenant_configs`, do NOT reintroduce a default-region fallback, and keep the build context at `diffMemPlatform/services/` (the RP Dockerfile ships `diffmem_mcp`).
50
+ - ARCHITECTURE (ADR-030, implemented in SESSION_SPEC_2026-10-16-002; env-map half superseded by ADR-045): the MCP is co-located inside every regional plane at `/p/{project_id}/mcp` and edge-routed by the GLB's `/p/proj_{region}_*` rules. The standalone service, GLB `/mcp/*` rule, `RegionalRouter` Firestore machinery, and every `DEFAULT_REGION` fallback are DECOMMISSIONED. ADR-045 also removed the client-side region→URL map: stdio targets a single `DIFFMEM_API_URL` and the GLB does the routing; `router.py` is format validation only (`ROUTER_UNPARSEABLE_PROJECT`). Do NOT write `region` into `tenant_configs`, do NOT reintroduce a default-region fallback or a client-side URL map, and keep the build context at `diffMemPlatform/services/` (the RP Dockerfile ships `diffmem_mcp`).
50
51
 
51
52
  ## Attention Guidance
52
53
  - When changing tool signatures: also update `diffmem_mcp/security.py` validation
@@ -57,6 +58,5 @@ Standalone MCP (Model Context Protocol) server that exposes DiffMem's public mem
57
58
  - Package was renamed from `app` to `diffmem_mcp` to avoid namespace conflicts with regional-plane
58
59
 
59
60
  ## Deployment (as of 2026-10-16 — deployed to prod)
60
- - **Production** (ADR-030): the MCP sub-app ships INSIDE every regional-plane image (RP Dockerfile COPYs `diffmem_mcp`; build context `diffMemPlatform/services/`) and mounts at `/p/{project_id}/mcp`, edge-routed by the GLB's `/p/proj_{region}_*` rules. `ENABLE_MCP_SERVER=true` in every env. SSE auth: per-request contextvar identity + per-key TTL cache (no env-var bridge). Old `/mcp/*` routes 404 by design. Full runbook: `PRODUCTION_DEPLOYMENT.md`.
61
- - **Staging**: Co-located with regional-plane at `/mcp` (set `ENABLE_MCP_SERVER=true` — STAGING-ONLY flag; do not enable in prod). The ASGI app is prefix-agnostic; RP owns the `/mcp` mount.
61
+ - **Production** (ADR-030; client contract ADR-045): the MCP sub-app ships INSIDE every regional-plane image (RP Dockerfile COPYs `diffmem_mcp`; build context `diffMemPlatform/services/`) and mounts at `/p/{project_id}/mcp`, edge-routed by the GLB's `/p/proj_{region}_*` rules. `ENABLE_MCP_SERVER=true` in every env. The RP defaults `DIFFMEM_API_URL` to its own loopback (`http://127.0.0.1:$PORT`): the public edge is unreachable through all-traffic VPC egress and fronts a different env than dogfood (GK corporate memory is on dogfood: `https://staging.api.diffmem.com/p/{project_id}/mcp`). SSE auth: per-request contextvar identity + per-key TTL cache (no env-var bridge). Old `/mcp/*` routes 404 by design. Full runbook: `PRODUCTION_DEPLOYMENT.md`.
62
62
  - Dockerfile copies `diffmem_mcp/` (NOT the pre-rename `app/`) and runs `python -m diffmem_mcp.server --sse`.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: diffmem-mcp-server
3
- Version: 0.1.0
3
+ Version: 0.1.2
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
@@ -134,19 +134,17 @@ covered in [README.md](README.md) § "Running Directly".
134
134
  "command": "uvx",
135
135
  "args": ["diffmem-mcp-server"],
136
136
  "env": {
137
- "DIFFMEM_API_KEY": "dm_...",
138
- "DIFFMEM_API_URLS": "{\"eu\": \"https://eu-api.diffmem.com\"}"
137
+ "DIFFMEM_API_KEY": "dm_..."
139
138
  }
140
139
  }
141
140
  }
142
141
  }
143
142
  ```
144
143
 
145
- stdio has no GLB, so the server derives the region from the `project_id`
146
- prefix (`router.py`) and picks the base URL from `DIFFMEM_API_URLS`.
147
- There is **no default region**: a malformed project ID or a region absent
148
- from the map fails loud (`ROUTER_UNPARSEABLE_PROJECT` /
149
- `ROUTER_REGION_NOT_DEPLOYED`).
144
+ stdio targets the single `DIFFMEM_API_URL` base (default
145
+ `https://api.diffmem.com`); the GLB edge-routes `/p/{project_id}/*` by the
146
+ `project_id` prefix, so the client carries no region knowledge (ADR-045).
147
+ A malformed project ID fails loud (`ROUTER_UNPARSEABLE_PROJECT`).
150
148
 
151
149
  ## Environment variables
152
150
 
@@ -160,7 +158,7 @@ stdio only:
160
158
  | Variable | Required | Purpose |
161
159
  |---|---|---|
162
160
  | `DIFFMEM_API_KEY` | Yes | API key (`dm_...`) |
163
- | `DIFFMEM_API_URLS` | Yes | JSON map region → base URL (one entry per deployed region). Deprecated alias `REGIONAL_PLANE_URLS` still works (warns) |
161
+ | `DIFFMEM_API_URL` | No | DiffMem API base URL (default `https://api.diffmem.com`; override only for local dev) |
164
162
  | `GOOGLE_CLOUD_PROJECT` | No | Firestore project for local key validation |
165
163
 
166
164
  (`DEFAULT_REGION` and `MCP_IMAGE_TAG` are GONE — the first was the silent
@@ -39,9 +39,8 @@ Legacy Server-Sent Events transport at `/p/{project_id}/mcp/sse`. Still served u
39
39
 
40
40
  ### Prerequisites
41
41
 
42
- - Python 3.12+
43
- - Firebase project with Firestore enabled
44
- - DiffMem API key (create via dashboard or regional-plane API)
42
+ - Python 3.12+ (installed automatically by `uvx`)
43
+ - DiffMem API key (create via dashboard or the DiffMem API)
45
44
 
46
45
  ### Installation
47
46
 
@@ -69,14 +68,13 @@ pip install -e .
69
68
  | Variable | Required | Default | Description |
70
69
  |----------|----------|---------|-------------|
71
70
  | `DIFFMEM_API_KEY` | Yes | — | DiffMem API key for authentication |
72
- | `GOOGLE_CLOUD_PROJECT` | No | `demo-local` | GCP project for Firestore |
73
- | `REGIONAL_PLANE_URLS` | No | `{"us": "http://localhost:8080"}` | JSON mapping of region → URL (stdio resolution) |
71
+ | `DIFFMEM_API_URL` | No | `https://api.diffmem.com` | DiffMem API base URL — override only for local development. The regional-plane-hosted MCP defaults it to its own plane over loopback (`http://127.0.0.1:$PORT`) |
74
72
  | `MCP_RATE_LIMIT_RPM` | No | `60` | Rate limit per API key (requests/min) |
75
73
 
76
- ADR-030: region is derived from the `project_id` prefix (`proj_{region}_...`)
77
- — there is NO `DEFAULT_REGION` fallback and NO region cache. Malformed IDs or
78
- undeployed regions fail loud (`ROUTER_UNPARSEABLE_PROJECT` /
79
- `ROUTER_REGION_NOT_DEPLOYED`).
74
+ ADR-045: one base URL. Routing to your project's home region happens at the
75
+ service edge via the `project_id` in the URL path — the client config carries
76
+ no region knowledge. A malformed `project_id` fails loud
77
+ (`ROUTER_UNPARSEABLE_PROJECT`).
80
78
 
81
79
  ## MCP Client Configuration
82
80
 
@@ -91,8 +89,7 @@ Add to `~/Library/Application Support/Claude/claude_desktop_config.json`:
91
89
  "command": "uvx",
92
90
  "args": ["diffmem-mcp-server"],
93
91
  "env": {
94
- "DIFFMEM_API_KEY": "dm_your_api_key_here",
95
- "REGIONAL_PLANE_URLS": "{\"eu\": \"https://eu-api.diffmem.com\", \"us\": \"https://us-api.diffmem.com\"}"
92
+ "DIFFMEM_API_KEY": "dm_your_api_key_here"
96
93
  }
97
94
  }
98
95
  }
@@ -125,8 +122,7 @@ Add to `.cursor/mcp.json`:
125
122
  "command": "uvx",
126
123
  "args": ["diffmem-mcp-server"],
127
124
  "env": {
128
- "DIFFMEM_API_KEY": "dm_your_api_key_here",
129
- "REGIONAL_PLANE_URLS": "{\"eu\": \"https://eu-api.diffmem.com\"}"
125
+ "DIFFMEM_API_KEY": "dm_your_api_key_here"
130
126
  }
131
127
  }
132
128
  }
@@ -158,9 +154,10 @@ Add to `.cursor/mcp.json`:
158
154
  ### stdio Mode (Local)
159
155
 
160
156
  ```bash
161
- # Set environment variables
157
+ # Set environment variables (DIFFMEM_API_URL defaults to https://api.diffmem.com;
158
+ # point it at your local regional-plane service when developing in this repo)
162
159
  export DIFFMEM_API_KEY="dm_your_api_key_here"
163
- export REGIONAL_PLANE_URLS='{"eu": "https://eu-api.diffmem.com"}' # stdio only
160
+ export DIFFMEM_API_URL="http://localhost:8080"
164
161
 
165
162
  # Run the server
166
163
  python -m diffmem_mcp.server
@@ -171,7 +168,7 @@ python -m diffmem_mcp.server
171
168
  ```bash
172
169
  # Set environment variables
173
170
  export DIFFMEM_API_KEY="dm_your_api_key_here"
174
- export REGIONAL_PLANE_URLS='{"eu": "https://eu-api.diffmem.com"}' # stdio only
171
+ export DIFFMEM_API_URL="http://localhost:8080"
175
172
 
176
173
  # Run with HTTP transports (streamable at /mcp, legacy SSE at /sse)
177
174
  python -m diffmem_mcp.server --sse --host 0.0.0.0 --port 3001
@@ -222,7 +219,7 @@ diffmem_mcp/
222
219
  ├── __init__.py
223
220
  ├── asgi.py # HTTP ASGI adapter (streamable + SSE) for FastAPI mounting
224
221
  ├── auth.py # API key validation (SHA-256 hash lookup)
225
- ├── router.py # Regional routing (project → region → URL)
222
+ ├── router.py # project_id format validation (ADR-045: the GLB routes, not the client)
226
223
  ├── security.py # Space validation, quota, rate limiting
227
224
  ├── server.py # MCP server instance & entry point
228
225
  ├── settings.py # Environment configuration
@@ -1,6 +1,8 @@
1
- """HTTP client for calling regional-plane APIs.
1
+ """HTTP client for calling the DiffMem API.
2
2
 
3
- Handles Bearer token forwarding, error mapping, and regional routing.
3
+ Handles Bearer token forwarding and upstream error mapping. ADR-045: the
4
+ client does no routing — the base URL is a single setting and the GLB
5
+ edge-routes /p/{project_id}/* by the project_id path prefix.
4
6
  """
5
7
 
6
8
  from __future__ import annotations
@@ -92,12 +92,53 @@ class AuthHeaderMiddleware:
92
92
  identity.path_project_id,
93
93
  )
94
94
  try:
95
+ if scope["type"] == "http" and _is_mcp_transport_path(scope["path"]):
96
+ denial = await _http_auth_denial(identity)
97
+ if denial is not None:
98
+ return await denial(scope, receive, send)
95
99
  return await self.app(scope, receive, send)
96
100
  finally:
97
101
  if token is not None:
98
102
  _current_identity.reset(token)
99
103
 
100
104
 
105
+ def _is_mcp_transport_path(path: str) -> bool:
106
+ """Streamable (/mcp) and SSE (/mcp/sse, /mcp/messages) routes; /health and unknown paths stay ungated."""
107
+ return path.endswith("/mcp") or "/mcp/" in path
108
+
109
+
110
+ _DENIAL_STATUS = {
111
+ "missing_api_key": 401,
112
+ "invalid_api_key": 401,
113
+ "unparseable_project": 401,
114
+ "project_mismatch": 403,
115
+ }
116
+
117
+
118
+ async def _http_auth_denial(identity: RequestIdentity):
119
+ """Validate the request's key before any MCP session work; a JSON error response on failure, else None."""
120
+ from starlette.responses import JSONResponse
121
+
122
+ from diffmem_mcp.auth import AuthError
123
+ from diffmem_mcp.context import get_context
124
+
125
+ try:
126
+ await get_context().get_auth()
127
+ return None
128
+ except AuthError as exc:
129
+ status = _DENIAL_STATUS.get(exc.code, 503)
130
+ logger.warning(
131
+ "MCP_HTTP_AUTH_DENIED: code=%s status=%s path_project_id=%s",
132
+ exc.code,
133
+ status,
134
+ identity.path_project_id,
135
+ )
136
+ headers = {"WWW-Authenticate": 'Bearer realm="diffmem"'} if status == 401 else None
137
+ return JSONResponse(
138
+ {"error": {"code": exc.code, "message": exc.message}}, status_code=status, headers=headers
139
+ )
140
+
141
+
101
142
  def create_mcp_asgi_app() -> Starlette:
102
143
  """Create a Starlette ASGI app with streamable HTTP + SSE routes.
103
144
 
@@ -1,14 +1,16 @@
1
1
  """API key validation for the MCP server.
2
2
 
3
- Validates DiffMem API keys via the DiffMem API's ``GET /v1/auth/validate``
3
+ Validates DiffMem API keys via the regional plane's ``GET /v1/auth/validate``
4
4
  endpoint — the same Bearer-key mechanism every tool call uses. No local
5
5
  Firestore: customer machines have no GCP credentials, and validation must
6
6
  work identically for stdio (env key) and hosted SSE (Authorization header).
7
7
 
8
- Validation is region-agnostic (every regional-plane instance can validate any
9
- key — it self-validates on every public route), so the validator targets a
10
- deterministic base URL from DIFFMEM_API_URLS and the per-call router handles
11
- region routing afterward, once project_id is known.
8
+ Validation is region-agnostic (every regional plane can validate any key —
9
+ key hashes live in the project-default Firestore and each plane self-
10
+ validates on every public route), so the validator targets the single
11
+ DIFFMEM_API_URL base (ADR-045); the GLB edge routes the un-prefixed
12
+ validate path to a regional plane, and the project_id path prefix handles
13
+ region selection on every subsequent call.
12
14
 
13
15
  For stdio transport, the API key is provided via the DIFFMEM_API_KEY
14
16
  environment variable (set by the MCP client, e.g. Claude Desktop or Cursor).
@@ -19,10 +21,13 @@ from __future__ import annotations
19
21
  import logging
20
22
  import os
21
23
  from dataclasses import dataclass
22
- from typing import Mapping, Optional
24
+ from typing import Optional
23
25
 
24
26
  import httpx
25
27
 
28
+ from diffmem_mcp.router import UnparseableProjectError, validate_project_id
29
+ from diffmem_mcp.security import SecurityError
30
+
26
31
  logger = logging.getLogger(__name__)
27
32
 
28
33
  _VALIDATE_PATH = "/v1/auth/validate"
@@ -36,7 +41,7 @@ class AuthContext:
36
41
  key_id: str
37
42
  project_id: str
38
43
  label: str
39
- raw_key: str # Retained for forwarding to regional-plane as Bearer token
44
+ raw_key: str # Retained for forwarding to the DiffMem API as Bearer token
40
45
  # Null = legacy key / full access (spec #77 §4). A non-null list is the
41
46
  # key's exact powers — strictly additive, no implied scopes.
42
47
  scopes: Optional[list[str]] = None
@@ -46,39 +51,34 @@ class AuthContext:
46
51
  space_allowlist: Optional[list[str]] = None
47
52
 
48
53
 
49
- class AuthError(Exception):
54
+ class AuthError(SecurityError):
50
55
  """Raised when API key validation fails."""
51
56
 
52
- def __init__(self, code: str, message: str):
53
- self.code = code
54
- self.message = message
55
- super().__init__(message)
57
+ # WHY: a SecurityError subclass so every tool's denial handler returns the machine code.
56
58
 
57
59
 
58
60
  class ApiKeyValidator:
59
61
  """Validates DiffMem API keys against the DiffMem API.
60
62
 
61
63
  Usage:
62
- validator = ApiKeyValidator(api_urls)
64
+ validator = ApiKeyValidator(base_url)
63
65
  ctx = await validator.validate("dk_abc123...")
64
66
 
65
67
  Args:
66
- api_urls: parsed DIFFMEM_API_URLS map (region → base URL). Any entry
67
- works for validation; the sorted-first URL is chosen for
68
- determinism.
68
+ base_url: the single DIFFMEM_API_URL base (ADR-045).
69
69
  """
70
70
 
71
71
  def __init__(
72
72
  self,
73
- api_urls: Mapping[str, str],
73
+ base_url: str,
74
74
  transport: httpx.AsyncBaseTransport | None = None,
75
75
  ) -> None:
76
- if not api_urls:
76
+ if not base_url:
77
77
  raise AuthError(
78
78
  code="config_error",
79
- message="DIFFMEM_API_URLS is empty — no API endpoint to validate against.",
79
+ message="DIFFMEM_API_URL is empty — no API endpoint to validate against.",
80
80
  )
81
- self._base_url = sorted(api_urls.values())[0].rstrip("/")
81
+ self._base_url = base_url.rstrip("/")
82
82
  self._transport = transport # test seam: inject httpx.MockTransport
83
83
 
84
84
  async def validate(self, raw_key: str) -> AuthContext:
@@ -137,6 +137,15 @@ class ApiKeyValidator:
137
137
  message="API key is not associated with a project.",
138
138
  )
139
139
 
140
+ # Format contract, not routing: the GLB routes by the /p/proj_{region}_*
141
+ # prefix, so a malformed ID would only surface as an opaque upstream
142
+ # 404. Fail loud here instead (router.py owns the pattern).
143
+ try:
144
+ validate_project_id(project_id)
145
+ except UnparseableProjectError as exc:
146
+ logger.error("AUTH_UNPARSEABLE_PROJECT: project_id=%s", project_id)
147
+ raise AuthError(code="unparseable_project", message=str(exc)) from exc
148
+
140
149
  logger.info("AUTH_SUCCESS: key_id=%s project_id=%s", key_id, project_id)
141
150
 
142
151
  return AuthContext(
@@ -69,7 +69,7 @@ class DiffMemContext:
69
69
  # Firestore — customer machines have no GCP credentials).
70
70
  from diffmem_mcp.settings import get_settings
71
71
 
72
- self._validator = ApiKeyValidator(get_settings().get_api_urls())
72
+ self._validator = ApiKeyValidator(get_settings().get_api_url())
73
73
  auth = await self._validator.validate(raw_key)
74
74
  self._auth_cache[key_hash] = _CacheEntry(auth=auth, cached_at=now)
75
75
  if len(self._auth_cache) > _MAX_AUTH_CACHE:
@@ -0,0 +1,64 @@
1
+ """Claude-facing copy — the single production source for tool descriptions
2
+ and server ``instructions`` (issue #227, spec 10-mcp-memory-capture §6).
3
+
4
+ Every string is verbatim from the 017-validated prototype package
5
+ ``VARIANTS["B"]`` — operator-tested in Claude Desktop (wayfinder ticket 017,
6
+ spec 10-mcp-memory-capture §6) — and this module is its single source since
7
+ the prototype harness was retired post-ship (issue #229; ticket 017 remains
8
+ the wording's primary record).
9
+
10
+ Attribution discipline (spec §7): the A-vs-B treatment was validated as a
11
+ package and the B-vs-C lever split was not measured — nothing here may claim
12
+ which lever carried the effect. The copy stands alone for any MCP client.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ # Normative frame only — no duplication of description content, no client
18
+ # named, no behavior claims beyond the frame (spec §6.3).
19
+ SERVER_INSTRUCTIONS = (
20
+ "DiffMem is this project's persistent memory. Save memory-worthy "
21
+ "exchanges to it proactively, without being asked, and search it with "
22
+ "retrieve_context before answering from memory. Do not wait for the user "
23
+ "to request a save."
24
+ )
25
+
26
+ # Trigger-shaped ingest copy (the capture contract, spec §6.1): concrete
27
+ # triggers + negative space + one-save-per-exchange cap + content shape +
28
+ # smart-routing default + the fire-and-forget ack line.
29
+ INGEST_MEMORY_DESCRIPTION = """Save a memory to DiffMem, the project's persistent memory store.
30
+
31
+ Call this yourself when the exchange is memory-worthy — do not wait to be asked:
32
+ - The user explicitly asks you to remember or save something. Pass their words
33
+ through near-verbatim in `content`.
34
+ - A stable fact surfaces: preferences, constraints, decisions and their
35
+ outcomes, the project's stack, people's names or roles, ongoing work.
36
+ - The user corrects something already saved. Save the correction as a plain
37
+ statement; consolidation resolves the conflict downstream.
38
+
39
+ Do not call when:
40
+ - The exchange is routine conversation or a one-off question.
41
+ - You are unsure whether it is memory-worthy — when unsure, don't save.
42
+ - You already saved in this exchange. At most one save per exchange; batch
43
+ related facts into a single call.
44
+
45
+ How to compose `content`:
46
+ - Proactive saves: write short, distilled, self-contained statements. You hold
47
+ the conversation context the pipeline never sees — put it in the content.
48
+ - Explicit "remember this" requests: pass the user's words through near-raw.
49
+
50
+ Leave `space_id` empty unless the user explicitly named a target space —
51
+ smart routing picks the right space for you.
52
+
53
+ Returns {"status": "accepted", "save_id"} in under a second; processing
54
+ continues in the background. Check a save later with check_save_status(save_id)."""
55
+
56
+ CHECK_SAVE_STATUS_DESCRIPTION = """Check the outcome of a memory save made with ingest_memory.
57
+
58
+ Returns the save's current state: queued, processing, committed, or failed
59
+ (with an error code). Use when the user asks whether something was saved or
60
+ saved correctly — saves are not announced automatically, this tool is the only
61
+ way to see a failure.
62
+
63
+ Args:
64
+ save_id: The save_id returned by the ingest_memory call to check."""
@@ -0,0 +1,59 @@
1
+ # CAPABILITY: project_id format validation — the client-side half of the
2
+ # routing contract. ADR-045: the MCP server no longer routes; the GLB
3
+ # path-routes /p/{project_id}/* by the project_id prefix and the server
4
+ # targets a single base URL. What remains here is the format contract: a
5
+ # malformed ID fails loud with a public-language error instead of surfacing
6
+ # as an opaque upstream 404.
7
+ # INPUTS: project_id (proj_{region}_{8-char base32})
8
+ # OUTPUTS: validated project_id, or UnparseableProjectError
9
+ # CONSTRAINTS: PURE and SYNCHRONOUS — no Firestore, no async, no cache.
10
+
11
+ """project_id format validation for the DiffMem MCP server.
12
+
13
+ ADR-030 put the region inside the project_id (``proj_{region}_{8-char
14
+ base32}``) so edge routing and any client-side routing agree by construction.
15
+ ADR-045 removed the client-side region→URL map that consumed the prefix:
16
+ routing belongs to the GLB. The format itself is still the shared contract,
17
+ kept in sync (drift test asserts this) with:
18
+
19
+ - ``control-plane/app/utils/project_id.py`` — PROJECT_ID_PATTERN, format spec
20
+ - ``global-load-balancer/url-map.tf`` — /p/proj_{region}_* path rules
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import logging
26
+ import re
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+ __all__ = ["PROJECT_ID_PATTERN", "UnparseableProjectError", "validate_project_id"]
31
+
32
+ # Same contract as control-plane/app/utils/project_id.py — a drift test asserts
33
+ # the two regexes are string-identical. No capture group: nothing client-side
34
+ # consumes the region anymore (ADR-045).
35
+ PROJECT_ID_PATTERN = re.compile(r"^proj_[a-z]{2}_[a-z2-7]{8}$")
36
+
37
+
38
+ class UnparseableProjectError(Exception):
39
+ """A project_id violates the proj_{region}_{suffix} contract — fail loud."""
40
+
41
+ def __init__(self, message: str):
42
+ super().__init__(message)
43
+
44
+
45
+ def validate_project_id(project_id: str) -> str:
46
+ """Validate a project_id's format; return it unchanged.
47
+
48
+ Raises:
49
+ UnparseableProjectError: the ID violates the contract. Never falls
50
+ back silently — a malformed ID is a loud error, never a quiet
51
+ misroute.
52
+ """
53
+ if not PROJECT_ID_PATTERN.match(project_id):
54
+ logger.error("ROUTER_UNPARSEABLE_PROJECT: project_id=%s", project_id)
55
+ raise UnparseableProjectError(
56
+ f"project_id '{project_id}' does not match proj_{{region}}_{{8-char base32}} "
57
+ "(e.g. proj_eu_x7k2p3mz); refusing to route it anywhere by default."
58
+ )
59
+ return project_id
@@ -26,6 +26,10 @@ from mcp.server.transport_security import TransportSecuritySettings
26
26
  # testable without the FastMCP import.
27
27
  from diffmem_mcp.context import DiffMemContext, get_context # noqa: F401 (re-export)
28
28
 
29
+ # Claude-facing copy (issue #227): the server instructions are the 017-validated
30
+ # normative frame, single-sourced in copy.py — emitted on InitializeResult.
31
+ from diffmem_mcp.copy import SERVER_INSTRUCTIONS
32
+
29
33
  logger = logging.getLogger(__name__)
30
34
 
31
35
  # ---------------------------------------------------------------------------
@@ -34,12 +38,11 @@ logger = logging.getLogger(__name__)
34
38
 
35
39
  mcp = FastMCP(
36
40
  "DiffMem",
37
- instructions=(
38
- "DiffMem memory management server. Use these tools to interact with "
39
- "DiffMem memory spaces — ingest content, retrieve context, manage files, "
40
- "and inspect project configuration. All operations are scoped to the "
41
- "authenticated project; you do not need to provide a project_id."
42
- ),
41
+ # Issue #227 (spec 10-mcp-memory-capture §6.3): the 017-validated normative
42
+ # frame, not the old capability inventory — the frame is the proactivity
43
+ # lever validated as part of the copy package (no lever attribution: the
44
+ # B-vs-C split was not measured).
45
+ instructions=SERVER_INSTRUCTIONS,
43
46
  # ADR-039: streamable HTTP is stateless (no Mcp-Session-Id, no per-session
44
47
  # server-side state) so requests survive Cloud Run instance churn; plain
45
48
  # JSON responses keep the traffic proxy-friendly (no SSE-over-POST body).
@@ -0,0 +1,35 @@
1
+ """MCP server settings loaded from environment variables."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from functools import lru_cache
6
+
7
+ from pydantic import Field
8
+ from pydantic_settings import BaseSettings, SettingsConfigDict
9
+
10
+ # ADR-045: ONE base URL. The GLB path-routes /p/{project_id}/* by the
11
+ # project_id prefix, so the client carries no region knowledge and keeps no
12
+ # URL map — routing topology never crosses the package boundary. The only
13
+ # reason to override this value is local development against a running
14
+ # regional-plane service (e.g. http://localhost:8080).
15
+ DEFAULT_API_URL = "https://api.diffmem.com"
16
+
17
+
18
+ class Settings(BaseSettings):
19
+ model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", extra="ignore")
20
+
21
+ # DiffMem API base URL (ADR-045). Routing to the project's home region
22
+ # happens at the GLB edge via the /p/proj_{region}_* path prefix.
23
+ api_url: str = Field(default=DEFAULT_API_URL, validation_alias="DIFFMEM_API_URL")
24
+
25
+ # Rate limiting: requests per minute per API key
26
+ mcp_rate_limit_rpm: int = 60
27
+
28
+ def get_api_url(self) -> str:
29
+ """Base URL for every DiffMem API call (no trailing slash)."""
30
+ return self.api_url.rstrip("/")
31
+
32
+
33
+ @lru_cache
34
+ def get_settings() -> Settings:
35
+ return Settings()