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
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"""File-related MCP tools: list_files, read_file."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import logging
|
|
7
|
+
import time
|
|
8
|
+
|
|
9
|
+
from mcp.server.fastmcp import FastMCP
|
|
10
|
+
|
|
11
|
+
from diffmem_mcp.api_client import RegionalPlaneClient
|
|
12
|
+
from diffmem_mcp.scopes import SCOPE_FILES_READ, enforce_tool_access
|
|
13
|
+
from diffmem_mcp.security import AuditLogger, SecurityError
|
|
14
|
+
from diffmem_mcp.server import get_context
|
|
15
|
+
from diffmem_mcp.router import resolve_url
|
|
16
|
+
from diffmem_mcp.settings import get_settings
|
|
17
|
+
|
|
18
|
+
logger = logging.getLogger(__name__)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def register_file_tools(mcp_server: FastMCP) -> None:
|
|
22
|
+
"""Register file tools on the MCP server."""
|
|
23
|
+
|
|
24
|
+
@mcp_server.tool()
|
|
25
|
+
async def list_files(space_id: str) -> str:
|
|
26
|
+
"""List files in a memory space.
|
|
27
|
+
|
|
28
|
+
Args:
|
|
29
|
+
space_id: The space identifier (e.g. "default")
|
|
30
|
+
|
|
31
|
+
Returns a list of file paths with sizes and last-committed timestamps.
|
|
32
|
+
"""
|
|
33
|
+
ctx = get_context()
|
|
34
|
+
t0 = time.monotonic()
|
|
35
|
+
try:
|
|
36
|
+
auth = await ctx.get_auth()
|
|
37
|
+
project_id = auth.project_id
|
|
38
|
+
|
|
39
|
+
# Check pipeline (spec #77 §7.3): scope → space-allowlist → quota → handler.
|
|
40
|
+
# Space existence/quota are plane-enforced; denials pass through
|
|
41
|
+
# to tool output (ADR-038).
|
|
42
|
+
enforce_tool_access(auth, SCOPE_FILES_READ, [space_id])
|
|
43
|
+
|
|
44
|
+
# 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())
|
|
48
|
+
client = RegionalPlaneClient(base_url, auth.raw_key)
|
|
49
|
+
|
|
50
|
+
# Stale MCP→RP path fixed per spec §7.5: .../files → .../memory/files
|
|
51
|
+
result = await client.get(
|
|
52
|
+
f"/p/{project_id}/v1/spaces/{space_id}/memory/files"
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
duration_ms = (time.monotonic() - t0) * 1000
|
|
56
|
+
AuditLogger.log_invocation(
|
|
57
|
+
tool_name="list_files",
|
|
58
|
+
key_id=auth.key_id,
|
|
59
|
+
project_id=project_id,
|
|
60
|
+
space_id=space_id,
|
|
61
|
+
success=True,
|
|
62
|
+
duration_ms=duration_ms,
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
return json.dumps({
|
|
66
|
+
"status": "ok",
|
|
67
|
+
"space_id": space_id,
|
|
68
|
+
"files": result.get("files", []),
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
except SecurityError as e:
|
|
72
|
+
AuditLogger.log_invocation(
|
|
73
|
+
tool_name="list_files",
|
|
74
|
+
key_id=getattr(ctx.auth, "key_id", "unknown"),
|
|
75
|
+
project_id=getattr(ctx.auth, "project_id", "unknown"),
|
|
76
|
+
space_id=space_id,
|
|
77
|
+
success=False,
|
|
78
|
+
error_code=e.code,
|
|
79
|
+
)
|
|
80
|
+
return json.dumps({"status": "error", "code": e.code, "message": e.message})
|
|
81
|
+
except Exception as e:
|
|
82
|
+
logger.exception("LIST_FILES_ERROR")
|
|
83
|
+
return json.dumps({"status": "error", "code": "internal_error", "message": str(e)})
|
|
84
|
+
|
|
85
|
+
@mcp_server.tool()
|
|
86
|
+
async def read_file(space_id: str, path: str) -> str:
|
|
87
|
+
"""Read a specific file from a memory space.
|
|
88
|
+
|
|
89
|
+
Args:
|
|
90
|
+
space_id: The space identifier (e.g. "default")
|
|
91
|
+
path: File path relative to the space root (e.g. "memories/people/alice.md")
|
|
92
|
+
|
|
93
|
+
Returns the file content as text.
|
|
94
|
+
"""
|
|
95
|
+
ctx = get_context()
|
|
96
|
+
t0 = time.monotonic()
|
|
97
|
+
try:
|
|
98
|
+
auth = await ctx.get_auth()
|
|
99
|
+
project_id = auth.project_id
|
|
100
|
+
|
|
101
|
+
# Check pipeline (spec #77 §7.3): scope → space-allowlist → quota → handler.
|
|
102
|
+
# Space existence/quota are plane-enforced; denials pass through
|
|
103
|
+
# to tool output (ADR-038).
|
|
104
|
+
enforce_tool_access(auth, SCOPE_FILES_READ, [space_id])
|
|
105
|
+
|
|
106
|
+
# 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())
|
|
110
|
+
client = RegionalPlaneClient(base_url, auth.raw_key)
|
|
111
|
+
|
|
112
|
+
result = await client.get(
|
|
113
|
+
f"/p/{project_id}/v1/spaces/{space_id}/memory/files/{path}"
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
duration_ms = (time.monotonic() - t0) * 1000
|
|
117
|
+
AuditLogger.log_invocation(
|
|
118
|
+
tool_name="read_file",
|
|
119
|
+
key_id=auth.key_id,
|
|
120
|
+
project_id=project_id,
|
|
121
|
+
space_id=space_id,
|
|
122
|
+
success=True,
|
|
123
|
+
duration_ms=duration_ms,
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
return json.dumps({
|
|
127
|
+
"status": "ok",
|
|
128
|
+
"space_id": space_id,
|
|
129
|
+
"path": path,
|
|
130
|
+
"content": result.get("content", ""),
|
|
131
|
+
"size_bytes": result.get("size_bytes", 0),
|
|
132
|
+
"last_committed_at": result.get("last_committed_at", ""),
|
|
133
|
+
})
|
|
134
|
+
|
|
135
|
+
except SecurityError as e:
|
|
136
|
+
AuditLogger.log_invocation(
|
|
137
|
+
tool_name="read_file",
|
|
138
|
+
key_id=getattr(ctx.auth, "key_id", "unknown"),
|
|
139
|
+
project_id=getattr(ctx.auth, "project_id", "unknown"),
|
|
140
|
+
space_id=space_id,
|
|
141
|
+
success=False,
|
|
142
|
+
error_code=e.code,
|
|
143
|
+
)
|
|
144
|
+
return json.dumps({"status": "error", "code": e.code, "message": e.message})
|
|
145
|
+
except Exception as e:
|
|
146
|
+
logger.exception("READ_FILE_ERROR")
|
|
147
|
+
return json.dumps({"status": "error", "code": "internal_error", "message": str(e)})
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
"""Memory operation MCP tools: ingest_memory, retrieve_context."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import logging
|
|
7
|
+
import time
|
|
8
|
+
|
|
9
|
+
import httpx
|
|
10
|
+
from mcp.server.fastmcp import FastMCP
|
|
11
|
+
|
|
12
|
+
from diffmem_mcp.api_client import (
|
|
13
|
+
GENERIC_ERROR_MESSAGE,
|
|
14
|
+
RegionalPlaneClient,
|
|
15
|
+
map_upstream_http_error,
|
|
16
|
+
)
|
|
17
|
+
from diffmem_mcp.router import resolve_url
|
|
18
|
+
from diffmem_mcp.scopes import SCOPE_MEMORY_READ, SCOPE_MEMORY_WRITE, enforce_tool_access
|
|
19
|
+
from diffmem_mcp.security import AuditLogger, SecurityError
|
|
20
|
+
from diffmem_mcp.server import get_context
|
|
21
|
+
from diffmem_mcp.settings import get_settings
|
|
22
|
+
|
|
23
|
+
logger = logging.getLogger(__name__)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def register_memory_tools(mcp_server: FastMCP) -> None:
|
|
27
|
+
"""Register memory tools on the MCP server."""
|
|
28
|
+
|
|
29
|
+
@mcp_server.tool()
|
|
30
|
+
async def ingest_memory(content: str, space_id: str = "") -> str:
|
|
31
|
+
"""Ingest content into a DiffMem memory space.
|
|
32
|
+
|
|
33
|
+
Processes content through the memory pipeline — extracts entities,
|
|
34
|
+
creates/updates memory files, and builds semantic indexes.
|
|
35
|
+
|
|
36
|
+
Args:
|
|
37
|
+
content: The content to ingest (conversation transcript, notes, etc.)
|
|
38
|
+
space_id: Optional. Target space ID. If omitted, the system uses
|
|
39
|
+
intelligent routing to select the best public space based
|
|
40
|
+
on content analysis.
|
|
41
|
+
|
|
42
|
+
Returns processing result with session ID, resolved space, and any routing metadata.
|
|
43
|
+
"""
|
|
44
|
+
ctx = get_context()
|
|
45
|
+
t0 = time.monotonic()
|
|
46
|
+
try:
|
|
47
|
+
auth = await ctx.get_auth()
|
|
48
|
+
project_id = auth.project_id
|
|
49
|
+
|
|
50
|
+
# Check pipeline (spec #77 §7.3): scope → space-allowlist → quota → handler.
|
|
51
|
+
# Smart routing (no space_id) is allowlist-enforced at the regional
|
|
52
|
+
# plane's candidate pre-filter (spec #80 site 2).
|
|
53
|
+
# Quota and space existence are plane-enforced; denials pass
|
|
54
|
+
# through to tool output (ADR-038).
|
|
55
|
+
enforce_tool_access(auth, SCOPE_MEMORY_WRITE, [space_id] if space_id else None)
|
|
56
|
+
|
|
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())
|
|
61
|
+
client = RegionalPlaneClient(base_url, auth.raw_key)
|
|
62
|
+
|
|
63
|
+
# Generate session ID
|
|
64
|
+
import uuid
|
|
65
|
+
session_id = f"mcp-{uuid.uuid4().hex[:12]}"
|
|
66
|
+
|
|
67
|
+
# Call regional-plane
|
|
68
|
+
if space_id:
|
|
69
|
+
# Targeted ingest to specific space
|
|
70
|
+
result = await client.post(
|
|
71
|
+
f"/p/{project_id}/v1/spaces/{space_id}/memory/process",
|
|
72
|
+
json_body={
|
|
73
|
+
"memory_input": content,
|
|
74
|
+
"session_id": session_id,
|
|
75
|
+
},
|
|
76
|
+
timeout=120.0, # Memory processing can take a while
|
|
77
|
+
)
|
|
78
|
+
else:
|
|
79
|
+
# Smart routing — regional-plane selects the best public space
|
|
80
|
+
result = await client.post(
|
|
81
|
+
f"/p/{project_id}/v1/memory/process",
|
|
82
|
+
json_body={
|
|
83
|
+
"memory_input": content,
|
|
84
|
+
"session_id": session_id,
|
|
85
|
+
},
|
|
86
|
+
timeout=120.0,
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
duration_ms = (time.monotonic() - t0) * 1000
|
|
90
|
+
AuditLogger.log_invocation(
|
|
91
|
+
tool_name="ingest_memory",
|
|
92
|
+
key_id=auth.key_id,
|
|
93
|
+
project_id=project_id,
|
|
94
|
+
space_id=space_id or result.get("space_id"),
|
|
95
|
+
success=True,
|
|
96
|
+
duration_ms=duration_ms,
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
return json.dumps({
|
|
100
|
+
"status": "ok",
|
|
101
|
+
"session_id": session_id,
|
|
102
|
+
"space_id": result.get("space_id", space_id),
|
|
103
|
+
"routing": result.get("routing"),
|
|
104
|
+
"result": result.get("result"),
|
|
105
|
+
})
|
|
106
|
+
|
|
107
|
+
except SecurityError as e:
|
|
108
|
+
AuditLogger.log_invocation(
|
|
109
|
+
tool_name="ingest_memory",
|
|
110
|
+
key_id=getattr(ctx.auth, "key_id", "unknown"),
|
|
111
|
+
project_id=getattr(ctx.auth, "project_id", "unknown"),
|
|
112
|
+
space_id=space_id,
|
|
113
|
+
success=False,
|
|
114
|
+
error_code=e.code,
|
|
115
|
+
)
|
|
116
|
+
return json.dumps({"status": "error", "code": e.code, "message": e.message})
|
|
117
|
+
except httpx.HTTPStatusError as e:
|
|
118
|
+
# Issue #128: re-emit the regional plane's machine code + clean
|
|
119
|
+
# detail verbatim; never echo str(e) (full response body leak).
|
|
120
|
+
# auth is always bound by the time an HTTP error can occur.
|
|
121
|
+
mapped = map_upstream_http_error(e)
|
|
122
|
+
AuditLogger.log_invocation(
|
|
123
|
+
tool_name="ingest_memory",
|
|
124
|
+
key_id=auth.key_id,
|
|
125
|
+
project_id=auth.project_id,
|
|
126
|
+
space_id=space_id,
|
|
127
|
+
success=False,
|
|
128
|
+
error_code=mapped["code"],
|
|
129
|
+
)
|
|
130
|
+
return json.dumps(mapped)
|
|
131
|
+
except Exception:
|
|
132
|
+
# Leak-free catch-all (issue #128): a generic message only — the
|
|
133
|
+
# exception text may carry internal surface and stays server-side.
|
|
134
|
+
logger.exception("INGEST_MEMORY_ERROR")
|
|
135
|
+
return json.dumps({
|
|
136
|
+
"status": "error",
|
|
137
|
+
"code": "internal_error",
|
|
138
|
+
"message": GENERIC_ERROR_MESSAGE,
|
|
139
|
+
})
|
|
140
|
+
|
|
141
|
+
@mcp_server.tool()
|
|
142
|
+
async def retrieve_context(
|
|
143
|
+
query: str,
|
|
144
|
+
space_id: str = "",
|
|
145
|
+
spaces: str = "",
|
|
146
|
+
policy: str = "",
|
|
147
|
+
) -> str:
|
|
148
|
+
"""Retrieve relevant context from memory spaces.
|
|
149
|
+
|
|
150
|
+
Uses agent-based retrieval to find and synthesize the most relevant
|
|
151
|
+
memory content for a given query.
|
|
152
|
+
|
|
153
|
+
Args:
|
|
154
|
+
query: The conversation or query to retrieve context for
|
|
155
|
+
space_id: Optional. Search within a specific space only.
|
|
156
|
+
spaces: Optional. Comma-separated list of space IDs to search.
|
|
157
|
+
policy: Optional. Retrieval policy (e.g. "recent", "comprehensive").
|
|
158
|
+
|
|
159
|
+
Returns synthesized context with source references and retrieval metadata.
|
|
160
|
+
"""
|
|
161
|
+
ctx = get_context()
|
|
162
|
+
t0 = time.monotonic()
|
|
163
|
+
try:
|
|
164
|
+
auth = await ctx.get_auth()
|
|
165
|
+
project_id = auth.project_id
|
|
166
|
+
|
|
167
|
+
# Parse the comma-string contract once
|
|
168
|
+
requested_spaces = [s.strip() for s in spaces.split(",") if s.strip()] if spaces else []
|
|
169
|
+
target_spaces = ([space_id] if space_id else []) + requested_spaces
|
|
170
|
+
|
|
171
|
+
# Check pipeline (spec #77 §7.3): scope → space-allowlist → quota → handler.
|
|
172
|
+
# Policy-based retrieval (no explicit spaces) is allowlist-enforced
|
|
173
|
+
# at the regional plane (spec #80 site 2).
|
|
174
|
+
enforce_tool_access(auth, SCOPE_MEMORY_READ, target_spaces or None)
|
|
175
|
+
|
|
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())
|
|
180
|
+
client = RegionalPlaneClient(base_url, auth.raw_key)
|
|
181
|
+
|
|
182
|
+
# Build request body
|
|
183
|
+
body = {
|
|
184
|
+
"conversation": [{"role": "user", "content": query}],
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
if space_id:
|
|
188
|
+
body["spaces"] = [{"project_id": project_id, "space_id": space_id}]
|
|
189
|
+
elif requested_spaces:
|
|
190
|
+
body["spaces"] = [
|
|
191
|
+
{"project_id": project_id, "space_id": sid} for sid in requested_spaces
|
|
192
|
+
]
|
|
193
|
+
elif policy:
|
|
194
|
+
body["policy"] = policy
|
|
195
|
+
|
|
196
|
+
# Stale MCP→RP path fixed per spec §7.5: /v1/context → /v1/memory/context
|
|
197
|
+
result = await client.post(
|
|
198
|
+
f"/p/{project_id}/v1/memory/context",
|
|
199
|
+
json_body=body,
|
|
200
|
+
timeout=120.0,
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
duration_ms = (time.monotonic() - t0) * 1000
|
|
204
|
+
AuditLogger.log_invocation(
|
|
205
|
+
tool_name="retrieve_context",
|
|
206
|
+
key_id=auth.key_id,
|
|
207
|
+
project_id=project_id,
|
|
208
|
+
space_id=space_id,
|
|
209
|
+
success=True,
|
|
210
|
+
duration_ms=duration_ms,
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
return json.dumps({
|
|
214
|
+
"status": "ok",
|
|
215
|
+
"context": result.get("context"),
|
|
216
|
+
"session_metadata": result.get("session_metadata"),
|
|
217
|
+
})
|
|
218
|
+
|
|
219
|
+
except SecurityError as e:
|
|
220
|
+
AuditLogger.log_invocation(
|
|
221
|
+
tool_name="retrieve_context",
|
|
222
|
+
key_id=getattr(ctx.auth, "key_id", "unknown"),
|
|
223
|
+
project_id=getattr(ctx.auth, "project_id", "unknown"),
|
|
224
|
+
space_id=space_id,
|
|
225
|
+
success=False,
|
|
226
|
+
error_code=e.code,
|
|
227
|
+
)
|
|
228
|
+
return json.dumps({"status": "error", "code": e.code, "message": e.message})
|
|
229
|
+
except httpx.HTTPStatusError as e:
|
|
230
|
+
# Issue #128: identical error-mapping path to ingest_memory.
|
|
231
|
+
mapped = map_upstream_http_error(e)
|
|
232
|
+
AuditLogger.log_invocation(
|
|
233
|
+
tool_name="retrieve_context",
|
|
234
|
+
key_id=auth.key_id,
|
|
235
|
+
project_id=auth.project_id,
|
|
236
|
+
space_id=space_id,
|
|
237
|
+
success=False,
|
|
238
|
+
error_code=mapped["code"],
|
|
239
|
+
)
|
|
240
|
+
return json.dumps(mapped)
|
|
241
|
+
except Exception:
|
|
242
|
+
# Leak-free catch-all (issue #128): identical to ingest_memory.
|
|
243
|
+
logger.exception("RETRIEVE_CONTEXT_ERROR")
|
|
244
|
+
return json.dumps({
|
|
245
|
+
"status": "error",
|
|
246
|
+
"code": "internal_error",
|
|
247
|
+
"message": GENERIC_ERROR_MESSAGE,
|
|
248
|
+
})
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""Project-related MCP tools: get_project_status."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import logging
|
|
7
|
+
import time
|
|
8
|
+
|
|
9
|
+
import httpx
|
|
10
|
+
from mcp.server.fastmcp import FastMCP
|
|
11
|
+
|
|
12
|
+
from diffmem_mcp.api_client import RegionalPlaneClient, map_upstream_http_error
|
|
13
|
+
from diffmem_mcp.router import resolve_url
|
|
14
|
+
from diffmem_mcp.scopes import SCOPE_INTROSPECT_READ, enforce_tool_access
|
|
15
|
+
from diffmem_mcp.security import AuditLogger, SecurityError
|
|
16
|
+
from diffmem_mcp.server import get_context
|
|
17
|
+
from diffmem_mcp.settings import get_settings
|
|
18
|
+
|
|
19
|
+
logger = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def register_project_tools(mcp_server: FastMCP) -> None:
|
|
23
|
+
"""Register project tools on the MCP server."""
|
|
24
|
+
|
|
25
|
+
@mcp_server.tool()
|
|
26
|
+
async def get_project_status() -> str:
|
|
27
|
+
"""Get project configuration and status.
|
|
28
|
+
|
|
29
|
+
Returns plan details, quota limits, current usage, and space count.
|
|
30
|
+
No parameters needed — project scope is derived from your API key.
|
|
31
|
+
"""
|
|
32
|
+
ctx = get_context()
|
|
33
|
+
t0 = time.monotonic()
|
|
34
|
+
try:
|
|
35
|
+
auth = await ctx.get_auth()
|
|
36
|
+
project_id = auth.project_id
|
|
37
|
+
|
|
38
|
+
# Check pipeline (spec #77 §7.3): scope → space-allowlist → quota → handler
|
|
39
|
+
enforce_tool_access(auth, SCOPE_INTROSPECT_READ)
|
|
40
|
+
|
|
41
|
+
# 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())
|
|
45
|
+
client = RegionalPlaneClient(base_url, auth.raw_key)
|
|
46
|
+
status = await client.get(f"/p/{project_id}/v1/project/status")
|
|
47
|
+
|
|
48
|
+
duration_ms = (time.monotonic() - t0) * 1000
|
|
49
|
+
AuditLogger.log_invocation(
|
|
50
|
+
tool_name="get_project_status",
|
|
51
|
+
key_id=auth.key_id,
|
|
52
|
+
project_id=project_id,
|
|
53
|
+
success=True,
|
|
54
|
+
duration_ms=duration_ms,
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
return json.dumps({"status": "ok", **status})
|
|
58
|
+
|
|
59
|
+
except SecurityError as e:
|
|
60
|
+
AuditLogger.log_invocation(
|
|
61
|
+
tool_name="get_project_status",
|
|
62
|
+
key_id=getattr(ctx.auth, "key_id", "unknown"),
|
|
63
|
+
project_id=getattr(ctx.auth, "project_id", "unknown"),
|
|
64
|
+
success=False,
|
|
65
|
+
error_code=e.code,
|
|
66
|
+
)
|
|
67
|
+
return json.dumps({"status": "error", "code": e.code, "message": e.message})
|
|
68
|
+
except httpx.HTTPStatusError as e:
|
|
69
|
+
mapped = map_upstream_http_error(e)
|
|
70
|
+
AuditLogger.log_invocation(
|
|
71
|
+
tool_name="get_project_status",
|
|
72
|
+
key_id=getattr(ctx.auth, "key_id", "unknown"),
|
|
73
|
+
project_id=getattr(ctx.auth, "project_id", "unknown"),
|
|
74
|
+
success=False,
|
|
75
|
+
error_code=mapped["code"],
|
|
76
|
+
)
|
|
77
|
+
return json.dumps(mapped)
|
|
78
|
+
except Exception as e:
|
|
79
|
+
logger.exception("GET_PROJECT_STATUS_ERROR")
|
|
80
|
+
return json.dumps({"status": "error", "code": "internal_error", "message": str(e)})
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
"""Space-related MCP tools: list_spaces, get_space_info."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import logging
|
|
7
|
+
import time
|
|
8
|
+
|
|
9
|
+
import httpx
|
|
10
|
+
from mcp.server.fastmcp import FastMCP
|
|
11
|
+
|
|
12
|
+
from diffmem_mcp.api_client import RegionalPlaneClient, map_upstream_http_error
|
|
13
|
+
from diffmem_mcp.router import resolve_url
|
|
14
|
+
from diffmem_mcp.scopes import SCOPE_INTROSPECT_READ, enforce_tool_access
|
|
15
|
+
from diffmem_mcp.security import (
|
|
16
|
+
AuditLogger,
|
|
17
|
+
ensure_space_allowed,
|
|
18
|
+
filter_spaces_to_allowlist,
|
|
19
|
+
)
|
|
20
|
+
from diffmem_mcp.server import get_context
|
|
21
|
+
from diffmem_mcp.settings import get_settings
|
|
22
|
+
|
|
23
|
+
logger = logging.getLogger(__name__)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def register_space_tools(mcp_server: FastMCP) -> None:
|
|
27
|
+
"""Register space tools on the MCP server."""
|
|
28
|
+
|
|
29
|
+
async def _fetch_spaces(auth) -> list[dict]:
|
|
30
|
+
"""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."""
|
|
33
|
+
project_id = auth.project_id
|
|
34
|
+
base_url = resolve_url(project_id, get_settings().get_api_urls())
|
|
35
|
+
client = RegionalPlaneClient(base_url, auth.raw_key)
|
|
36
|
+
body = await client.get(f"/p/{project_id}/v1/spaces")
|
|
37
|
+
return body.get("spaces", [])
|
|
38
|
+
|
|
39
|
+
@mcp_server.tool()
|
|
40
|
+
async def list_spaces() -> str:
|
|
41
|
+
"""List all memory spaces in your project.
|
|
42
|
+
|
|
43
|
+
Returns space IDs, types (public/private), ontology, and initialization status.
|
|
44
|
+
No parameters needed — project scope is derived from your API key.
|
|
45
|
+
"""
|
|
46
|
+
ctx = get_context()
|
|
47
|
+
t0 = time.monotonic()
|
|
48
|
+
try:
|
|
49
|
+
auth = await ctx.get_auth()
|
|
50
|
+
project_id = auth.project_id
|
|
51
|
+
|
|
52
|
+
# Check pipeline (spec #77 §7.3): scope → space-allowlist → quota → handler
|
|
53
|
+
enforce_tool_access(auth, SCOPE_INTROSPECT_READ)
|
|
54
|
+
|
|
55
|
+
spaces = await _fetch_spaces(auth)
|
|
56
|
+
|
|
57
|
+
# Space-allowlist introspection filter (spec #77 §5, #80 site 3):
|
|
58
|
+
# excluded spaces are INVISIBLE — absent from results, never 403.
|
|
59
|
+
spaces = filter_spaces_to_allowlist(auth, spaces)
|
|
60
|
+
|
|
61
|
+
duration_ms = (time.monotonic() - t0) * 1000
|
|
62
|
+
AuditLogger.log_invocation(
|
|
63
|
+
tool_name="list_spaces",
|
|
64
|
+
key_id=auth.key_id,
|
|
65
|
+
project_id=project_id,
|
|
66
|
+
success=True,
|
|
67
|
+
duration_ms=duration_ms,
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
return json.dumps({
|
|
71
|
+
"status": "ok",
|
|
72
|
+
"project_id": project_id,
|
|
73
|
+
"space_count": len(spaces),
|
|
74
|
+
"spaces": spaces,
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
except SecurityError as e:
|
|
78
|
+
AuditLogger.log_invocation(
|
|
79
|
+
tool_name="list_spaces",
|
|
80
|
+
key_id=getattr(ctx.auth, "key_id", "unknown"),
|
|
81
|
+
project_id=getattr(ctx.auth, "project_id", "unknown"),
|
|
82
|
+
success=False,
|
|
83
|
+
error_code=e.code,
|
|
84
|
+
)
|
|
85
|
+
return json.dumps({"status": "error", "code": e.code, "message": e.message})
|
|
86
|
+
except httpx.HTTPStatusError as e:
|
|
87
|
+
mapped = map_upstream_http_error(e)
|
|
88
|
+
AuditLogger.log_invocation(
|
|
89
|
+
tool_name="list_spaces",
|
|
90
|
+
key_id=getattr(ctx.auth, "key_id", "unknown"),
|
|
91
|
+
project_id=getattr(ctx.auth, "project_id", "unknown"),
|
|
92
|
+
success=False,
|
|
93
|
+
error_code=mapped["code"],
|
|
94
|
+
)
|
|
95
|
+
return json.dumps(mapped)
|
|
96
|
+
except Exception as e:
|
|
97
|
+
logger.exception("LIST_SPACES_ERROR")
|
|
98
|
+
return json.dumps({"status": "error", "code": "internal_error", "message": str(e)})
|
|
99
|
+
|
|
100
|
+
@mcp_server.tool()
|
|
101
|
+
async def get_space_info(space_id: str) -> str:
|
|
102
|
+
"""Get detailed metadata for a specific memory space.
|
|
103
|
+
|
|
104
|
+
Args:
|
|
105
|
+
space_id: The space identifier (e.g. "default", "shared-kb")
|
|
106
|
+
|
|
107
|
+
Returns space metadata including ontology, description, file count, and storage usage.
|
|
108
|
+
"""
|
|
109
|
+
ctx = get_context()
|
|
110
|
+
t0 = time.monotonic()
|
|
111
|
+
try:
|
|
112
|
+
auth = await ctx.get_auth()
|
|
113
|
+
project_id = auth.project_id
|
|
114
|
+
|
|
115
|
+
# Check pipeline (spec #77 §7.3): scope → space-allowlist → quota → handler
|
|
116
|
+
enforce_tool_access(auth, SCOPE_INTROSPECT_READ)
|
|
117
|
+
|
|
118
|
+
# Allowlist check FIRST (spec #80 site 3): an excluded space must
|
|
119
|
+
# be indistinguishable from a nonexistent one — space_not_found,
|
|
120
|
+
# never access_denied/403.
|
|
121
|
+
ensure_space_allowed(auth, space_id)
|
|
122
|
+
|
|
123
|
+
# Space metadata arrives via the same API list the plane serves;
|
|
124
|
+
# a missing space is a lookup miss, not a plane error.
|
|
125
|
+
spaces = await _fetch_spaces(auth)
|
|
126
|
+
data = next((s for s in spaces if s.get("space_id") == space_id), None)
|
|
127
|
+
if data is None:
|
|
128
|
+
AuditLogger.log_invocation(
|
|
129
|
+
tool_name="get_space_info",
|
|
130
|
+
key_id=auth.key_id,
|
|
131
|
+
project_id=project_id,
|
|
132
|
+
space_id=space_id,
|
|
133
|
+
success=False,
|
|
134
|
+
error_code="space_not_found",
|
|
135
|
+
)
|
|
136
|
+
return json.dumps({
|
|
137
|
+
"status": "error",
|
|
138
|
+
"code": "space_not_found",
|
|
139
|
+
"message": f"Space '{space_id}' not found in project.",
|
|
140
|
+
})
|
|
141
|
+
|
|
142
|
+
duration_ms = (time.monotonic() - t0) * 1000
|
|
143
|
+
AuditLogger.log_invocation(
|
|
144
|
+
tool_name="get_space_info",
|
|
145
|
+
key_id=auth.key_id,
|
|
146
|
+
project_id=project_id,
|
|
147
|
+
space_id=space_id,
|
|
148
|
+
success=True,
|
|
149
|
+
duration_ms=duration_ms,
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
return json.dumps({
|
|
153
|
+
"status": "ok",
|
|
154
|
+
"space_id": space_id,
|
|
155
|
+
"space_type": data.get("space_type") or "public",
|
|
156
|
+
"ontology": data.get("ontology") or "corporate",
|
|
157
|
+
"initialized": bool(data.get("initialized")),
|
|
158
|
+
"description": data.get("description") or "",
|
|
159
|
+
"storage_bytes": data.get("storage_bytes") or 0,
|
|
160
|
+
"repository_id": data.get("repository_id") or "",
|
|
161
|
+
"initialized_at": data.get("initialized_at") or "",
|
|
162
|
+
})
|
|
163
|
+
|
|
164
|
+
except SecurityError as e:
|
|
165
|
+
AuditLogger.log_invocation(
|
|
166
|
+
tool_name="get_space_info",
|
|
167
|
+
key_id=getattr(ctx.auth, "key_id", "unknown"),
|
|
168
|
+
project_id=getattr(ctx.auth, "project_id", "unknown"),
|
|
169
|
+
space_id=space_id,
|
|
170
|
+
success=False,
|
|
171
|
+
error_code=e.code,
|
|
172
|
+
)
|
|
173
|
+
return json.dumps({"status": "error", "code": e.code, "message": e.message})
|
|
174
|
+
except httpx.HTTPStatusError as e:
|
|
175
|
+
mapped = map_upstream_http_error(e)
|
|
176
|
+
AuditLogger.log_invocation(
|
|
177
|
+
tool_name="get_space_info",
|
|
178
|
+
key_id=getattr(ctx.auth, "key_id", "unknown"),
|
|
179
|
+
project_id=getattr(ctx.auth, "project_id", "unknown"),
|
|
180
|
+
space_id=space_id,
|
|
181
|
+
success=False,
|
|
182
|
+
error_code=mapped["code"],
|
|
183
|
+
)
|
|
184
|
+
return json.dumps(mapped)
|
|
185
|
+
except Exception as e:
|
|
186
|
+
logger.exception("GET_SPACE_INFO_ERROR")
|
|
187
|
+
return json.dumps({"status": "error", "code": "internal_error", "message": str(e)})
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: diffmem-mcp-server
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: DiffMem MCP Server — exposes DiffMem memory APIs as MCP tools with security-first design
|
|
5
|
+
Requires-Python: >=3.12
|
|
6
|
+
Requires-Dist: httpx>=0.27.0
|
|
7
|
+
Requires-Dist: mcp<2,>=1.0.0
|
|
8
|
+
Requires-Dist: pydantic-settings>=2.3.0
|
|
9
|
+
Requires-Dist: pydantic>=2.7.0
|
|
10
|
+
Requires-Dist: sse-starlette>=2.0.0
|
|
11
|
+
Requires-Dist: uvicorn>=0.30.0
|
|
12
|
+
Provides-Extra: dev
|
|
13
|
+
Requires-Dist: pytest-asyncio>=0.23.0; extra == 'dev'
|
|
14
|
+
Requires-Dist: pytest>=8.2.0; extra == 'dev'
|
|
15
|
+
Requires-Dist: ruff>=0.4.0; extra == 'dev'
|