diffmem-mcp-server 0.1.0__tar.gz → 0.1.1__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 (35) hide show
  1. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.1}/CHANGELOG.md +11 -0
  2. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.1}/CONTEXT.md +4 -4
  3. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.1}/PKG-INFO +1 -1
  4. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.1}/PRODUCTION_DEPLOYMENT.md +6 -8
  5. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.1}/README.md +14 -17
  6. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.1}/diffmem_mcp/api_client.py +4 -2
  7. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.1}/diffmem_mcp/auth.py +23 -14
  8. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.1}/diffmem_mcp/context.py +1 -1
  9. diffmem_mcp_server-0.1.1/diffmem_mcp/router.py +59 -0
  10. diffmem_mcp_server-0.1.1/diffmem_mcp/settings.py +35 -0
  11. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.1}/diffmem_mcp/tools/files.py +6 -7
  12. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.1}/diffmem_mcp/tools/memory.py +6 -9
  13. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.1}/diffmem_mcp/tools/project.py +3 -4
  14. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.1}/diffmem_mcp/tools/spaces.py +3 -4
  15. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.1}/pyproject.toml +1 -1
  16. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.1}/tests/test_auth.py +10 -10
  17. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.1}/tests/test_memory_tools.py +1 -2
  18. diffmem_mcp_server-0.1.1/tests/test_router.py +103 -0
  19. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.1}/tests/test_space_allowlist.py +2 -2
  20. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.1}/uv.lock +1 -1
  21. diffmem_mcp_server-0.1.0/diffmem_mcp/router.py +0 -108
  22. diffmem_mcp_server-0.1.0/diffmem_mcp/settings.py +0 -63
  23. diffmem_mcp_server-0.1.0/tests/test_router.py +0 -158
  24. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.1}/.gitignore +0 -0
  25. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.1}/Dockerfile +0 -0
  26. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.1}/diffmem_mcp/__init__.py +0 -0
  27. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.1}/diffmem_mcp/asgi.py +0 -0
  28. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.1}/diffmem_mcp/scopes.py +0 -0
  29. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.1}/diffmem_mcp/security.py +0 -0
  30. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.1}/diffmem_mcp/server.py +0 -0
  31. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.1}/diffmem_mcp/tools/__init__.py +0 -0
  32. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.1}/tests/__init__.py +0 -0
  33. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.1}/tests/test_scope_enforcement.py +0 -0
  34. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.1}/tests/test_security.py +0 -0
  35. {diffmem_mcp_server-0.1.0 → diffmem_mcp_server-0.1.1}/tests/test_self_containment.py +0 -0
@@ -3,6 +3,17 @@
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
+ ## [0.1.1] — 2026-11-06
7
+
8
+ ### Changed
9
+ - **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.
10
+ - `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.
11
+ - Removed the deprecated `REGIONAL_PLANE_URLS` alias window (package had no external users yet).
12
+ - Auth validation targets the single base URL; the sorted-first-URL bootstrap is gone.
13
+
14
+ ### Fixed
15
+ - Example project IDs in docs/tests used a character outside the base32 suffix alphabet (`x7k2p9mz` → `x7k2p3mz`).
16
+
6
17
  ## [0.1.0] — 2026-10-30
7
18
 
8
19
  ### Added
@@ -29,8 +29,8 @@ Standalone MCP (Model Context Protocol) server that exposes DiffMem's public mem
29
29
  - `diffmem_mcp/scopes.py` — scope vocabulary mirror + enforce_scope (fail-closed; mirrors regional-plane `app/core/scopes.py`)
30
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`)
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
34
  - `diffmem_mcp/tools/` — MCP tool implementations (spaces, memory, files, project)
35
35
 
36
36
  ## External Dependencies
@@ -46,7 +46,7 @@ Standalone MCP (Model Context Protocol) server that exposes DiffMem's public mem
46
46
  - All tool invocations are audit-logged with structured events
47
47
  - 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
48
  - 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`).
49
+ - 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
50
 
51
51
  ## Attention Guidance
52
52
  - When changing tool signatures: also update `diffmem_mcp/security.py` validation
@@ -57,6 +57,6 @@ Standalone MCP (Model Context Protocol) server that exposes DiffMem's public mem
57
57
  - Package was renamed from `app` to `diffmem_mcp` to avoid namespace conflicts with regional-plane
58
58
 
59
59
  ## 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`.
60
+ - **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. 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
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.
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.1
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 |
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
@@ -5,10 +5,10 @@ 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 DiffMem API instance can validate any
9
+ key — it self-validates on every public route), so the validator targets the
10
+ single DIFFMEM_API_URL base (ADR-045); edge routing by the project_id path
11
+ prefix handles region selection on every subsequent call.
12
12
 
13
13
  For stdio transport, the API key is provided via the DIFFMEM_API_KEY
14
14
  environment variable (set by the MCP client, e.g. Claude Desktop or Cursor).
@@ -19,10 +19,12 @@ from __future__ import annotations
19
19
  import logging
20
20
  import os
21
21
  from dataclasses import dataclass
22
- from typing import Mapping, Optional
22
+ from typing import Optional
23
23
 
24
24
  import httpx
25
25
 
26
+ from diffmem_mcp.router import UnparseableProjectError, validate_project_id
27
+
26
28
  logger = logging.getLogger(__name__)
27
29
 
28
30
  _VALIDATE_PATH = "/v1/auth/validate"
@@ -36,7 +38,7 @@ class AuthContext:
36
38
  key_id: str
37
39
  project_id: str
38
40
  label: str
39
- raw_key: str # Retained for forwarding to regional-plane as Bearer token
41
+ raw_key: str # Retained for forwarding to the DiffMem API as Bearer token
40
42
  # Null = legacy key / full access (spec #77 §4). A non-null list is the
41
43
  # key's exact powers — strictly additive, no implied scopes.
42
44
  scopes: Optional[list[str]] = None
@@ -59,26 +61,24 @@ 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,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
@@ -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()
@@ -12,7 +12,6 @@ from diffmem_mcp.api_client import RegionalPlaneClient
12
12
  from diffmem_mcp.scopes import SCOPE_FILES_READ, enforce_tool_access
13
13
  from diffmem_mcp.security import AuditLogger, SecurityError
14
14
  from diffmem_mcp.server import get_context
15
- from diffmem_mcp.router import resolve_url
16
15
  from diffmem_mcp.settings import get_settings
17
16
 
18
17
  logger = logging.getLogger(__name__)
@@ -42,9 +41,9 @@ def register_file_tools(mcp_server: FastMCP) -> None:
42
41
  enforce_tool_access(auth, SCOPE_FILES_READ, [space_id])
43
42
 
44
43
  # Call regional-plane for file listing
45
- # ADR-030: the region comes from the project_id prefix — the same
46
- # key the GLB routed this request on. No default-region fallback.
47
- base_url = resolve_url(auth.project_id, get_settings().get_api_urls())
44
+ # ADR-045: one base URL; the GLB edge-routes /p/{project_id}/* by
45
+ # the project_id prefix, so the client does no region routing.
46
+ base_url = get_settings().get_api_url()
48
47
  client = RegionalPlaneClient(base_url, auth.raw_key)
49
48
 
50
49
  # Stale MCP→RP path fixed per spec §7.5: .../files → .../memory/files
@@ -104,9 +103,9 @@ def register_file_tools(mcp_server: FastMCP) -> None:
104
103
  enforce_tool_access(auth, SCOPE_FILES_READ, [space_id])
105
104
 
106
105
  # Call regional-plane for file read
107
- # ADR-030: the region comes from the project_id prefix — the same
108
- # key the GLB routed this request on. No default-region fallback.
109
- base_url = resolve_url(auth.project_id, get_settings().get_api_urls())
106
+ # ADR-045: one base URL; the GLB edge-routes /p/{project_id}/* by
107
+ # the project_id prefix, so the client does no region routing.
108
+ base_url = get_settings().get_api_url()
110
109
  client = RegionalPlaneClient(base_url, auth.raw_key)
111
110
 
112
111
  result = await client.get(
@@ -14,7 +14,6 @@ from diffmem_mcp.api_client import (
14
14
  RegionalPlaneClient,
15
15
  map_upstream_http_error,
16
16
  )
17
- from diffmem_mcp.router import resolve_url
18
17
  from diffmem_mcp.scopes import SCOPE_MEMORY_READ, SCOPE_MEMORY_WRITE, enforce_tool_access
19
18
  from diffmem_mcp.security import AuditLogger, SecurityError
20
19
  from diffmem_mcp.server import get_context
@@ -54,10 +53,9 @@ def register_memory_tools(mcp_server: FastMCP) -> None:
54
53
  # through to tool output (ADR-038).
55
54
  enforce_tool_access(auth, SCOPE_MEMORY_WRITE, [space_id] if space_id else None)
56
55
 
57
- # Get regional-plane client. ADR-030: the region comes from the
58
- # project_id prefix — the same key the GLB routed this request on.
59
- # No default-region fallback exists anywhere; failures are loud.
60
- base_url = resolve_url(auth.project_id, get_settings().get_api_urls())
56
+ # ADR-045: one base URL; the GLB edge-routes /p/{project_id}/* by
57
+ # the project_id prefix, so the client does no region routing.
58
+ base_url = get_settings().get_api_url()
61
59
  client = RegionalPlaneClient(base_url, auth.raw_key)
62
60
 
63
61
  # Generate session ID
@@ -173,10 +171,9 @@ def register_memory_tools(mcp_server: FastMCP) -> None:
173
171
  # at the regional plane (spec #80 site 2).
174
172
  enforce_tool_access(auth, SCOPE_MEMORY_READ, target_spaces or None)
175
173
 
176
- # Get regional-plane client. ADR-030: the region comes from the
177
- # project_id prefix — the same key the GLB routed this request on.
178
- # No default-region fallback exists anywhere; failures are loud.
179
- base_url = resolve_url(auth.project_id, get_settings().get_api_urls())
174
+ # ADR-045: one base URL; the GLB edge-routes /p/{project_id}/* by
175
+ # the project_id prefix, so the client does no region routing.
176
+ base_url = get_settings().get_api_url()
180
177
  client = RegionalPlaneClient(base_url, auth.raw_key)
181
178
 
182
179
  # Build request body
@@ -10,7 +10,6 @@ import httpx
10
10
  from mcp.server.fastmcp import FastMCP
11
11
 
12
12
  from diffmem_mcp.api_client import RegionalPlaneClient, map_upstream_http_error
13
- from diffmem_mcp.router import resolve_url
14
13
  from diffmem_mcp.scopes import SCOPE_INTROSPECT_READ, enforce_tool_access
15
14
  from diffmem_mcp.security import AuditLogger, SecurityError
16
15
  from diffmem_mcp.server import get_context
@@ -39,9 +38,9 @@ def register_project_tools(mcp_server: FastMCP) -> None:
39
38
  enforce_tool_access(auth, SCOPE_INTROSPECT_READ)
40
39
 
41
40
  # Read project status via the DiffMem API (no local Firestore —
42
- # customer machines have no GCP credentials). ADR-030: region
43
- # comes from the project_id prefix; failures are loud.
44
- base_url = resolve_url(project_id, get_settings().get_api_urls())
41
+ # customer machines have no GCP credentials). ADR-045: one base
42
+ # URL; the GLB edge-routes by the project_id path prefix.
43
+ base_url = get_settings().get_api_url()
45
44
  client = RegionalPlaneClient(base_url, auth.raw_key)
46
45
  status = await client.get(f"/p/{project_id}/v1/project/status")
47
46
 
@@ -10,7 +10,6 @@ import httpx
10
10
  from mcp.server.fastmcp import FastMCP
11
11
 
12
12
  from diffmem_mcp.api_client import RegionalPlaneClient, map_upstream_http_error
13
- from diffmem_mcp.router import resolve_url
14
13
  from diffmem_mcp.scopes import SCOPE_INTROSPECT_READ, enforce_tool_access
15
14
  from diffmem_mcp.security import (
16
15
  AuditLogger,
@@ -28,10 +27,10 @@ def register_space_tools(mcp_server: FastMCP) -> None:
28
27
 
29
28
  async def _fetch_spaces(auth) -> list[dict]:
30
29
  """Fetch the project's space list via the DiffMem API (no local
31
- Firestore — customer machines have no GCP credentials). ADR-030:
32
- region comes from the project_id prefix; failures are loud."""
30
+ Firestore — customer machines have no GCP credentials). ADR-045: one
31
+ base URL; the GLB edge-routes by the project_id path prefix."""
33
32
  project_id = auth.project_id
34
- base_url = resolve_url(project_id, get_settings().get_api_urls())
33
+ base_url = get_settings().get_api_url()
35
34
  client = RegionalPlaneClient(base_url, auth.raw_key)
36
35
  body = await client.get(f"/p/{project_id}/v1/spaces")
37
36
  return body.get("spaces", [])
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "diffmem-mcp-server"
7
- version = "0.1.0"
7
+ version = "0.1.1"
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 = [
@@ -8,7 +8,7 @@ Protected rules:
8
8
  - a 5xx or network failure is a TRANSIENT auth_unavailable — so a plane
9
9
  outage never looks like a revoked key
10
10
  - a success body missing key identity is invalid_api_key (fail closed)
11
- - empty key / empty api_urls fail loud with distinct codes
11
+ - empty key / empty base URL fail loud with distinct codes
12
12
  """
13
13
 
14
14
  from __future__ import annotations
@@ -18,10 +18,10 @@ import pytest
18
18
 
19
19
  from diffmem_mcp.auth import ApiKeyValidator, AuthError
20
20
 
21
- API_URLS = {"eu": "https://rp-eu.test", "us": "https://rp-us.test"}
21
+ API_URL = "https://rp-eu.test"
22
22
  VALIDATE_BODY = {
23
23
  "key_id": "kid_1",
24
- "project_id": "proj_eu_x7k2p9mz",
24
+ "project_id": "proj_eu_x7k2p3mz",
25
25
  "label": "test",
26
26
  "scopes": ["memory:write"],
27
27
  "space_allowlist": ["spc_a"],
@@ -32,14 +32,14 @@ def _validator(status: int = 200, payload: dict | None = VALIDATE_BODY) -> ApiKe
32
32
  def handler(request: httpx.Request) -> httpx.Response:
33
33
  return httpx.Response(status, json=payload)
34
34
 
35
- return ApiKeyValidator(API_URLS, transport=httpx.MockTransport(handler))
35
+ return ApiKeyValidator(API_URL, transport=httpx.MockTransport(handler))
36
36
 
37
37
 
38
38
  @pytest.mark.asyncio
39
39
  async def test_validate_success_builds_auth_context():
40
40
  ctx = await _validator().validate("dk_good")
41
41
  assert ctx.key_id == "kid_1"
42
- assert ctx.project_id == "proj_eu_x7k2p9mz"
42
+ assert ctx.project_id == "proj_eu_x7k2p3mz"
43
43
  assert ctx.scopes == ["memory:write"]
44
44
  assert ctx.space_allowlist == ["spc_a"]
45
45
  assert ctx.raw_key == "dk_good"
@@ -64,7 +64,7 @@ async def test_validate_network_error_is_transient_unavailable():
64
64
  def handler(request: httpx.Request) -> httpx.Response:
65
65
  raise httpx.ConnectError("connection refused", request=request)
66
66
 
67
- validator = ApiKeyValidator(API_URLS, transport=httpx.MockTransport(handler))
67
+ validator = ApiKeyValidator(API_URL, transport=httpx.MockTransport(handler))
68
68
  with pytest.raises(AuthError) as exc:
69
69
  await validator.validate("dk_good")
70
70
  assert exc.value.code == "auth_unavailable"
@@ -84,13 +84,13 @@ async def test_validate_empty_key_fails_loud():
84
84
  assert exc.value.code == "missing_api_key"
85
85
 
86
86
 
87
- def test_validator_empty_api_urls_fails_loud():
87
+ def test_validator_empty_api_url_fails_loud():
88
88
  with pytest.raises(AuthError) as exc:
89
- ApiKeyValidator({})
89
+ ApiKeyValidator("")
90
90
  assert exc.value.code == "config_error"
91
91
 
92
92
 
93
- def test_validator_base_url_is_deterministic():
94
- """Sorted-first URL — validation is region-agnostic, never random."""
93
+ def test_validator_base_url_is_verbatim():
94
+ """The single DIFFMEM_API_URL base is used as-is (no map, no selection)."""
95
95
  v = _validator()
96
96
  assert v._base_url == "https://rp-eu.test"
@@ -78,8 +78,7 @@ def tools(monkeypatch):
78
78
 
79
79
  stub = _StubClient()
80
80
  monkeypatch.setattr(memory_module, "get_context", lambda: _FakeCtx())
81
- monkeypatch.setattr(memory_module, "get_settings", lambda: SimpleNamespace(get_api_urls=dict))
82
- monkeypatch.setattr(memory_module, "resolve_url", lambda project_id, urls: RP_BASE_URL)
81
+ monkeypatch.setattr(memory_module, "get_settings", lambda: SimpleNamespace(get_api_url=lambda: RP_BASE_URL))
83
82
  monkeypatch.setattr(memory_module, "RegionalPlaneClient", lambda base_url, key: stub)
84
83
 
85
84
  def _sync(fn):
@@ -0,0 +1,103 @@
1
+ """Tests for project_id format validation (ADR-030 prefix contract, ADR-045
2
+ client-side routing removal).
3
+
4
+ Business rule under test: the project_id prefix IS the routing contract — the
5
+ GLB path-routes /p/{project_id}/* by the same segment, so client-side routing
6
+ logic must NOT exist (a reintroduced region→URL map would drift from the
7
+ edge). Format validation remains: a malformed ID is a loud failure, never a
8
+ quiet misroute or an opaque upstream 404. If someone reintroduces a
9
+ DEFAULT_REGION fallback, a URL map, or a Firestore lookup, these tests fail.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import re
15
+ from pathlib import Path
16
+
17
+ import pytest
18
+
19
+ from diffmem_mcp.router import PROJECT_ID_PATTERN, UnparseableProjectError, validate_project_id
20
+
21
+ PLATFORM_ROOT = Path(__file__).resolve().parents[3]
22
+ GLB_URL_MAP = PLATFORM_ROOT / "infra" / "terraform" / "modules" / "global-load-balancer" / "url-map.tf"
23
+
24
+ VALID_IDS = [
25
+ "proj_eu_x7k2p3mz",
26
+ "proj_us_abcdefgh",
27
+ "proj_sg_x2k3p4mz",
28
+ ]
29
+
30
+ INVALID_IDS = [
31
+ "", # empty
32
+ "proj_EU_x7k2p9mz", # uppercase region
33
+ "proj_eu_x7k2p9m", # 7-char suffix
34
+ "proj_eu_x7k2p9mzz", # 9-char suffix
35
+ "proj_eu_x7k2019z", # 0/1 not in base32 alphabet
36
+ "prj_eu_x7k2p9mz", # wrong prefix
37
+ "proj_eu_x7k2p9mz_extra", # trailing garbage
38
+ ]
39
+
40
+
41
+ # ---------------------------------------------------------------------------
42
+ # Format contract
43
+ # ---------------------------------------------------------------------------
44
+
45
+ @pytest.mark.parametrize("project_id", VALID_IDS)
46
+ def test_valid_ids_pass_through_unchanged(project_id):
47
+ assert validate_project_id(project_id) == project_id
48
+
49
+
50
+ @pytest.mark.parametrize("project_id", INVALID_IDS)
51
+ def test_malformed_ids_fail_loud(project_id, caplog):
52
+ with pytest.raises(UnparseableProjectError):
53
+ validate_project_id(project_id)
54
+ assert "ROUTER_UNPARSEABLE_PROJECT" in caplog.text
55
+
56
+
57
+ def test_no_routing_semantics_in_module():
58
+ """ADR-045 guard on CODE, not comments: the router module must not route.
59
+ No URL maps, no resolution, no Firestore machinery, no async resolve."""
60
+ source = (Path(__file__).resolve().parents[1] / "diffmem_mcp" / "router.py").read_text()
61
+ code = "\n".join(
62
+ line for line in source.splitlines()
63
+ if not line.lstrip().startswith("#") and '"""' not in line
64
+ )
65
+ assert "api_urls" not in code
66
+ assert "DIFFMEM_API_URL" not in code
67
+ assert "TENANT_CONFIGS_COLLECTION" not in code
68
+ assert "default_region" not in code
69
+ assert "async def" not in code # validation is synchronous
70
+ assert "resolve_url" not in code
71
+
72
+
73
+ # ---------------------------------------------------------------------------
74
+ # Drift alarms: the prefix contract is shared with the GLB and control-plane
75
+ # ---------------------------------------------------------------------------
76
+
77
+ def test_control_plane_pattern_is_identical():
78
+ """The regex is the shared contract — drift here misroutes real traffic."""
79
+ cp = PLATFORM_ROOT / "services" / "control-plane" / "app" / "utils" / "project_id.py"
80
+ assert cp.exists(), f"control-plane project_id.py missing at {cp} — layout drift"
81
+ source = cp.read_text()
82
+ cp_match = re.search(r"PROJECT_ID_PATTERN\s*=\s*re\.compile\(\s*r\"([^\"]+)\"", source)
83
+ assert cp_match, "control-plane PROJECT_ID_PATTERN not found — layout drift"
84
+ assert cp_match.group(1) == PROJECT_ID_PATTERN.pattern, (
85
+ "MCP and control-plane project_id patterns drifted — routing would disagree"
86
+ )
87
+
88
+
89
+ def test_glb_region_codes_parse():
90
+ """Every region the GLB can route must be parseable by the format."""
91
+ source = GLB_URL_MAP.read_text()
92
+ glb_codes = set(re.findall(r"/p/proj_([a-z]{2})_\*", source))
93
+ assert glb_codes, "no GLB region paths found — url-map.tf layout drift"
94
+ for code in glb_codes:
95
+ assert PROJECT_ID_PATTERN.match(f"proj_{code}_x7k2p3mz"), (
96
+ f"GLB region code '{code}' not parseable by the project_id contract"
97
+ )
98
+
99
+
100
+ def test_glb_region_codes_are_two_lowercase_letters():
101
+ source = GLB_URL_MAP.read_text()
102
+ for code in set(re.findall(r"/p/proj_([a-z]{2})_\*", source)):
103
+ assert len(code) == 2 and code.isalpha() and code.islower()
@@ -34,7 +34,7 @@ KEY_DOC = {
34
34
  # DiffMem API validate-endpoint mock (httpx.MockTransport seam)
35
35
  # ---------------------------------------------------------------------------
36
36
 
37
- API_URLS = {"us": "https://rp-us.test"}
37
+ API_URL = "https://rp-us.test"
38
38
 
39
39
 
40
40
  def _validator_for_response(payload: dict | None, status: int = 200) -> ApiKeyValidator:
@@ -43,7 +43,7 @@ def _validator_for_response(payload: dict | None, status: int = 200) -> ApiKeyVa
43
43
  assert request.headers["Authorization"] == "Bearer dk_test"
44
44
  return httpx.Response(status, json=payload)
45
45
 
46
- return ApiKeyValidator(API_URLS, transport=httpx.MockTransport(handler))
46
+ return ApiKeyValidator(API_URL, transport=httpx.MockTransport(handler))
47
47
 
48
48
 
49
49
  # ---------------------------------------------------------------------------
@@ -201,7 +201,7 @@ wheels = [
201
201
 
202
202
  [[package]]
203
203
  name = "diffmem-mcp-server"
204
- version = "0.1.0"
204
+ version = "0.1.1"
205
205
  source = { editable = "." }
206
206
  dependencies = [
207
207
  { name = "httpx" },
@@ -1,108 +0,0 @@
1
- # CAPABILITY: region derivation from the project_id prefix (ADR-030 §4–5)
2
- # INPUTS: project_id (proj_{region}_{8-char base32}), DIFFMEM_API_URLS env map
3
- # OUTPUTS: API base URL for the project's home region
4
- # CONSTRAINTS: PURE and SYNCHRONOUS — no Firestore, no async, no cache. The
5
- # prefix IS the routing contract: the GLB routes /p/{project_id}/* by the same
6
- # segment, so MCP routing agrees with edge routing by construction. Silent
7
- # fallback to a default region is FORBIDDEN — a malformed ID or an undeployed
8
- # region is a loud error, never a quiet misroute.
9
-
10
- """Regional routing for the DiffMem MCP server.
11
-
12
- Pre-ADR-030 this module read ``tenant_configs`` from Firestore and fell back
13
- to ``DEFAULT_REGION`` — dead code whose silent fallback was exactly the
14
- compliance failure mode ADR-030 eliminates. Since ADR-030 the region lives in
15
- the project_id itself (the same key the GLB edge routes on), so resolution is
16
- pure string parsing.
17
-
18
- Keep in sync (drift alarm tests assert this):
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
- from typing import Mapping
28
-
29
- logger = logging.getLogger(__name__)
30
-
31
- __all__ = ["PROJECT_ID_PATTERN", "RegionResolutionError", "resolve_url", "RegionalRouter"]
32
-
33
- # Same contract as control-plane/app/utils/project_id.py — a drift test asserts
34
- # the two regexes stay identical.
35
- PROJECT_ID_PATTERN = re.compile(r"^proj_([a-z]{2})_[a-z2-7]{8}$")
36
-
37
-
38
- class RegionResolutionError(Exception):
39
- """A project's region cannot be resolved — routing must fail loud.
40
-
41
- Attributes:
42
- code: ``unparseable_project`` (ID violates the proj_{region}_{suffix}
43
- contract) or ``region_not_deployed`` (well-formed ID whose region
44
- has no entry in DIFFMEM_API_URLS — GLB/env drift alarm).
45
- """
46
-
47
- def __init__(self, code: str, message: str) -> None:
48
- super().__init__(message)
49
- self.code = code
50
-
51
-
52
- def resolve_url(project_id: str, api_urls: Mapping[str, str]) -> str:
53
- """Resolve a project_id to its API base URL.
54
-
55
- Args:
56
- project_id: ``proj_{region}_{8-char base32}`` (the GLB's routing key)
57
- api_urls: DIFFMEM_API_URLS map (region code → base URL)
58
-
59
- Returns:
60
- The API base URL for this project's home region.
61
-
62
- Raises:
63
- RegionResolutionError: code ``unparseable_project`` or
64
- ``region_not_deployed`` — never falls back silently.
65
- """
66
- match = PROJECT_ID_PATTERN.match(project_id)
67
- if not match:
68
- logger.error("ROUTER_UNPARSEABLE_PROJECT: project_id=%s", project_id)
69
- raise RegionResolutionError(
70
- "unparseable_project",
71
- f"project_id '{project_id}' does not match proj_{{region}}_{{8-char base32}} "
72
- "(e.g. proj_eu_x7k2p9mz); refusing to route it anywhere by default.",
73
- )
74
-
75
- region = match.group(1)
76
- url = api_urls.get(region)
77
- if url is None:
78
- logger.error(
79
- "ROUTER_REGION_NOT_DEPLOYED: project_id=%s region=%s — no URL in "
80
- "DIFFMEM_API_URLS (GLB/env drift?)",
81
- project_id,
82
- region,
83
- )
84
- raise RegionResolutionError(
85
- "region_not_deployed",
86
- f"Region '{region}' (from project_id '{project_id}') has no API URL "
87
- "configured — check the DIFFMEM_API_URLS setting.",
88
- )
89
-
90
- logger.debug("ROUTER_RESOLVED: project_id=%s region=%s", project_id, region)
91
- return url
92
-
93
-
94
- class RegionalRouter:
95
- """Thin seam over :func:`resolve_url`.
96
-
97
- Kept as a named seam (tests, reviewers, and the drift-alarm tests anchor
98
- here) — but it is now a pure function object: no Firestore client, no
99
- async, no cache. ``api_urls`` is the already-parsed DIFFMEM_API_URLS
100
- map.
101
- """
102
-
103
- def __init__(self, api_urls: Mapping[str, str]) -> None:
104
- self._api_urls = dict(api_urls)
105
-
106
- def resolve(self, project_id: str) -> str:
107
- """Resolve a project_id to the API base URL (see resolve_url)."""
108
- return resolve_url(project_id, self._api_urls)
@@ -1,63 +0,0 @@
1
- """MCP server settings loaded from environment variables."""
2
-
3
- from __future__ import annotations
4
-
5
- import json
6
- from functools import lru_cache
7
- from typing import Dict
8
-
9
- from pydantic import AliasChoices, Field, field_validator, model_validator
10
- from pydantic_settings import BaseSettings, SettingsConfigDict
11
-
12
-
13
- class Settings(BaseSettings):
14
- model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", extra="ignore")
15
-
16
- # API endpoint routing: JSON mapping of region_key → base URL.
17
- # Example: '{"us": "https://api.diffmem.com", "eu": "https://api.diffmem.com"}'
18
- # ADR-030: region is derived from the project_id prefix (see router.py);
19
- # there is NO default region and NO cache — resolution is pure parsing.
20
- # Public-facing name (ADR-037 vocabulary): the plane noun is internal.
21
- # Deprecated alias REGIONAL_PLANE_URLS kept one transition window.
22
- api_urls: str = Field(
23
- default='{"us": "http://localhost:8080"}',
24
- validation_alias=AliasChoices("DIFFMEM_API_URLS", "REGIONAL_PLANE_URLS"),
25
- )
26
-
27
- # Rate limiting: requests per minute per API key
28
- mcp_rate_limit_rpm: int = 60
29
-
30
- @field_validator("api_urls")
31
- @classmethod
32
- def parse_api_urls(cls, v: str) -> str:
33
- """Validate JSON format."""
34
- try:
35
- parsed = json.loads(v)
36
- if not isinstance(parsed, dict):
37
- raise ValueError("Must be a JSON object")
38
- except json.JSONDecodeError as e:
39
- raise ValueError(f"Invalid JSON: {e}") from e
40
- return v
41
-
42
- @model_validator(mode="after")
43
- def _warn_deprecated_env(self) -> "Settings":
44
- """Warn when configured via the deprecated REGIONAL_PLANE_URLS name."""
45
- import os
46
- import warnings
47
-
48
- if os.environ.get("REGIONAL_PLANE_URLS") and not os.environ.get("DIFFMEM_API_URLS"):
49
- warnings.warn(
50
- "REGIONAL_PLANE_URLS is deprecated; use DIFFMEM_API_URLS (same JSON shape).",
51
- DeprecationWarning,
52
- stacklevel=2,
53
- )
54
- return self
55
-
56
- def get_api_urls(self) -> Dict[str, str]:
57
- """Parse api_urls JSON into a dict."""
58
- return json.loads(self.api_urls)
59
-
60
-
61
- @lru_cache
62
- def get_settings() -> Settings:
63
- return Settings()
@@ -1,158 +0,0 @@
1
- """Tests for the regional routing module (ADR-030 — pure prefix resolution).
2
-
3
- Business rule under test: MCP routing MUST agree with GLB edge routing by
4
- construction — the region comes from the project_id prefix, the same key the
5
- GLB routes on. There is NO silent default: a malformed ID or an undeployed
6
- region is a loud failure. If these tests can fail, the routing contract is
7
- being protected; if someone reintroduces a DEFAULT_REGION fallback or a
8
- Firestore lookup, these tests fail.
9
- """
10
-
11
- from __future__ import annotations
12
-
13
- import re
14
- from pathlib import Path
15
-
16
- import pytest
17
-
18
- from diffmem_mcp.router import (
19
- PROJECT_ID_PATTERN,
20
- RegionResolutionError,
21
- RegionalRouter,
22
- resolve_url,
23
- )
24
-
25
- PLATFORM_ROOT = Path(__file__).resolve().parents[3]
26
- GLB_URL_MAP = PLATFORM_ROOT / "infra" / "terraform" / "modules" / "global-load-balancer" / "url-map.tf"
27
- CP_PROJECT_ID = PLATFORM_ROOT / "services" / "control-plane" / "app" / "utils" / "project_id.py"
28
-
29
- URLS = {
30
- "eu": "https://eu-api.diffmem.com",
31
- "us": "https://us-api.diffmem.com",
32
- "sg": "https://sg-api.diffmem.com",
33
- }
34
-
35
-
36
- # ---------------------------------------------------------------------------
37
- # Pure resolution
38
- # ---------------------------------------------------------------------------
39
-
40
- @pytest.mark.parametrize(
41
- ("project_id", "expected"),
42
- [
43
- ("proj_eu_x7k2p3mz", "https://eu-api.diffmem.com"),
44
- ("proj_us_x7k2p3mz", "https://us-api.diffmem.com"),
45
- ("proj_sg_x7k2p3mz", "https://sg-api.diffmem.com"),
46
- ],
47
- )
48
- def test_resolve_url_routes_by_prefix(project_id, expected):
49
- assert resolve_url(project_id, URLS) == expected
50
-
51
-
52
- def test_router_seem_delegates():
53
- router = RegionalRouter(URLS)
54
- assert router.resolve("proj_us_x7k2p3mz") == "https://us-api.diffmem.com"
55
-
56
-
57
- def test_parse_pattern_accepts_full_base32_suffix():
58
- # base32 lowercase alphabet: a-z + 2-7 — full 8-char alphabet sweep.
59
- for ch in "abcdefghijklmnopqrstuvwxyz234567":
60
- assert PROJECT_ID_PATTERN.match(f"proj_eu_{ch * 8}"), ch
61
-
62
-
63
- # ---------------------------------------------------------------------------
64
- # Loud failures — no silent defaults
65
- # ---------------------------------------------------------------------------
66
-
67
- @pytest.mark.parametrize(
68
- "bad_id",
69
- [
70
- "proj1", # legacy shape (pre-GLB format)
71
- "proj_eu_short", # suffix too short
72
- "proj_eu_AAAAAAAA", # uppercase — outside base32 lowercase alphabet
73
- "proj_toolongregion_x7k2p3mz", # region not exactly 2 lowercase letters
74
- "", # empty
75
- ],
76
- )
77
- def test_unparseable_project_fails_loud(bad_id, caplog):
78
- with pytest.raises(RegionResolutionError) as exc_info:
79
- resolve_url(bad_id, URLS)
80
- assert exc_info.value.code == "unparseable_project"
81
- assert "ROUTER_UNPARSEABLE_PROJECT" in caplog.text
82
-
83
-
84
- def test_region_not_deployed_fails_loud(caplog):
85
- # Well-formed ID for a region with no URL in the env map — GLB/env drift.
86
- with pytest.raises(RegionResolutionError) as exc_info:
87
- resolve_url("proj_jp_x7k2p3mz", URLS)
88
- assert exc_info.value.code == "region_not_deployed"
89
- assert "ROUTER_REGION_NOT_DEPLOYED" in caplog.text
90
-
91
-
92
- def test_no_fallback_semantics_in_module():
93
- """A reintroduced DEFAULT_REGION fallback would be the exact failure mode
94
- ADR-030 eliminates. Guard on CODE, not comments: no Firestore machinery,
95
- no async resolve, no silent .get() fallback chain."""
96
- source = (Path(__file__).resolve().parents[1] / "diffmem_mcp" / "router.py").read_text()
97
- code = "\n".join(
98
- line for line in source.splitlines()
99
- if not line.lstrip().startswith("#") and '"""' not in line
100
- )
101
- assert "TENANT_CONFIGS_COLLECTION" not in code
102
- assert "CacheEntry" not in code
103
- assert "default_region" not in code
104
- assert "async def" not in code # resolution is synchronous by design
105
-
106
-
107
- # ---------------------------------------------------------------------------
108
- # Drift alarms — three repos must agree on the project_id contract
109
- # ---------------------------------------------------------------------------
110
-
111
- def test_pattern_matches_control_plane_contract():
112
- """Behavioral drift alarm: the MCP regex must accept/reject exactly the
113
- IDs the control-plane contract accepts/rejects, and must extract the
114
- region as segment 2 (the segment the GLB routes on)."""
115
- cp_match = re.search(
116
- r'PROJECT_ID_PATTERN = re\.compile\(r"([^"]+)"\)', CP_PROJECT_ID.read_text()
117
- )
118
- assert cp_match, "control-plane PROJECT_ID_PATTERN not found — layout drift"
119
- cp_pattern = re.compile(cp_match.group(1))
120
-
121
- corpus = [
122
- "proj_eu_x7k2p3mz",
123
- "proj_us_aaaaaaaa",
124
- "proj_sg_zzzzzzzz",
125
- "proj_jp_22222222",
126
- "proj1",
127
- "proj_eu_short",
128
- "proj_eu_AAAAAAAA",
129
- "proj_toolongregion_x7k2p3mz",
130
- "",
131
- "PROJ_EU_X7K2P3MZ",
132
- ]
133
- for pid in corpus:
134
- assert bool(PROJECT_ID_PATTERN.match(pid)) == bool(cp_pattern.match(pid)), pid
135
-
136
- valid = "proj_us_x7k2p3mz"
137
- assert PROJECT_ID_PATTERN.match(valid).group(1) == valid.split("_")[1]
138
-
139
-
140
- def test_glb_region_codes_all_parse():
141
- """Every region code the GLB routes must be parseable by this module —
142
- if the GLB grows a code this regex can't handle, MCP routing breaks for
143
- that region the moment it enables."""
144
- source = GLB_URL_MAP.read_text()
145
- glb_codes = set(re.findall(r"/p/proj_([a-z]{2})_\*", source))
146
- assert glb_codes, "no GLB region paths found — url-map.tf layout drift"
147
- for code in glb_codes:
148
- assert PROJECT_ID_PATTERN.match(f"proj_{code}_x7k2p3mz"), (
149
- f"GLB region code '{code}' not parseable by the MCP router"
150
- )
151
- # And it must be routable when the env map carries it.
152
- assert resolve_url(f"proj_{code}_x7k2p3mz", {code: "https://x"}) == "https://x"
153
-
154
-
155
- def test_glb_region_codes_are_two_lowercase_letters():
156
- source = GLB_URL_MAP.read_text()
157
- for code in set(re.findall(r"/p/proj_([a-z]{2})_\*", source)):
158
- assert len(code) == 2 and code.isalpha() and code.islower()