diffmem-mcp-server 0.1.0__py3-none-any.whl
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/__init__.py +1 -0
- diffmem_mcp/api_client.py +137 -0
- diffmem_mcp/asgi.py +171 -0
- diffmem_mcp/auth.py +158 -0
- diffmem_mcp/context.py +124 -0
- diffmem_mcp/router.py +108 -0
- diffmem_mcp/scopes.py +89 -0
- diffmem_mcp/security.py +243 -0
- diffmem_mcp/server.py +151 -0
- diffmem_mcp/settings.py +63 -0
- diffmem_mcp/tools/__init__.py +22 -0
- diffmem_mcp/tools/files.py +147 -0
- diffmem_mcp/tools/memory.py +248 -0
- diffmem_mcp/tools/project.py +80 -0
- diffmem_mcp/tools/spaces.py +187 -0
- diffmem_mcp_server-0.1.0.dist-info/METADATA +15 -0
- diffmem_mcp_server-0.1.0.dist-info/RECORD +19 -0
- diffmem_mcp_server-0.1.0.dist-info/WHEEL +4 -0
- diffmem_mcp_server-0.1.0.dist-info/entry_points.txt +2 -0
diffmem_mcp/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""DiffMem MCP Server — exposes DiffMem memory APIs as MCP tools."""
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""HTTP client for calling regional-plane APIs.
|
|
2
|
+
|
|
3
|
+
Handles Bearer token forwarding, error mapping, and regional routing.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import logging
|
|
9
|
+
from typing import Any, Dict, Optional
|
|
10
|
+
|
|
11
|
+
import httpx
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
_DEFAULT_TIMEOUT = 30.0
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
# ---------------------------------------------------------------------------
|
|
19
|
+
# Upstream error mapping (issue #128 / ADR-038)
|
|
20
|
+
# ---------------------------------------------------------------------------
|
|
21
|
+
|
|
22
|
+
# The regional plane's tenant-facing error body shape:
|
|
23
|
+
# {"error": <machine code>, "detail": <clean detail>}
|
|
24
|
+
GENERIC_ERROR_MESSAGE = "An unexpected error occurred. The incident has been logged."
|
|
25
|
+
UPSTREAM_UNPARSEABLE_CODE = "upstream_error"
|
|
26
|
+
UPSTREAM_UNPARSEABLE_MESSAGE = (
|
|
27
|
+
"The memory service returned an error response that could not be interpreted."
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def map_upstream_http_error(exc: httpx.HTTPStatusError) -> Dict[str, Any]:
|
|
32
|
+
"""Map one regional-plane HTTP failure to the MCP tool error envelope.
|
|
33
|
+
|
|
34
|
+
Passthrough ONLY when the body carries a machine code (``"error"`` key):
|
|
35
|
+
the exact upstream code and its clean ``detail`` are re-emitted verbatim —
|
|
36
|
+
no rewording, no added vocabulary. Any other body (non-JSON, unexpected
|
|
37
|
+
shape) maps to a generic code. Neither the response body nor the exception
|
|
38
|
+
text ever reaches tool output; both are logged here, server-side, as the
|
|
39
|
+
operator signal instead (ADR-038: never echo ``str(e)`` of HTTP errors).
|
|
40
|
+
"""
|
|
41
|
+
try:
|
|
42
|
+
body = exc.response.json()
|
|
43
|
+
except Exception: # noqa: BLE001 — any body the JSON parser rejects is unmappable
|
|
44
|
+
body = None
|
|
45
|
+
|
|
46
|
+
code = body.get("error") if isinstance(body, dict) else None
|
|
47
|
+
detail = body.get("detail") if isinstance(body, dict) else None
|
|
48
|
+
|
|
49
|
+
if isinstance(code, str) and code:
|
|
50
|
+
logger.warning(
|
|
51
|
+
"MCP_UPSTREAM_HTTP_ERROR: status=%s upstream_code=%s",
|
|
52
|
+
exc.response.status_code,
|
|
53
|
+
code,
|
|
54
|
+
)
|
|
55
|
+
message = detail if isinstance(detail, str) and detail else GENERIC_ERROR_MESSAGE
|
|
56
|
+
return {"status": "error", "code": code, "message": message}
|
|
57
|
+
|
|
58
|
+
logger.warning(
|
|
59
|
+
"MCP_UPSTREAM_HTTP_ERROR: status=%s unmappable_body=%r",
|
|
60
|
+
exc.response.status_code,
|
|
61
|
+
body,
|
|
62
|
+
)
|
|
63
|
+
return {
|
|
64
|
+
"status": "error",
|
|
65
|
+
"code": UPSTREAM_UNPARSEABLE_CODE,
|
|
66
|
+
"message": UPSTREAM_UNPARSEABLE_MESSAGE,
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class RegionalPlaneClient:
|
|
71
|
+
"""HTTP client for calling regional-plane public APIs.
|
|
72
|
+
|
|
73
|
+
All requests are authenticated with the same Bearer API key the MCP
|
|
74
|
+
client presented. The regional-plane validates the key independently.
|
|
75
|
+
"""
|
|
76
|
+
|
|
77
|
+
def __init__(self, base_url: str, api_key: str) -> None:
|
|
78
|
+
self._base_url = base_url.rstrip("/")
|
|
79
|
+
self._api_key = api_key
|
|
80
|
+
self._headers = {
|
|
81
|
+
"Authorization": f"Bearer {api_key}",
|
|
82
|
+
"Content-Type": "application/json",
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async def get(
|
|
86
|
+
self,
|
|
87
|
+
path: str,
|
|
88
|
+
*,
|
|
89
|
+
timeout: float = _DEFAULT_TIMEOUT,
|
|
90
|
+
) -> Dict[str, Any]:
|
|
91
|
+
"""Make an authenticated GET request to the regional-plane.
|
|
92
|
+
|
|
93
|
+
Args:
|
|
94
|
+
path: API path (e.g. "/p/{project_id}/v1/spaces/{space_id}/files")
|
|
95
|
+
timeout: Request timeout in seconds
|
|
96
|
+
|
|
97
|
+
Returns:
|
|
98
|
+
JSON response body
|
|
99
|
+
|
|
100
|
+
Raises:
|
|
101
|
+
httpx.HTTPStatusError: On 4xx/5xx responses
|
|
102
|
+
"""
|
|
103
|
+
url = f"{self._base_url}{path}"
|
|
104
|
+
logger.debug("API_GET: %s", url)
|
|
105
|
+
|
|
106
|
+
async with httpx.AsyncClient(timeout=timeout) as client:
|
|
107
|
+
resp = await client.get(url, headers=self._headers)
|
|
108
|
+
resp.raise_for_status()
|
|
109
|
+
return resp.json()
|
|
110
|
+
|
|
111
|
+
async def post(
|
|
112
|
+
self,
|
|
113
|
+
path: str,
|
|
114
|
+
*,
|
|
115
|
+
json_body: Dict[str, Any],
|
|
116
|
+
timeout: float = _DEFAULT_TIMEOUT,
|
|
117
|
+
) -> Dict[str, Any]:
|
|
118
|
+
"""Make an authenticated POST request to the regional-plane.
|
|
119
|
+
|
|
120
|
+
Args:
|
|
121
|
+
path: API path
|
|
122
|
+
json_body: Request body
|
|
123
|
+
timeout: Request timeout in seconds
|
|
124
|
+
|
|
125
|
+
Returns:
|
|
126
|
+
JSON response body
|
|
127
|
+
|
|
128
|
+
Raises:
|
|
129
|
+
httpx.HTTPStatusError: On 4xx/5xx responses
|
|
130
|
+
"""
|
|
131
|
+
url = f"{self._base_url}{path}"
|
|
132
|
+
logger.debug("API_POST: %s", url)
|
|
133
|
+
|
|
134
|
+
async with httpx.AsyncClient(timeout=timeout) as client:
|
|
135
|
+
resp = await client.post(url, headers=self._headers, json=json_body)
|
|
136
|
+
resp.raise_for_status()
|
|
137
|
+
return resp.json()
|
diffmem_mcp/asgi.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
"""ASGI application factory for the HTTP transports (streamable HTTP + SSE).
|
|
2
|
+
|
|
3
|
+
Creates a Starlette ASGI app wrapping the FastMCP streamable-HTTP endpoint at
|
|
4
|
+
the inner path ``/mcp`` plus the legacy SSE endpoints (``/sse`` +
|
|
5
|
+
``/messages``, deprecated — ADR-039). Mounted by the regional-plane at
|
|
6
|
+
``/p/{project_id}`` (ADR-030 — regional, co-located, edge-routed) and usable
|
|
7
|
+
standalone for stdio-less local runs.
|
|
8
|
+
|
|
9
|
+
Public URL shape (inner path is ``/mcp``, RP mount is ``/p/{project_id}``):
|
|
10
|
+
- Streamable HTTP (recommended): ``/p/{project_id}/mcp``
|
|
11
|
+
- Legacy SSE: ``/p/{project_id}/mcp/sse`` + ``/p/{project_id}/mcp/messages``
|
|
12
|
+
- Health: ``/p/{project_id}/health``
|
|
13
|
+
|
|
14
|
+
Auth contract (single validation per request, no env-var race):
|
|
15
|
+
``AuthHeaderMiddleware`` extracts the Bearer key from the Authorization header
|
|
16
|
+
and publishes it — together with the mount's path ``project_id`` — on a
|
|
17
|
+
**per-request contextvar**. ``DiffMemContext`` reads identity from that
|
|
18
|
+
contextvar; the process-global ``os.environ`` is never written. Concurrent SSE
|
|
19
|
+
clients with different keys are isolated by construction.
|
|
20
|
+
|
|
21
|
+
The project-scoped mount is a cross-tenant guard: a request to
|
|
22
|
+
``/p/proj_a_x/mcp`` carrying a key for ``proj_b_y`` fails loud at handshake
|
|
23
|
+
(``project_mismatch``) instead of operating on the wrong project's data.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import logging
|
|
29
|
+
from contextlib import asynccontextmanager
|
|
30
|
+
from contextvars import ContextVar
|
|
31
|
+
from dataclasses import dataclass
|
|
32
|
+
from typing import TYPE_CHECKING, AsyncIterator, Optional
|
|
33
|
+
|
|
34
|
+
if TYPE_CHECKING:
|
|
35
|
+
from starlette.applications import Starlette
|
|
36
|
+
|
|
37
|
+
logger = logging.getLogger(__name__)
|
|
38
|
+
|
|
39
|
+
__all__ = [
|
|
40
|
+
"create_mcp_asgi_app",
|
|
41
|
+
"mcp_session_manager_lifespan",
|
|
42
|
+
"AuthHeaderMiddleware",
|
|
43
|
+
"RequestIdentity",
|
|
44
|
+
"current_identity",
|
|
45
|
+
]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(frozen=True)
|
|
49
|
+
class RequestIdentity:
|
|
50
|
+
"""Per-request identity published by ``AuthHeaderMiddleware``."""
|
|
51
|
+
|
|
52
|
+
raw_key: str = ""
|
|
53
|
+
path_project_id: Optional[str] = None # set by the RP project-scoped mount guard
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
_current_identity: ContextVar[Optional[RequestIdentity]] = ContextVar(
|
|
57
|
+
"mcp_request_identity", default=None
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def current_identity() -> Optional[RequestIdentity]:
|
|
62
|
+
"""Identity for the in-flight request, or ``None`` outside SSE requests (stdio)."""
|
|
63
|
+
return _current_identity.get()
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class AuthHeaderMiddleware:
|
|
67
|
+
"""Extract the Bearer key from the Authorization header per request.
|
|
68
|
+
|
|
69
|
+
WHY A CONTEXTVAR, NOT ``os.environ``: the pre-ADR-030 bridge wrote the key
|
|
70
|
+
into the process-global environment, so two concurrent SSE clients with
|
|
71
|
+
different keys raced on a single slot and the shared auth cache could serve
|
|
72
|
+
one client's identity to another. A contextvar is task-local — no shared
|
|
73
|
+
state, no race.
|
|
74
|
+
"""
|
|
75
|
+
|
|
76
|
+
def __init__(self, app):
|
|
77
|
+
self.app = app
|
|
78
|
+
|
|
79
|
+
async def __call__(self, scope, receive, send):
|
|
80
|
+
identity: Optional[RequestIdentity] = None
|
|
81
|
+
token = None
|
|
82
|
+
if scope["type"] in ("http", "websocket"):
|
|
83
|
+
headers = dict(scope.get("headers", []))
|
|
84
|
+
auth_header = headers.get(b"authorization", b"").decode("utf-8")
|
|
85
|
+
raw_key = auth_header[7:].strip() if auth_header.startswith("Bearer ") else ""
|
|
86
|
+
path_project_id = (scope.get("state") or {}).get("mcp_path_project_id")
|
|
87
|
+
identity = RequestIdentity(raw_key=raw_key, path_project_id=path_project_id)
|
|
88
|
+
token = _current_identity.set(identity)
|
|
89
|
+
logger.debug(
|
|
90
|
+
"AUTH_IDENTITY_SET: key_prefix=%s path_project_id=%s",
|
|
91
|
+
identity.raw_key[:8],
|
|
92
|
+
identity.path_project_id,
|
|
93
|
+
)
|
|
94
|
+
try:
|
|
95
|
+
return await self.app(scope, receive, send)
|
|
96
|
+
finally:
|
|
97
|
+
if token is not None:
|
|
98
|
+
_current_identity.reset(token)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def create_mcp_asgi_app() -> Starlette:
|
|
102
|
+
"""Create a Starlette ASGI app with streamable HTTP + SSE routes.
|
|
103
|
+
|
|
104
|
+
This function imports the module-level ``mcp`` instance from
|
|
105
|
+
``diffmem_mcp.server`` and registers tools before returning the app.
|
|
106
|
+
It is safe to call multiple times (tool registration is idempotent).
|
|
107
|
+
|
|
108
|
+
Route precedence matters: the exact-path streamable Route (``/mcp``,
|
|
109
|
+
POST/GET/DELETE) is inserted before the ``/mcp`` Mount so ``/sse`` and
|
|
110
|
+
``/messages`` fall through to the SSE app while ``/mcp`` itself serves
|
|
111
|
+
streamable HTTP.
|
|
112
|
+
|
|
113
|
+
Returns:
|
|
114
|
+
A Starlette ASGI application with both HTTP transports.
|
|
115
|
+
"""
|
|
116
|
+
from diffmem_mcp.server import mcp
|
|
117
|
+
from diffmem_mcp.tools import register_tools
|
|
118
|
+
|
|
119
|
+
register_tools(mcp)
|
|
120
|
+
|
|
121
|
+
logger.info("Creating MCP ASGI app with streamable HTTP + SSE transports")
|
|
122
|
+
sse_app = mcp.sse_app()
|
|
123
|
+
http_app = mcp.streamable_http_app() # instantiates the session manager
|
|
124
|
+
|
|
125
|
+
# Parent app adds /health (Cloud Run + CI smoke + GLB operational probes)
|
|
126
|
+
# and re-hosts the streamable route ahead of the SSE mount so the two
|
|
127
|
+
# transports share the /mcp prefix without shadowing each other.
|
|
128
|
+
async def _health(request): # pragma: no cover - trivial responder
|
|
129
|
+
from starlette.responses import JSONResponse
|
|
130
|
+
|
|
131
|
+
return JSONResponse({"status": "ok", "service": "diffmem-mcp-server"})
|
|
132
|
+
|
|
133
|
+
from starlette.applications import Starlette as ParentApp
|
|
134
|
+
from starlette.routing import Mount, Route
|
|
135
|
+
|
|
136
|
+
app = ParentApp(
|
|
137
|
+
routes=[
|
|
138
|
+
Route("/health", _health, methods=["GET"]),
|
|
139
|
+
# The SDK route serves the streamable ASGI handler (class-based,
|
|
140
|
+
# so all methods — POST/GET/DELETE — pass through). Its Starlette
|
|
141
|
+
# app carries the session-manager lifespan, which a MOUNT would
|
|
142
|
+
# swallow; the parent lifespan below runs it instead.
|
|
143
|
+
*http_app.routes,
|
|
144
|
+
Mount("/mcp", app=sse_app),
|
|
145
|
+
],
|
|
146
|
+
lifespan=mcp_session_manager_lifespan,
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
# Wrap with auth middleware to publish per-request identity.
|
|
150
|
+
# Starlette apps are ASGI callable, so we wrap directly.
|
|
151
|
+
return AuthHeaderMiddleware(app)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
@asynccontextmanager
|
|
155
|
+
async def mcp_session_manager_lifespan(app: object = None) -> AsyncIterator[None]:
|
|
156
|
+
"""Run the FastMCP streamable-HTTP session manager.
|
|
157
|
+
|
|
158
|
+
The SDK ties the manager to the streamable app's Starlette lifespan, but
|
|
159
|
+
Starlette does NOT propagate lifespan to mounted sub-apps — so the
|
|
160
|
+
regional-plane (which mounts this factory's app) enters this context from
|
|
161
|
+
its own FastAPI lifespan. Standalone uvicorn runs reach it through the
|
|
162
|
+
parent app's lifespan (same function). ``run()`` may be called exactly
|
|
163
|
+
once per process.
|
|
164
|
+
"""
|
|
165
|
+
from diffmem_mcp.server import mcp
|
|
166
|
+
from diffmem_mcp.tools import register_tools
|
|
167
|
+
|
|
168
|
+
register_tools(mcp)
|
|
169
|
+
mcp.streamable_http_app() # ensure the session manager exists
|
|
170
|
+
async with mcp.session_manager.run():
|
|
171
|
+
yield
|
diffmem_mcp/auth.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"""API key validation for the MCP server.
|
|
2
|
+
|
|
3
|
+
Validates DiffMem API keys via the DiffMem API's ``GET /v1/auth/validate``
|
|
4
|
+
endpoint — the same Bearer-key mechanism every tool call uses. No local
|
|
5
|
+
Firestore: customer machines have no GCP credentials, and validation must
|
|
6
|
+
work identically for stdio (env key) and hosted SSE (Authorization header).
|
|
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.
|
|
12
|
+
|
|
13
|
+
For stdio transport, the API key is provided via the DIFFMEM_API_KEY
|
|
14
|
+
environment variable (set by the MCP client, e.g. Claude Desktop or Cursor).
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import logging
|
|
20
|
+
import os
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
from typing import Mapping, Optional
|
|
23
|
+
|
|
24
|
+
import httpx
|
|
25
|
+
|
|
26
|
+
logger = logging.getLogger(__name__)
|
|
27
|
+
|
|
28
|
+
_VALIDATE_PATH = "/v1/auth/validate"
|
|
29
|
+
_VALIDATE_TIMEOUT = 10.0
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True)
|
|
33
|
+
class AuthContext:
|
|
34
|
+
"""Immutable auth context derived from a validated API key."""
|
|
35
|
+
|
|
36
|
+
key_id: str
|
|
37
|
+
project_id: str
|
|
38
|
+
label: str
|
|
39
|
+
raw_key: str # Retained for forwarding to regional-plane as Bearer token
|
|
40
|
+
# Null = legacy key / full access (spec #77 §4). A non-null list is the
|
|
41
|
+
# key's exact powers — strictly additive, no implied scopes.
|
|
42
|
+
scopes: Optional[list[str]] = None
|
|
43
|
+
# Null = legacy key / all spaces (spec #77 §5). A non-null list is the
|
|
44
|
+
# static allowlist minted at key creation — spaces created after issuance
|
|
45
|
+
# are never auto-accessible.
|
|
46
|
+
space_allowlist: Optional[list[str]] = None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class AuthError(Exception):
|
|
50
|
+
"""Raised when API key validation fails."""
|
|
51
|
+
|
|
52
|
+
def __init__(self, code: str, message: str):
|
|
53
|
+
self.code = code
|
|
54
|
+
self.message = message
|
|
55
|
+
super().__init__(message)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class ApiKeyValidator:
|
|
59
|
+
"""Validates DiffMem API keys against the DiffMem API.
|
|
60
|
+
|
|
61
|
+
Usage:
|
|
62
|
+
validator = ApiKeyValidator(api_urls)
|
|
63
|
+
ctx = await validator.validate("dk_abc123...")
|
|
64
|
+
|
|
65
|
+
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.
|
|
69
|
+
"""
|
|
70
|
+
|
|
71
|
+
def __init__(
|
|
72
|
+
self,
|
|
73
|
+
api_urls: Mapping[str, str],
|
|
74
|
+
transport: httpx.AsyncBaseTransport | None = None,
|
|
75
|
+
) -> None:
|
|
76
|
+
if not api_urls:
|
|
77
|
+
raise AuthError(
|
|
78
|
+
code="config_error",
|
|
79
|
+
message="DIFFMEM_API_URLS is empty — no API endpoint to validate against.",
|
|
80
|
+
)
|
|
81
|
+
self._base_url = sorted(api_urls.values())[0].rstrip("/")
|
|
82
|
+
self._transport = transport # test seam: inject httpx.MockTransport
|
|
83
|
+
|
|
84
|
+
async def validate(self, raw_key: str) -> AuthContext:
|
|
85
|
+
"""Validate a raw API key and return its auth context.
|
|
86
|
+
|
|
87
|
+
Args:
|
|
88
|
+
raw_key: The raw API key string (e.g. "dk_abc123...")
|
|
89
|
+
|
|
90
|
+
Returns:
|
|
91
|
+
AuthContext with key_id, project_id, label, scopes, space_allowlist
|
|
92
|
+
|
|
93
|
+
Raises:
|
|
94
|
+
AuthError: code ``missing_api_key`` (empty key), ``invalid_api_key``
|
|
95
|
+
(invalid/revoked — permanent), or ``auth_unavailable``
|
|
96
|
+
(API unreachable/5xx — transient, retry later).
|
|
97
|
+
"""
|
|
98
|
+
if not raw_key:
|
|
99
|
+
raise AuthError(code="missing_api_key", message="API key is required.")
|
|
100
|
+
|
|
101
|
+
try:
|
|
102
|
+
resp = await httpx.AsyncClient(
|
|
103
|
+
timeout=_VALIDATE_TIMEOUT, transport=self._transport
|
|
104
|
+
).get(
|
|
105
|
+
f"{self._base_url}{_VALIDATE_PATH}",
|
|
106
|
+
headers={"Authorization": f"Bearer {raw_key}"},
|
|
107
|
+
)
|
|
108
|
+
except httpx.HTTPError as exc:
|
|
109
|
+
logger.error("AUTH_UNAVAILABLE: base_url=%s error=%r", self._base_url, exc)
|
|
110
|
+
raise AuthError(
|
|
111
|
+
code="auth_unavailable",
|
|
112
|
+
message="Could not reach the DiffMem API to validate the key. Retry shortly.",
|
|
113
|
+
) from exc
|
|
114
|
+
|
|
115
|
+
if resp.status_code == 401:
|
|
116
|
+
logger.warning("AUTH_INVALID_KEY: key rejected by API (401)")
|
|
117
|
+
raise AuthError(
|
|
118
|
+
code="invalid_api_key",
|
|
119
|
+
message="API key is invalid or revoked.",
|
|
120
|
+
)
|
|
121
|
+
if resp.status_code != 200:
|
|
122
|
+
logger.error(
|
|
123
|
+
"AUTH_UNAVAILABLE: base_url=%s status=%s", self._base_url, resp.status_code
|
|
124
|
+
)
|
|
125
|
+
raise AuthError(
|
|
126
|
+
code="auth_unavailable",
|
|
127
|
+
message="DiffMem API could not validate the key. Retry shortly.",
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
body = resp.json()
|
|
131
|
+
project_id = body.get("project_id")
|
|
132
|
+
key_id = body.get("key_id")
|
|
133
|
+
if not isinstance(project_id, str) or not project_id or not key_id:
|
|
134
|
+
logger.error("AUTH_MISSING_PROJECT: validate response missing key identity")
|
|
135
|
+
raise AuthError(
|
|
136
|
+
code="invalid_api_key",
|
|
137
|
+
message="API key is not associated with a project.",
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
logger.info("AUTH_SUCCESS: key_id=%s project_id=%s", key_id, project_id)
|
|
141
|
+
|
|
142
|
+
return AuthContext(
|
|
143
|
+
key_id=key_id,
|
|
144
|
+
project_id=project_id,
|
|
145
|
+
label=body.get("label", ""),
|
|
146
|
+
raw_key=raw_key,
|
|
147
|
+
scopes=body.get("scopes"),
|
|
148
|
+
space_allowlist=body.get("space_allowlist"),
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def get_api_key_from_env() -> Optional[str]:
|
|
153
|
+
"""Get the API key from DIFFMEM_API_KEY environment variable.
|
|
154
|
+
|
|
155
|
+
Returns:
|
|
156
|
+
The API key string, or None if not set
|
|
157
|
+
"""
|
|
158
|
+
return os.environ.get("DIFFMEM_API_KEY")
|
diffmem_mcp/context.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
# CAPABILITY: MCP auth context with TTL re-validation (spec #77 / ticket #81)
|
|
2
|
+
# Lives apart from server.py so the auth seam is testable without the FastMCP
|
|
3
|
+
# import (mcp 2.x renames break that import path; runtime pins mcp<2).
|
|
4
|
+
#
|
|
5
|
+
# Auth cache semantics (ADR-030, per-key): validated AuthContexts are cached
|
|
6
|
+
# by SHA-256(key) for `auth_ttl` seconds — revocations and scope edits
|
|
7
|
+
# propagate within the bounded window without a process restart. The cache is
|
|
8
|
+
# KEYED, not single-slot: concurrent SSE clients with different keys get
|
|
9
|
+
# isolated identities (the pre-ADR-030 single-slot design could serve one
|
|
10
|
+
# client's auth to another after a cache hit).
|
|
11
|
+
#
|
|
12
|
+
# Identity source: the per-request contextvar published by AuthHeaderMiddleware
|
|
13
|
+
# (SSE), falling back to DIFFMEM_API_KEY env (stdio — one process, one key).
|
|
14
|
+
# A path-project mismatch (URL project ≠ key project) fails loud: the
|
|
15
|
+
# project-scoped mount is a residency/correctness contract, not a hint.
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import hashlib
|
|
20
|
+
import time
|
|
21
|
+
from contextvars import ContextVar
|
|
22
|
+
from dataclasses import dataclass, field
|
|
23
|
+
|
|
24
|
+
from diffmem_mcp.auth import ApiKeyValidator, AuthContext
|
|
25
|
+
|
|
26
|
+
DEFAULT_AUTH_TTL = 60
|
|
27
|
+
_MAX_AUTH_CACHE = 256 # distinct keys per process; FIFO-evict beyond this
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True)
|
|
31
|
+
class _CacheEntry:
|
|
32
|
+
auth: AuthContext
|
|
33
|
+
cached_at: float
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass
|
|
37
|
+
class DiffMemContext:
|
|
38
|
+
"""Holds validated auth and derived state for the current MCP session."""
|
|
39
|
+
|
|
40
|
+
# Auth cache TTL (seconds): revocations and scope edits propagate within
|
|
41
|
+
# this bounded window without a process restart (spec #77 §7.5).
|
|
42
|
+
auth_ttl: int = DEFAULT_AUTH_TTL
|
|
43
|
+
_auth_cache: dict[str, _CacheEntry] = field(default_factory=dict, repr=False)
|
|
44
|
+
_validator: ApiKeyValidator | None = field(default=None, repr=False)
|
|
45
|
+
|
|
46
|
+
async def get_auth(self) -> AuthContext:
|
|
47
|
+
"""Get the auth context for the in-flight identity, revalidating after TTL.
|
|
48
|
+
|
|
49
|
+
Raises:
|
|
50
|
+
AuthError: If no key is present, the key is invalid/revoked, or the
|
|
51
|
+
mount-path project_id does not match the key's project_id.
|
|
52
|
+
"""
|
|
53
|
+
from diffmem_mcp.asgi import current_identity
|
|
54
|
+
|
|
55
|
+
identity = current_identity()
|
|
56
|
+
raw_key = identity.raw_key if identity is not None else (self._env_key() or "")
|
|
57
|
+
if not raw_key:
|
|
58
|
+
raise self._missing_key_error()
|
|
59
|
+
|
|
60
|
+
key_hash = hashlib.sha256(raw_key.encode()).hexdigest()
|
|
61
|
+
now = time.monotonic()
|
|
62
|
+
|
|
63
|
+
cached = self._auth_cache.get(key_hash)
|
|
64
|
+
if cached is not None and (now - cached.cached_at) < self.auth_ttl:
|
|
65
|
+
auth = cached.auth
|
|
66
|
+
else:
|
|
67
|
+
if self._validator is None:
|
|
68
|
+
# Key validation happens via the DiffMem API (no local
|
|
69
|
+
# Firestore — customer machines have no GCP credentials).
|
|
70
|
+
from diffmem_mcp.settings import get_settings
|
|
71
|
+
|
|
72
|
+
self._validator = ApiKeyValidator(get_settings().get_api_urls())
|
|
73
|
+
auth = await self._validator.validate(raw_key)
|
|
74
|
+
self._auth_cache[key_hash] = _CacheEntry(auth=auth, cached_at=now)
|
|
75
|
+
if len(self._auth_cache) > _MAX_AUTH_CACHE:
|
|
76
|
+
oldest = min(self._auth_cache, key=lambda k: self._auth_cache[k].cached_at)
|
|
77
|
+
del self._auth_cache[oldest]
|
|
78
|
+
|
|
79
|
+
# Cross-tenant guard: the project-scoped mount path must agree with the
|
|
80
|
+
# key's project. Mismatch = client misconfiguration; fail loud.
|
|
81
|
+
if identity is not None and identity.path_project_id:
|
|
82
|
+
if auth.project_id != identity.path_project_id:
|
|
83
|
+
from diffmem_mcp.auth import AuthError
|
|
84
|
+
|
|
85
|
+
raise AuthError(
|
|
86
|
+
code="project_mismatch",
|
|
87
|
+
message=(
|
|
88
|
+
f"URL project '{identity.path_project_id}' does not match "
|
|
89
|
+
f"the API key's project '{auth.project_id}'."
|
|
90
|
+
),
|
|
91
|
+
)
|
|
92
|
+
return auth
|
|
93
|
+
|
|
94
|
+
@staticmethod
|
|
95
|
+
def _env_key() -> str | None:
|
|
96
|
+
import os
|
|
97
|
+
|
|
98
|
+
return os.environ.get("DIFFMEM_API_KEY") or None
|
|
99
|
+
|
|
100
|
+
@staticmethod
|
|
101
|
+
def _missing_key_error() -> Exception:
|
|
102
|
+
from diffmem_mcp.auth import AuthError
|
|
103
|
+
|
|
104
|
+
return AuthError(
|
|
105
|
+
code="missing_api_key",
|
|
106
|
+
message=(
|
|
107
|
+
"No API key on the request (Authorization header) and "
|
|
108
|
+
"DIFFMEM_API_KEY is not set. Configure your MCP client to pass "
|
|
109
|
+
"the key as a Bearer token or via the environment variable."
|
|
110
|
+
),
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
# Global context instance — safe to share: identity arrives per-request via
|
|
115
|
+
# contextvar; validated auth is cached per key-hash, never per-client-slot.
|
|
116
|
+
_context: DiffMemContext | None = None
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def get_context() -> DiffMemContext:
|
|
120
|
+
"""Get or create the global DiffMemContext."""
|
|
121
|
+
global _context
|
|
122
|
+
if _context is None:
|
|
123
|
+
_context = DiffMemContext()
|
|
124
|
+
return _context
|