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/router.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
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)
|
diffmem_mcp/scopes.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
# CAPABILITY: MCP-surface scope vocabulary + enforcement (spec #77 / ticket #81)
|
|
2
|
+
# Semantics: mirrors regional-plane app/core/scopes.py exactly — strictly
|
|
3
|
+
# additive composition, no sentinel scope, unknown scopes fail closed.
|
|
4
|
+
# The MCP layer is defense-in-depth over the RP per-request enforcement.
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import logging
|
|
9
|
+
|
|
10
|
+
from diffmem_mcp.security import SecurityError, ensure_space_permitted
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
SCOPE_MEMORY_READ = "memory:read"
|
|
15
|
+
SCOPE_MEMORY_WRITE = "memory:write"
|
|
16
|
+
SCOPE_FILES_READ = "files:read"
|
|
17
|
+
SCOPE_FILES_WRITE = "files:write"
|
|
18
|
+
SCOPE_INTROSPECT_READ = "introspect:read"
|
|
19
|
+
|
|
20
|
+
KNOWN_SCOPES: frozenset[str] = frozenset(
|
|
21
|
+
{
|
|
22
|
+
SCOPE_MEMORY_READ,
|
|
23
|
+
SCOPE_MEMORY_WRITE,
|
|
24
|
+
SCOPE_FILES_READ,
|
|
25
|
+
SCOPE_FILES_WRITE,
|
|
26
|
+
SCOPE_INTROSPECT_READ,
|
|
27
|
+
}
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def enforce_tool_access(auth, required_scope: str, space_ids: list[str] | None = None) -> None:
|
|
32
|
+
"""One seam for the whole tool-level check pipeline (spec #77 §7.3).
|
|
33
|
+
|
|
34
|
+
Enforces scope → space-allowlist in the normative order, BEFORE any I/O
|
|
35
|
+
or quota, so the ordering is structural rather than convention. Every
|
|
36
|
+
tool's first line after ``get_auth()`` is this call; space-targeting
|
|
37
|
+
tools pass the addressed space ids. Legacy keys (null scopes) pass with
|
|
38
|
+
LEGACY_KEY_FULL_ACCESS logged.
|
|
39
|
+
"""
|
|
40
|
+
enforce_scope(auth, required_scope)
|
|
41
|
+
for sid in space_ids or ():
|
|
42
|
+
ensure_space_permitted(auth, sid)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def enforce_scope(auth, required_scope: str) -> None:
|
|
46
|
+
"""Scope check for one MCP tool call. Fail closed, before any I/O.
|
|
47
|
+
|
|
48
|
+
Legacy keys (scopes == null) pass everywhere — LEGACY_KEY_FULL_ACCESS
|
|
49
|
+
makes the log stream a migration-progress dashboard. Unknown scope
|
|
50
|
+
strings deny the key on every tool call (SCOPE_UNKNOWN). A scoped key
|
|
51
|
+
without the required scope is denied with insufficient_scope, naming
|
|
52
|
+
the required scope so the caller can self-serve the fix.
|
|
53
|
+
"""
|
|
54
|
+
scopes: list[str] | None = auth.scopes
|
|
55
|
+
key_id = auth.key_id
|
|
56
|
+
|
|
57
|
+
if scopes is None:
|
|
58
|
+
logger.info("LEGACY_KEY_FULL_ACCESS: key_id=%s required_scope=%s", key_id, required_scope)
|
|
59
|
+
return
|
|
60
|
+
|
|
61
|
+
# Defense-in-depth: validation prevents minting unknown scopes, but a key
|
|
62
|
+
# doc written out-of-band must never widen access.
|
|
63
|
+
unknown = sorted(set(scopes) - KNOWN_SCOPES)
|
|
64
|
+
if unknown:
|
|
65
|
+
logger.error(
|
|
66
|
+
"SCOPE_UNKNOWN: key_id=%s unknown_scopes=%s required_scope=%s",
|
|
67
|
+
key_id,
|
|
68
|
+
",".join(unknown),
|
|
69
|
+
required_scope,
|
|
70
|
+
)
|
|
71
|
+
raise SecurityError(
|
|
72
|
+
code="insufficient_scope",
|
|
73
|
+
message=(
|
|
74
|
+
f"API key carries unknown scope(s): {', '.join(unknown)}. "
|
|
75
|
+
"Re-issue the key with valid scopes."
|
|
76
|
+
),
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
if required_scope not in scopes:
|
|
80
|
+
logger.info(
|
|
81
|
+
"INSUFFICIENT_SCOPE: key_id=%s required_scope=%s key_scopes=%s",
|
|
82
|
+
key_id,
|
|
83
|
+
required_scope,
|
|
84
|
+
",".join(sorted(scopes)),
|
|
85
|
+
)
|
|
86
|
+
raise SecurityError(
|
|
87
|
+
code="insufficient_scope",
|
|
88
|
+
message=f"API key lacks required scope: {required_scope}.",
|
|
89
|
+
)
|
diffmem_mcp/security.py
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
"""Security enforcement layer for the DiffMem MCP server.
|
|
2
|
+
|
|
3
|
+
Provides deterministic, zero-trust security enforcement:
|
|
4
|
+
- Space-allowlist enforcement (local, from the key's validated allowlist)
|
|
5
|
+
- Rate limiting (token-bucket per API key)
|
|
6
|
+
- Audit logging (every tool invocation logged)
|
|
7
|
+
|
|
8
|
+
Space existence and quota are enforced by the regional plane itself
|
|
9
|
+
(scope → space-allowlist → quota → handler, spec #77 §7.3) — the bridge no
|
|
10
|
+
longer duplicates those checks against Firestore (customer machines have no
|
|
11
|
+
GCP credentials); plane denials pass through to tool output via ADR-038.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import hashlib
|
|
17
|
+
import logging
|
|
18
|
+
import time
|
|
19
|
+
from collections import defaultdict
|
|
20
|
+
from dataclasses import dataclass, field
|
|
21
|
+
from datetime import UTC, datetime
|
|
22
|
+
from typing import Any, Dict, Optional
|
|
23
|
+
|
|
24
|
+
logger = logging.getLogger(__name__)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _enforce_space_allowlist(auth, space_id: str, *, surface: str, code: str, message: str) -> None:
|
|
28
|
+
"""Shared allowlist gate for the two denial semantics (spec #77 §5).
|
|
29
|
+
|
|
30
|
+
Introspection treats an excluded space as nonexistent (invisible-not-403);
|
|
31
|
+
memory/files treat it as an explicit denial. Legacy keys (null allowlist)
|
|
32
|
+
see all spaces. Every denial emits a structured SPACE_DENIED WARN.
|
|
33
|
+
"""
|
|
34
|
+
allowlist = auth.space_allowlist
|
|
35
|
+
if allowlist is None or space_id in allowlist:
|
|
36
|
+
return
|
|
37
|
+
logger.warning(
|
|
38
|
+
"SPACE_DENIED: key_id=%s project_id=%s space_id=%s surface=%s allowlist=%s",
|
|
39
|
+
auth.key_id,
|
|
40
|
+
auth.project_id,
|
|
41
|
+
space_id,
|
|
42
|
+
surface,
|
|
43
|
+
",".join(allowlist),
|
|
44
|
+
)
|
|
45
|
+
raise SecurityError(code=code, message=message)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def ensure_space_allowed(auth, space_id: str) -> None:
|
|
49
|
+
"""Introspection invisibility for space allowlists (spec #77 §5/#80 site 3).
|
|
50
|
+
|
|
51
|
+
An excluded space must be indistinguishable from a nonexistent one:
|
|
52
|
+
this raises ``space_not_found`` (NOT a 403-style ``access_denied``) and
|
|
53
|
+
emits a structured ``SPACE_DENIED`` WARN carrying key and space so
|
|
54
|
+
probing/misconfiguration stays visible in the log stream. Legacy keys
|
|
55
|
+
(``space_allowlist is None``) see all spaces.
|
|
56
|
+
"""
|
|
57
|
+
_enforce_space_allowlist(
|
|
58
|
+
auth,
|
|
59
|
+
space_id,
|
|
60
|
+
surface="mcp_introspection",
|
|
61
|
+
code="space_not_found",
|
|
62
|
+
message=f"Space '{space_id}' not found in project.",
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def ensure_space_permitted(auth, space_id: str) -> None:
|
|
67
|
+
"""Space-allowlist denial for memory/files MCP tools (spec #77 §5, #81).
|
|
68
|
+
|
|
69
|
+
Unlike introspection (ensure_space_allowed: invisible-not-403), a
|
|
70
|
+
memory/files operation on an excluded space is an explicit DENIAL:
|
|
71
|
+
raises ``space_denied``. Legacy keys (``space_allowlist is None``) see
|
|
72
|
+
all spaces.
|
|
73
|
+
"""
|
|
74
|
+
_enforce_space_allowlist(
|
|
75
|
+
auth,
|
|
76
|
+
space_id,
|
|
77
|
+
surface="mcp_tool",
|
|
78
|
+
code="space_denied",
|
|
79
|
+
message=(
|
|
80
|
+
f"API key is not permitted to access space '{space_id}'. "
|
|
81
|
+
"Ask the project owner to re-issue the key with this space allowed."
|
|
82
|
+
),
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def filter_spaces_to_allowlist(auth, spaces: list[dict]) -> list[dict]:
|
|
87
|
+
"""Filter a listing of space docs to the key's allowlist (spec #80 site 3).
|
|
88
|
+
|
|
89
|
+
Excluded spaces are INVISIBLE — absent from results, never a denial.
|
|
90
|
+
Emits one structured ``SPACES_FILTERED`` INFO event when anything was
|
|
91
|
+
dropped. Legacy keys (``space_allowlist is None``) pass through unchanged.
|
|
92
|
+
"""
|
|
93
|
+
allowlist = getattr(auth, "space_allowlist", None)
|
|
94
|
+
if allowlist is None:
|
|
95
|
+
return spaces
|
|
96
|
+
allowed = set(allowlist)
|
|
97
|
+
kept = [s for s in spaces if s.get("space_id") in allowed]
|
|
98
|
+
excluded = sorted({s.get("space_id") for s in spaces} - allowed)
|
|
99
|
+
if excluded:
|
|
100
|
+
logger.info(
|
|
101
|
+
"SPACES_FILTERED: key_id=%s project_id=%s excluded_spaces=%s",
|
|
102
|
+
getattr(auth, "key_id", "unknown"),
|
|
103
|
+
getattr(auth, "project_id", "unknown"),
|
|
104
|
+
",".join(excluded),
|
|
105
|
+
)
|
|
106
|
+
return kept
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class SecurityError(Exception):
|
|
110
|
+
"""Raised when a security check fails."""
|
|
111
|
+
|
|
112
|
+
def __init__(self, code: str, message: str):
|
|
113
|
+
self.code = code
|
|
114
|
+
self.message = message
|
|
115
|
+
super().__init__(message)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
@dataclass
|
|
119
|
+
class TokenBucket:
|
|
120
|
+
"""Token bucket for rate limiting."""
|
|
121
|
+
|
|
122
|
+
capacity: int
|
|
123
|
+
refill_rate: float # tokens per second
|
|
124
|
+
tokens: float = field(init=False)
|
|
125
|
+
last_refill: float = field(init=False)
|
|
126
|
+
|
|
127
|
+
def __post_init__(self):
|
|
128
|
+
self.tokens = float(self.capacity)
|
|
129
|
+
self.last_refill = time.monotonic()
|
|
130
|
+
|
|
131
|
+
def consume(self) -> bool:
|
|
132
|
+
"""Try to consume one token. Returns True if allowed, False if rate limited."""
|
|
133
|
+
now = time.monotonic()
|
|
134
|
+
elapsed = now - self.last_refill
|
|
135
|
+
self.tokens = min(self.capacity, self.tokens + elapsed * self.refill_rate)
|
|
136
|
+
self.last_refill = now
|
|
137
|
+
|
|
138
|
+
if self.tokens >= 1.0:
|
|
139
|
+
self.tokens -= 1.0
|
|
140
|
+
return True
|
|
141
|
+
return False
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
class SecurityGuard:
|
|
145
|
+
"""Deterministic local rate limiting for all MCP tool calls.
|
|
146
|
+
|
|
147
|
+
Space existence and quota enforcement live on the regional plane
|
|
148
|
+
(spec #77 §7.3 normative order); only rate limiting is enforced locally,
|
|
149
|
+
since it protects the bridge process itself, not upstream storage.
|
|
150
|
+
|
|
151
|
+
Usage:
|
|
152
|
+
guard = SecurityGuard(rpm=60)
|
|
153
|
+
guard.check_rate_limit(key_id)
|
|
154
|
+
"""
|
|
155
|
+
|
|
156
|
+
def __init__(self, rpm: int = 60) -> None:
|
|
157
|
+
"""
|
|
158
|
+
Args:
|
|
159
|
+
rpm: Rate limit per API key (requests per minute)
|
|
160
|
+
"""
|
|
161
|
+
self._rpm = rpm
|
|
162
|
+
self._buckets: Dict[str, TokenBucket] = {}
|
|
163
|
+
|
|
164
|
+
def check_rate_limit(self, key_id: str) -> None:
|
|
165
|
+
"""Check rate limit for an API key using token-bucket algorithm.
|
|
166
|
+
|
|
167
|
+
Args:
|
|
168
|
+
key_id: The API key ID to check
|
|
169
|
+
|
|
170
|
+
Raises:
|
|
171
|
+
SecurityError: If rate limit is exceeded
|
|
172
|
+
"""
|
|
173
|
+
if key_id not in self._buckets:
|
|
174
|
+
self._buckets[key_id] = TokenBucket(
|
|
175
|
+
capacity=self._rpm,
|
|
176
|
+
refill_rate=self._rpm / 60.0, # tokens per second
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
if not self._buckets[key_id].consume():
|
|
180
|
+
logger.warning("RATE_LIMIT_EXCEEDED: key_id=%s", key_id)
|
|
181
|
+
raise SecurityError(
|
|
182
|
+
code="rate_limit_exceeded",
|
|
183
|
+
message=f"Rate limit exceeded ({self._rpm} requests per minute). Please slow down.",
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
class AuditLogger:
|
|
188
|
+
"""Structured audit logging for all MCP tool invocations.
|
|
189
|
+
|
|
190
|
+
Every tool call is logged with: tool name, key_id (hashed), project_id,
|
|
191
|
+
space_id (if applicable), success/failure, timestamp.
|
|
192
|
+
"""
|
|
193
|
+
|
|
194
|
+
@staticmethod
|
|
195
|
+
def _hash_key_id(key_id: str) -> str:
|
|
196
|
+
"""Hash key_id for logging (don't expose raw key IDs in logs)."""
|
|
197
|
+
return hashlib.sha256(key_id.encode()).hexdigest()[:16]
|
|
198
|
+
|
|
199
|
+
@staticmethod
|
|
200
|
+
def log_invocation(
|
|
201
|
+
*,
|
|
202
|
+
tool_name: str,
|
|
203
|
+
key_id: str,
|
|
204
|
+
project_id: str,
|
|
205
|
+
space_id: Optional[str] = None,
|
|
206
|
+
success: bool,
|
|
207
|
+
error_code: Optional[str] = None,
|
|
208
|
+
duration_ms: Optional[float] = None,
|
|
209
|
+
) -> None:
|
|
210
|
+
"""Log a tool invocation as a structured audit event.
|
|
211
|
+
|
|
212
|
+
Args:
|
|
213
|
+
tool_name: Name of the MCP tool
|
|
214
|
+
key_id: API key ID (will be hashed for logging)
|
|
215
|
+
project_id: Project ID from auth context
|
|
216
|
+
space_id: Space ID if applicable
|
|
217
|
+
success: Whether the call succeeded
|
|
218
|
+
error_code: Error code if failed
|
|
219
|
+
duration_ms: Call duration in milliseconds
|
|
220
|
+
"""
|
|
221
|
+
hashed_key = AuditLogger._hash_key_id(key_id)
|
|
222
|
+
status = "success" if success else "failure"
|
|
223
|
+
|
|
224
|
+
log_data = {
|
|
225
|
+
"event": "MCP_TOOL_INVOCATION",
|
|
226
|
+
"tool": tool_name,
|
|
227
|
+
"key_hash": hashed_key,
|
|
228
|
+
"project_id": project_id,
|
|
229
|
+
"status": status,
|
|
230
|
+
"timestamp": datetime.now(UTC).isoformat(),
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
if space_id:
|
|
234
|
+
log_data["space_id"] = space_id
|
|
235
|
+
if error_code:
|
|
236
|
+
log_data["error_code"] = error_code
|
|
237
|
+
if duration_ms is not None:
|
|
238
|
+
log_data["duration_ms"] = round(duration_ms, 1)
|
|
239
|
+
|
|
240
|
+
if success:
|
|
241
|
+
logger.info("MCP_TOOL_INVOCATION %s", log_data)
|
|
242
|
+
else:
|
|
243
|
+
logger.warning("MCP_TOOL_INVOCATION %s", log_data)
|
diffmem_mcp/server.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"""DiffMem MCP Server — main entry point.
|
|
2
|
+
|
|
3
|
+
Creates the MCP server instance and wires up auth context. Tools are registered
|
|
4
|
+
via the ``register_tools`` function from ``app.tools``.
|
|
5
|
+
|
|
6
|
+
For stdio transport, the API key is provided via DIFFMEM_API_KEY env var.
|
|
7
|
+
For HTTP transports (``--sse`` flag), the API key comes from the
|
|
8
|
+
Authorization header (handled by the regional-plane gateway).
|
|
9
|
+
|
|
10
|
+
HTTP transports (ADR-039): streamable HTTP at inner path ``/mcp`` (the
|
|
11
|
+
recommended remote transport) plus legacy SSE at ``/sse`` + ``/messages``.
|
|
12
|
+
The FastMCP instance is built stateless (``stateless_http=True``) so a
|
|
13
|
+
streamable session never pins to one Cloud Run instance.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import argparse
|
|
19
|
+
import logging
|
|
20
|
+
import sys
|
|
21
|
+
|
|
22
|
+
from mcp.server.fastmcp import FastMCP
|
|
23
|
+
from mcp.server.transport_security import TransportSecuritySettings
|
|
24
|
+
|
|
25
|
+
# Auth context (TTL re-validation) lives in context.py so the auth seam stays
|
|
26
|
+
# testable without the FastMCP import.
|
|
27
|
+
from diffmem_mcp.context import DiffMemContext, get_context # noqa: F401 (re-export)
|
|
28
|
+
|
|
29
|
+
logger = logging.getLogger(__name__)
|
|
30
|
+
|
|
31
|
+
# ---------------------------------------------------------------------------
|
|
32
|
+
# MCP server instance
|
|
33
|
+
# ---------------------------------------------------------------------------
|
|
34
|
+
|
|
35
|
+
mcp = FastMCP(
|
|
36
|
+
"DiffMem",
|
|
37
|
+
instructions=(
|
|
38
|
+
"DiffMem memory management server. Use these tools to interact with "
|
|
39
|
+
"DiffMem memory spaces — ingest content, retrieve context, manage files, "
|
|
40
|
+
"and inspect project configuration. All operations are scoped to the "
|
|
41
|
+
"authenticated project; you do not need to provide a project_id."
|
|
42
|
+
),
|
|
43
|
+
# ADR-039: streamable HTTP is stateless (no Mcp-Session-Id, no per-session
|
|
44
|
+
# server-side state) so requests survive Cloud Run instance churn; plain
|
|
45
|
+
# JSON responses keep the traffic proxy-friendly (no SSE-over-POST body).
|
|
46
|
+
stateless_http=True,
|
|
47
|
+
json_response=True,
|
|
48
|
+
# Match the SSE app's security posture: no DNS-rebinding Host check. The
|
|
49
|
+
# streamable endpoint is a public, GLB-fronted, Bearer-authed API — not a
|
|
50
|
+
# browser-reachable localhost server — and the SDK's localhost-only Host
|
|
51
|
+
# allowlist would reject api.diffmem.com outright.
|
|
52
|
+
transport_security=TransportSecuritySettings(enable_dns_rebinding_protection=False),
|
|
53
|
+
# Inner path under the RP mount /p/{project_id} → public URL is the clean
|
|
54
|
+
# https://api.diffmem.com/p/{project_id}/mcp (asgi.py reuses this route).
|
|
55
|
+
streamable_http_path="/mcp",
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
# ---------------------------------------------------------------------------
|
|
60
|
+
# Entry point
|
|
61
|
+
# ---------------------------------------------------------------------------
|
|
62
|
+
|
|
63
|
+
def main():
|
|
64
|
+
"""Run the MCP server with stdio transport."""
|
|
65
|
+
# Configure logging to stderr (stdout is reserved for MCP protocol)
|
|
66
|
+
logging.basicConfig(
|
|
67
|
+
level=logging.INFO,
|
|
68
|
+
format="%(asctime)s %(name)s %(levelname)s %(message)s",
|
|
69
|
+
stream=sys.stderr,
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
# Import and register tools
|
|
73
|
+
from diffmem_mcp.tools import register_tools
|
|
74
|
+
|
|
75
|
+
register_tools(mcp)
|
|
76
|
+
|
|
77
|
+
# Run with stdio transport (default)
|
|
78
|
+
mcp.run()
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def main_sse(host: str = "0.0.0.0", port: int = 3001) -> None:
|
|
82
|
+
"""Run the MCP server with HTTP transports (SSE + streamable) via uvicorn.
|
|
83
|
+
|
|
84
|
+
Args:
|
|
85
|
+
host: Bind address (default ``0.0.0.0``).
|
|
86
|
+
port: Bind port (default ``3001``).
|
|
87
|
+
"""
|
|
88
|
+
import uvicorn
|
|
89
|
+
|
|
90
|
+
# Configure logging (stdout is available for SSE transport)
|
|
91
|
+
logging.basicConfig(
|
|
92
|
+
level=logging.INFO,
|
|
93
|
+
format="%(asctime)s %(name)s %(levelname)s %(message)s",
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
from diffmem_mcp.asgi import create_mcp_asgi_app
|
|
97
|
+
|
|
98
|
+
mcp_app = create_mcp_asgi_app()
|
|
99
|
+
|
|
100
|
+
# Standalone layout: run the sub-app at the ROOT — its inner routes already
|
|
101
|
+
# are /mcp (streamable), /mcp/sse + /mcp/messages (legacy SSE), /health.
|
|
102
|
+
# The RP co-location mount (/p/{project_id}) supplies the public prefix in
|
|
103
|
+
# every real environment; standalone adds none (ADR-030/ADR-039).
|
|
104
|
+
logger.info(
|
|
105
|
+
"Starting MCP server with HTTP transports (streamable at /mcp, legacy SSE at /mcp/sse) on %s:%s",
|
|
106
|
+
host,
|
|
107
|
+
port,
|
|
108
|
+
)
|
|
109
|
+
uvicorn.run(mcp_app, host=host, port=port)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
# ---------------------------------------------------------------------------
|
|
113
|
+
# CLI
|
|
114
|
+
# ---------------------------------------------------------------------------
|
|
115
|
+
|
|
116
|
+
def cli(argv: list[str] | None = None) -> None:
|
|
117
|
+
"""Console-script entry point (``diffmem-mcp-server``).
|
|
118
|
+
|
|
119
|
+
Parses args so ``--help`` works from an installed wheel without starting
|
|
120
|
+
the server, then dispatches to the stdio or HTTP runner.
|
|
121
|
+
"""
|
|
122
|
+
parser = argparse.ArgumentParser(
|
|
123
|
+
prog="diffmem-mcp-server",
|
|
124
|
+
description="DiffMem MCP Server",
|
|
125
|
+
)
|
|
126
|
+
parser.add_argument(
|
|
127
|
+
"--sse",
|
|
128
|
+
action="store_true",
|
|
129
|
+
help="Run with HTTP transports: streamable HTTP + legacy SSE (default: stdio)",
|
|
130
|
+
)
|
|
131
|
+
parser.add_argument(
|
|
132
|
+
"--host",
|
|
133
|
+
default="0.0.0.0",
|
|
134
|
+
help="Host to bind HTTP transports (default: 0.0.0.0)",
|
|
135
|
+
)
|
|
136
|
+
parser.add_argument(
|
|
137
|
+
"--port",
|
|
138
|
+
type=int,
|
|
139
|
+
default=3001,
|
|
140
|
+
help="Port to bind HTTP transports (default: 3001)",
|
|
141
|
+
)
|
|
142
|
+
args = parser.parse_args(argv)
|
|
143
|
+
|
|
144
|
+
if args.sse:
|
|
145
|
+
main_sse(host=args.host, port=args.port)
|
|
146
|
+
else:
|
|
147
|
+
main()
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
if __name__ == "__main__":
|
|
151
|
+
cli()
|
diffmem_mcp/settings.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
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()
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""MCP tool registration for DiffMem."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from mcp.server.fastmcp import FastMCP
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def register_tools(mcp_server: FastMCP) -> None:
|
|
9
|
+
"""Register all DiffMem tools on the MCP server instance.
|
|
10
|
+
|
|
11
|
+
Called once at server startup. Each tool module registers its own tools
|
|
12
|
+
via this function.
|
|
13
|
+
"""
|
|
14
|
+
from diffmem_mcp.tools.spaces import register_space_tools
|
|
15
|
+
from diffmem_mcp.tools.files import register_file_tools
|
|
16
|
+
from diffmem_mcp.tools.memory import register_memory_tools
|
|
17
|
+
from diffmem_mcp.tools.project import register_project_tools
|
|
18
|
+
|
|
19
|
+
register_space_tools(mcp_server)
|
|
20
|
+
register_file_tools(mcp_server)
|
|
21
|
+
register_memory_tools(mcp_server)
|
|
22
|
+
register_project_tools(mcp_server)
|