diffmem-mcp-server 0.1.1__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.
- diffmem_mcp_server-0.1.2/CHANGELOG.md +45 -0
- {diffmem_mcp_server-0.1.1 → diffmem_mcp_server-0.1.2}/CONTEXT.md +5 -5
- {diffmem_mcp_server-0.1.1 → diffmem_mcp_server-0.1.2}/PKG-INFO +1 -1
- {diffmem_mcp_server-0.1.1 → diffmem_mcp_server-0.1.2}/README.md +1 -1
- {diffmem_mcp_server-0.1.1 → diffmem_mcp_server-0.1.2}/diffmem_mcp/asgi.py +41 -0
- {diffmem_mcp_server-0.1.1 → diffmem_mcp_server-0.1.2}/diffmem_mcp/auth.py +10 -10
- diffmem_mcp_server-0.1.2/diffmem_mcp/copy.py +64 -0
- {diffmem_mcp_server-0.1.1 → diffmem_mcp_server-0.1.2}/diffmem_mcp/server.py +9 -6
- {diffmem_mcp_server-0.1.1 → diffmem_mcp_server-0.1.2}/diffmem_mcp/tools/files.py +6 -4
- diffmem_mcp_server-0.1.2/diffmem_mcp/tools/memory.py +424 -0
- {diffmem_mcp_server-0.1.1 → diffmem_mcp_server-0.1.2}/diffmem_mcp/tools/project.py +5 -4
- {diffmem_mcp_server-0.1.1 → diffmem_mcp_server-0.1.2}/diffmem_mcp/tools/spaces.py +11 -8
- {diffmem_mcp_server-0.1.1 → diffmem_mcp_server-0.1.2}/pyproject.toml +1 -1
- diffmem_mcp_server-0.1.2/tests/test_capture_copy_contract.py +108 -0
- diffmem_mcp_server-0.1.2/tests/test_fire_and_forget_contract.py +356 -0
- diffmem_mcp_server-0.1.2/tests/test_http_auth_gate.py +94 -0
- {diffmem_mcp_server-0.1.1 → diffmem_mcp_server-0.1.2}/tests/test_memory_tools.py +67 -6
- diffmem_mcp_server-0.1.2/tests/test_spaces_tool_error_surface.py +126 -0
- diffmem_mcp_server-0.1.2/tests/test_tool_error_paths.py +78 -0
- {diffmem_mcp_server-0.1.1 → diffmem_mcp_server-0.1.2}/uv.lock +6 -6
- diffmem_mcp_server-0.1.1/CHANGELOG.md +0 -27
- diffmem_mcp_server-0.1.1/diffmem_mcp/tools/memory.py +0 -245
- {diffmem_mcp_server-0.1.1 → diffmem_mcp_server-0.1.2}/.gitignore +0 -0
- {diffmem_mcp_server-0.1.1 → diffmem_mcp_server-0.1.2}/Dockerfile +0 -0
- {diffmem_mcp_server-0.1.1 → diffmem_mcp_server-0.1.2}/PRODUCTION_DEPLOYMENT.md +0 -0
- {diffmem_mcp_server-0.1.1 → diffmem_mcp_server-0.1.2}/diffmem_mcp/__init__.py +0 -0
- {diffmem_mcp_server-0.1.1 → diffmem_mcp_server-0.1.2}/diffmem_mcp/api_client.py +0 -0
- {diffmem_mcp_server-0.1.1 → diffmem_mcp_server-0.1.2}/diffmem_mcp/context.py +0 -0
- {diffmem_mcp_server-0.1.1 → diffmem_mcp_server-0.1.2}/diffmem_mcp/router.py +0 -0
- {diffmem_mcp_server-0.1.1 → diffmem_mcp_server-0.1.2}/diffmem_mcp/scopes.py +0 -0
- {diffmem_mcp_server-0.1.1 → diffmem_mcp_server-0.1.2}/diffmem_mcp/security.py +0 -0
- {diffmem_mcp_server-0.1.1 → diffmem_mcp_server-0.1.2}/diffmem_mcp/settings.py +0 -0
- {diffmem_mcp_server-0.1.1 → diffmem_mcp_server-0.1.2}/diffmem_mcp/tools/__init__.py +0 -0
- {diffmem_mcp_server-0.1.1 → diffmem_mcp_server-0.1.2}/tests/__init__.py +0 -0
- {diffmem_mcp_server-0.1.1 → diffmem_mcp_server-0.1.2}/tests/test_auth.py +0 -0
- {diffmem_mcp_server-0.1.1 → diffmem_mcp_server-0.1.2}/tests/test_router.py +0 -0
- {diffmem_mcp_server-0.1.1 → diffmem_mcp_server-0.1.2}/tests/test_scope_enforcement.py +0 -0
- {diffmem_mcp_server-0.1.1 → diffmem_mcp_server-0.1.2}/tests/test_security.py +0 -0
- {diffmem_mcp_server-0.1.1 → diffmem_mcp_server-0.1.2}/tests/test_self_containment.py +0 -0
- {diffmem_mcp_server-0.1.1 → diffmem_mcp_server-0.1.2}/tests/test_space_allowlist.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
|
|
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
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
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
|
|
@@ -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; 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
|
-
- **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`.
|
|
@@ -68,7 +68,7 @@ pip install -e .
|
|
|
68
68
|
| Variable | Required | Default | Description |
|
|
69
69
|
|----------|----------|---------|-------------|
|
|
70
70
|
| `DIFFMEM_API_KEY` | Yes | — | DiffMem API key for authentication |
|
|
71
|
-
| `DIFFMEM_API_URL` | No | `https://api.diffmem.com` | DiffMem API base URL — override only for local development |
|
|
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`) |
|
|
72
72
|
| `MCP_RATE_LIMIT_RPM` | No | `60` | Rate limit per API key (requests/min) |
|
|
73
73
|
|
|
74
74
|
ADR-045: one base URL. Routing to your project's home region happens at the
|
|
@@ -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
|
|
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
|
|
9
|
-
key
|
|
10
|
-
|
|
11
|
-
|
|
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).
|
|
@@ -24,6 +26,7 @@ from typing import Optional
|
|
|
24
26
|
import httpx
|
|
25
27
|
|
|
26
28
|
from diffmem_mcp.router import UnparseableProjectError, validate_project_id
|
|
29
|
+
from diffmem_mcp.security import SecurityError
|
|
27
30
|
|
|
28
31
|
logger = logging.getLogger(__name__)
|
|
29
32
|
|
|
@@ -48,13 +51,10 @@ class AuthContext:
|
|
|
48
51
|
space_allowlist: Optional[list[str]] = None
|
|
49
52
|
|
|
50
53
|
|
|
51
|
-
class AuthError(
|
|
54
|
+
class AuthError(SecurityError):
|
|
52
55
|
"""Raised when API key validation fails."""
|
|
53
56
|
|
|
54
|
-
|
|
55
|
-
self.code = code
|
|
56
|
-
self.message = message
|
|
57
|
-
super().__init__(message)
|
|
57
|
+
# WHY: a SecurityError subclass so every tool's denial handler returns the machine code.
|
|
58
58
|
|
|
59
59
|
|
|
60
60
|
class ApiKeyValidator:
|
|
@@ -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."""
|
|
@@ -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
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
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).
|
|
@@ -30,6 +30,7 @@ def register_file_tools(mcp_server: FastMCP) -> None:
|
|
|
30
30
|
Returns a list of file paths with sizes and last-committed timestamps.
|
|
31
31
|
"""
|
|
32
32
|
ctx = get_context()
|
|
33
|
+
auth = None
|
|
33
34
|
t0 = time.monotonic()
|
|
34
35
|
try:
|
|
35
36
|
auth = await ctx.get_auth()
|
|
@@ -70,8 +71,8 @@ def register_file_tools(mcp_server: FastMCP) -> None:
|
|
|
70
71
|
except SecurityError as e:
|
|
71
72
|
AuditLogger.log_invocation(
|
|
72
73
|
tool_name="list_files",
|
|
73
|
-
key_id=getattr(
|
|
74
|
-
project_id=getattr(
|
|
74
|
+
key_id=getattr(auth, "key_id", "unknown"),
|
|
75
|
+
project_id=getattr(auth, "project_id", "unknown"),
|
|
75
76
|
space_id=space_id,
|
|
76
77
|
success=False,
|
|
77
78
|
error_code=e.code,
|
|
@@ -92,6 +93,7 @@ def register_file_tools(mcp_server: FastMCP) -> None:
|
|
|
92
93
|
Returns the file content as text.
|
|
93
94
|
"""
|
|
94
95
|
ctx = get_context()
|
|
96
|
+
auth = None
|
|
95
97
|
t0 = time.monotonic()
|
|
96
98
|
try:
|
|
97
99
|
auth = await ctx.get_auth()
|
|
@@ -134,8 +136,8 @@ def register_file_tools(mcp_server: FastMCP) -> None:
|
|
|
134
136
|
except SecurityError as e:
|
|
135
137
|
AuditLogger.log_invocation(
|
|
136
138
|
tool_name="read_file",
|
|
137
|
-
key_id=getattr(
|
|
138
|
-
project_id=getattr(
|
|
139
|
+
key_id=getattr(auth, "key_id", "unknown"),
|
|
140
|
+
project_id=getattr(auth, "project_id", "unknown"),
|
|
139
141
|
space_id=space_id,
|
|
140
142
|
success=False,
|
|
141
143
|
error_code=e.code,
|