densemem 2.6.6rc12__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.
densemem/__init__.py ADDED
@@ -0,0 +1,44 @@
1
+ from .client import DenseMemClient, SyncDenseMemClient, TokenProvider
2
+ from .errors import (
3
+ DenseMemAuthenticationError,
4
+ DenseMemCancelledError,
5
+ DenseMemError,
6
+ DenseMemOperationError,
7
+ DenseMemProtocolError,
8
+ DenseMemTimeoutError,
9
+ DenseMemTransportError,
10
+ )
11
+ from .requests import (
12
+ Evidence,
13
+ RecallRequest,
14
+ RelationshipProposal,
15
+ RememberRequest,
16
+ SessionEvent,
17
+ SessionRequest,
18
+ TraceRequest,
19
+ )
20
+ from .results import RecallResult, RememberResult, SessionResult, TraceResult
21
+
22
+ __all__ = [
23
+ "DenseMemAuthenticationError",
24
+ "DenseMemCancelledError",
25
+ "DenseMemClient",
26
+ "DenseMemError",
27
+ "DenseMemOperationError",
28
+ "DenseMemProtocolError",
29
+ "DenseMemTimeoutError",
30
+ "DenseMemTransportError",
31
+ "Evidence",
32
+ "RecallRequest",
33
+ "RecallResult",
34
+ "RelationshipProposal",
35
+ "RememberRequest",
36
+ "RememberResult",
37
+ "SessionEvent",
38
+ "SessionRequest",
39
+ "SessionResult",
40
+ "SyncDenseMemClient",
41
+ "TokenProvider",
42
+ "TraceRequest",
43
+ "TraceResult",
44
+ ]
densemem/client.py ADDED
@@ -0,0 +1,310 @@
1
+ import asyncio
2
+ import copy
3
+ import json
4
+ import logging
5
+ import math
6
+ import traceback
7
+ from collections.abc import Callable, Coroutine
8
+ from contextvars import ContextVar
9
+ from typing import Any, Protocol, TypeVar, cast
10
+ from urllib.parse import urlsplit
11
+
12
+ import httpx
13
+ from mcp import ClientSession
14
+ from mcp.client.streamable_http import streamable_http_client
15
+ from mcp.shared.exceptions import McpError
16
+ from mcp.types import InitializeResult, JSONRPCMessage, ListToolsResult
17
+ from pydantic import ValidationError
18
+
19
+ from .errors import (
20
+ DenseMemAuthenticationError,
21
+ DenseMemCancelledError,
22
+ DenseMemError,
23
+ DenseMemOperationError,
24
+ DenseMemProtocolError,
25
+ DenseMemTimeoutError,
26
+ DenseMemTransportError,
27
+ )
28
+ from .requests import RecallRequest, RememberRequest, SessionRequest, TraceRequest
29
+ from .results import RecallResult, RememberResult, SessionResult, TraceResult
30
+
31
+ _operation_token: ContextVar[str] = ContextVar("densemem_operation_token", default="")
32
+
33
+
34
+ class _CredentialFilter(logging.Filter):
35
+ def filter(self, record: logging.LogRecord) -> bool:
36
+ token = _operation_token.get()
37
+ if token:
38
+ record.msg = record.getMessage().replace(token, "[REDACTED]")
39
+ record.args = ()
40
+ if record.exc_info and record.exc_info[1] is not None:
41
+ record.exc_text = "".join(traceback.format_exception(record.exc_info[1])).replace(
42
+ token, "[REDACTED]"
43
+ )
44
+ record.exc_info = None
45
+ return True
46
+
47
+
48
+ logging.getLogger("mcp.client.streamable_http").addFilter(_CredentialFilter())
49
+
50
+
51
+ class TokenProvider(Protocol):
52
+ async def __call__(self) -> str: ...
53
+
54
+
55
+ class DenseMemClient:
56
+ def __init__(
57
+ self,
58
+ endpoint: str,
59
+ *,
60
+ token: str | None = None,
61
+ token_provider: TokenProvider | None = None,
62
+ timeout: float = 190.0,
63
+ ) -> None:
64
+ url = urlsplit(endpoint)
65
+ if (
66
+ url.scheme not in ("http", "https")
67
+ or not url.hostname
68
+ or url.username is not None
69
+ or url.password is not None
70
+ or url.query
71
+ or url.fragment
72
+ ):
73
+ raise ValueError(
74
+ "endpoint must be an HTTP(S) URL without URL credentials or query/fragment"
75
+ )
76
+ if (token is None) == (token_provider is None):
77
+ raise ValueError("provide exactly one of token or token_provider")
78
+ if token is not None and not _valid_token(token):
79
+ raise ValueError("token must be a nonempty bearer credential without line breaks")
80
+ if token_provider is not None and not callable(token_provider):
81
+ raise ValueError("token_provider must be an async callable")
82
+ if not math.isfinite(timeout) or timeout <= 0:
83
+ raise ValueError("timeout must be positive and finite")
84
+ self.endpoint = endpoint
85
+ self.timeout = timeout
86
+ self._token = token
87
+ self._token_provider = token_provider
88
+
89
+ async def initialize(self) -> InitializeResult:
90
+ return cast(InitializeResult, await self._execute("initialize"))
91
+
92
+ async def list_tools(self) -> ListToolsResult:
93
+ return cast(ListToolsResult, await self._execute("list_tools"))
94
+
95
+ async def remember(self, request: RememberRequest) -> RememberResult:
96
+ return cast(RememberResult, await self._execute("remember", cast(dict[str, Any], request)))
97
+
98
+ async def ingest_session(self, request: SessionRequest) -> SessionResult:
99
+ return cast(
100
+ SessionResult, await self._execute("ingest_session", cast(dict[str, Any], request))
101
+ )
102
+
103
+ async def recall_memory(self, request: RecallRequest) -> RecallResult:
104
+ return cast(
105
+ RecallResult, await self._execute("recall_memory", cast(dict[str, Any], request))
106
+ )
107
+
108
+ async def trace_memory(self, request: TraceRequest) -> TraceResult:
109
+ return cast(TraceResult, await self._execute("trace_memory", cast(dict[str, Any], request)))
110
+
111
+ async def _execute(self, method: str, request: dict[str, Any] | None = None) -> Any:
112
+ payload = copy.deepcopy(request)
113
+ token = ""
114
+ token_context = _operation_token.set("")
115
+ response_error: httpx.HTTPStatusError | None = None
116
+
117
+ async def inspect_response(response: httpx.Response) -> None:
118
+ nonlocal response_error
119
+ try:
120
+ await _inspect_response(response)
121
+ except httpx.HTTPStatusError as exc:
122
+ # The SDK can swallow notification HTTP failures during transport cleanup.
123
+ if response_error is None:
124
+ response_error = exc
125
+ raise
126
+
127
+ try:
128
+ async with asyncio.timeout(self.timeout):
129
+ token = await self._credential()
130
+ _operation_token.set(token)
131
+ async with httpx.AsyncClient(
132
+ headers={"Authorization": f"Bearer {token}"},
133
+ timeout=httpx.Timeout(self.timeout, connect=min(10.0, self.timeout)),
134
+ follow_redirects=False,
135
+ event_hooks={"response": [inspect_response]},
136
+ ) as http:
137
+ async with streamable_http_client(self.endpoint, http_client=http) as streams:
138
+ async with ClientSession(streams[0], streams[1]) as session:
139
+ initialized = await session.initialize()
140
+ if method == "initialize":
141
+ return initialized
142
+ if method == "list_tools":
143
+ return await session.list_tools()
144
+ response = await session.call_tool(method, payload)
145
+ result = response.structuredContent
146
+ if not isinstance(result, dict):
147
+ raise DenseMemProtocolError(
148
+ "Dense-Mem did not return structured content"
149
+ )
150
+ if response.isError or result.get("processing_state") == "failed":
151
+ errors = result.get("errors")
152
+ fields = (
153
+ errors[0] if isinstance(errors, list) and errors else result
154
+ )
155
+ code = fields.get("code") if isinstance(fields, dict) else None
156
+ if code == "request_cancelled":
157
+ raise DenseMemCancelledError(
158
+ _public_message(result, token), result=result
159
+ )
160
+ error_type = (
161
+ DenseMemTimeoutError
162
+ if code == "request_timeout"
163
+ else DenseMemOperationError
164
+ )
165
+ raise error_type(_public_message(result, token), result=result)
166
+ return result
167
+ except DenseMemCancelledError:
168
+ raise
169
+ except asyncio.CancelledError:
170
+ raise DenseMemCancelledError(
171
+ "Dense-Mem operation cancelled; receipt is unknown"
172
+ ) from None
173
+ except Exception as exc:
174
+ error = _translate_error(exc, token)
175
+ if response_error is not None and error.result is None:
176
+ error = _translate_error(response_error, token)
177
+ raise error from None
178
+ finally:
179
+ _operation_token.reset(token_context)
180
+
181
+ async def _credential(self) -> str:
182
+ if self._token is not None:
183
+ return self._token
184
+ try:
185
+ assert self._token_provider is not None
186
+ token = await self._token_provider()
187
+ except Exception:
188
+ raise DenseMemAuthenticationError("Token provider failed") from None
189
+ if not _valid_token(token):
190
+ raise DenseMemAuthenticationError(
191
+ "Token provider did not return a valid bearer credential"
192
+ )
193
+ return token
194
+
195
+
196
+ def _valid_token(token: str) -> bool:
197
+ return isinstance(token, str) and bool(token) and "\r" not in token and "\n" not in token
198
+
199
+
200
+ def _public_message(result: dict[str, Any], token: str) -> str:
201
+ errors = result.get("errors")
202
+ fields = errors[0] if isinstance(errors, list) and errors else result
203
+ message = fields.get("message") if isinstance(fields, dict) else None
204
+ if not isinstance(message, str):
205
+ return "Dense-Mem operation failed"
206
+ return (message.replace(token, "[REDACTED]") if token else message)[:512]
207
+
208
+
209
+ async def _inspect_response(response: httpx.Response) -> None:
210
+ if not response.is_error:
211
+ if response.status_code == 200 and response.headers.get("content-type", "").startswith(
212
+ "application/json"
213
+ ):
214
+ try:
215
+ JSONRPCMessage.model_validate_json(await response.aread())
216
+ except ValidationError:
217
+ raise DenseMemProtocolError("Dense-Mem returned an invalid MCP response") from None
218
+ return
219
+ body = bytearray()
220
+ async for chunk in response.aiter_bytes():
221
+ body.extend(chunk[: 16385 - len(body)])
222
+ if len(body) > 16384:
223
+ break
224
+ fields: dict[str, Any] = {}
225
+ if len(body) <= 16384:
226
+ try:
227
+ parsed = json.loads(body)
228
+ except (ValueError, UnicodeDecodeError):
229
+ parsed = None
230
+ if isinstance(parsed, dict):
231
+ fields = parsed
232
+ correlation = response.headers.get("X-Correlation-ID")
233
+ if correlation and "correlation_id" not in fields:
234
+ fields["correlation_id"] = correlation
235
+ response.extensions["densemem_error"] = fields
236
+ response.raise_for_status()
237
+
238
+
239
+ def _translate_error(exc: Exception, token: str) -> DenseMemError:
240
+ if isinstance(exc, ExceptionGroup):
241
+ return _translate_error(exc.exceptions[0], token)
242
+ if isinstance(exc, DenseMemError):
243
+ return exc
244
+ if isinstance(exc, (TimeoutError, httpx.TimeoutException)):
245
+ return DenseMemTimeoutError("Dense-Mem operation timed out; receipt is unknown")
246
+ if isinstance(exc, httpx.HTTPStatusError):
247
+ status = exc.response.status_code
248
+ cls = DenseMemAuthenticationError if status in (401, 403) else DenseMemTransportError
249
+ fields = exc.response.extensions.get("densemem_error") or None
250
+ return cls(
251
+ _public_message(fields, token)
252
+ if fields
253
+ else f"Dense-Mem HTTP request failed ({status})",
254
+ status_code=status,
255
+ result=fields,
256
+ )
257
+ if isinstance(exc, httpx.TransportError):
258
+ return DenseMemTransportError("Dense-Mem transport failed; receipt is unknown")
259
+ if isinstance(exc, McpError):
260
+ result = exc.error.data if isinstance(exc.error.data, dict) else None
261
+ protocol_cls = DenseMemTimeoutError if exc.error.code == 408 else DenseMemProtocolError
262
+ return protocol_cls(
263
+ _public_message(result, token) if result else "Dense-Mem MCP request failed",
264
+ result=result,
265
+ rpc_code=exc.error.code,
266
+ )
267
+ return DenseMemProtocolError("Dense-Mem returned an invalid MCP response")
268
+
269
+
270
+ T = TypeVar("T")
271
+
272
+
273
+ class SyncDenseMemClient:
274
+ def __init__(
275
+ self,
276
+ endpoint: str,
277
+ *,
278
+ token: str | None = None,
279
+ token_provider: TokenProvider | None = None,
280
+ timeout: float = 190.0,
281
+ ) -> None:
282
+ self._async = DenseMemClient(
283
+ endpoint, token=token, token_provider=token_provider, timeout=timeout
284
+ )
285
+
286
+ @staticmethod
287
+ def _run(operation: Callable[[], Coroutine[Any, Any, T]]) -> T:
288
+ try:
289
+ asyncio.get_running_loop()
290
+ except RuntimeError:
291
+ return asyncio.run(operation())
292
+ raise RuntimeError("SyncDenseMemClient cannot run inside an event loop; use DenseMemClient")
293
+
294
+ def initialize(self) -> InitializeResult:
295
+ return self._run(self._async.initialize)
296
+
297
+ def list_tools(self) -> ListToolsResult:
298
+ return self._run(self._async.list_tools)
299
+
300
+ def remember(self, request: RememberRequest) -> RememberResult:
301
+ return self._run(lambda: self._async.remember(request))
302
+
303
+ def ingest_session(self, request: SessionRequest) -> SessionResult:
304
+ return self._run(lambda: self._async.ingest_session(request))
305
+
306
+ def recall_memory(self, request: RecallRequest) -> RecallResult:
307
+ return self._run(lambda: self._async.recall_memory(request))
308
+
309
+ def trace_memory(self, request: TraceRequest) -> TraceResult:
310
+ return self._run(lambda: self._async.trace_memory(request))
densemem/errors.py ADDED
@@ -0,0 +1,68 @@
1
+ import asyncio
2
+ from typing import Any
3
+
4
+
5
+ class DenseMemError(Exception):
6
+ """A bounded client failure; result retains any server-returned receipt."""
7
+
8
+ def __init__(
9
+ self,
10
+ message: str,
11
+ *,
12
+ result: dict[str, Any] | None = None,
13
+ status_code: int | None = None,
14
+ rpc_code: int | None = None,
15
+ ) -> None:
16
+ super().__init__(message)
17
+ self.result = result
18
+ self.status_code = status_code
19
+ self.rpc_code = rpc_code
20
+ fields = result or {}
21
+ errors = fields.get("errors")
22
+ primary = errors[0] if isinstance(errors, list) and errors else fields
23
+ primary = primary if isinstance(primary, dict) else {}
24
+ for name in ("code", "reason_code", "next_action", "remediation"):
25
+ value = primary.get(name)
26
+ setattr(self, name, value if isinstance(value, str) else None)
27
+ self.code: str | None
28
+ self.reason_code: str | None
29
+ self.next_action: str | None
30
+ self.remediation: str | None
31
+ self.retryable = primary.get("retryable") is True
32
+ self.submission_id = self._identifier(fields, "submission_id")
33
+ self.correlation_id = self._identifier(fields, "correlation_id")
34
+
35
+ @staticmethod
36
+ def _identifier(fields: dict[str, Any], key: str) -> str | None:
37
+ value = fields.get(key)
38
+ return value if isinstance(value, str) and 0 < len(value) <= 128 else None
39
+
40
+
41
+ class DenseMemAuthenticationError(DenseMemError):
42
+ """Credential acquisition or HTTP authentication/authorization failed."""
43
+
44
+
45
+ class DenseMemTransportError(DenseMemError):
46
+ """Transport failed; a write without a receipt has an unknown outcome."""
47
+
48
+
49
+ class DenseMemProtocolError(DenseMemError):
50
+ """MCP returned a protocol error or an invalid response."""
51
+
52
+
53
+ class DenseMemOperationError(DenseMemError):
54
+ """The server returned an actionable error or failed terminal receipt."""
55
+
56
+
57
+ class DenseMemTimeoutError(DenseMemTransportError):
58
+ """The client or server deadline elapsed."""
59
+
60
+
61
+ class DenseMemCancelledError(asyncio.CancelledError):
62
+ """Caller cancellation, without an invented server receipt."""
63
+
64
+ def __init__(self, message: str, *, result: dict[str, Any] | None = None) -> None:
65
+ super().__init__(message)
66
+ self.result = result
67
+ self.submission_id = DenseMemError._identifier(result or {}, "submission_id")
68
+ self.correlation_id = DenseMemError._identifier(result or {}, "correlation_id")
densemem/py.typed ADDED
File without changes
densemem/requests.py ADDED
@@ -0,0 +1,115 @@
1
+ from typing import Any, Literal, NotRequired, TypedDict
2
+
3
+ EntityKind = Literal[
4
+ "person", "organization", "project", "product", "place", "document", "concept", "other"
5
+ ]
6
+ ValueType = Literal["string", "number", "boolean", "date", "date_time"]
7
+
8
+
9
+ class EntityProposal(TypedDict, total=False):
10
+ name: str
11
+ entity_kind: EntityKind
12
+ known_entity_id: str | None
13
+
14
+
15
+ class ValueProposal(TypedDict):
16
+ type: ValueType
17
+ value: str | int | float | bool
18
+ display: NotRequired[str]
19
+ unit: NotRequired[str]
20
+
21
+
22
+ class ObjectProposal(TypedDict, total=False):
23
+ entity: EntityProposal
24
+ value: ValueProposal
25
+
26
+
27
+ class PredicateProposal(TypedDict, total=False):
28
+ proposed_key: str
29
+ known_predicate_key: str
30
+
31
+
32
+ class CorrectionTarget(TypedDict):
33
+ relationship_id: str
34
+ expected_version: int
35
+
36
+
37
+ class ConflictContext(TypedDict):
38
+ conflict_id: str
39
+ expected_version: int
40
+
41
+
42
+ class RelationshipProposal(TypedDict):
43
+ ref: str
44
+ subject: EntityProposal
45
+ predicate: PredicateProposal
46
+ object: ObjectProposal
47
+ polarity: Literal["+", "-"]
48
+ evidence_indices: list[int]
49
+ known_evidence_ids: NotRequired[list[str]]
50
+ valid_from: NotRequired[str | None]
51
+ valid_to: NotRequired[str | None]
52
+ correction_target: NotRequired[CorrectionTarget]
53
+ conflict_context: NotRequired[ConflictContext]
54
+ client_comment: NotRequired[str | None]
55
+
56
+
57
+ class Evidence(TypedDict):
58
+ content: str
59
+ source_type: NotRequired[Literal["conversation", "document", "observation", "manual"]]
60
+ source: NotRequired[str]
61
+ authority: NotRequired[Literal["authoritative", "primary", "secondary", "inferred", "unknown"]]
62
+ source_group: NotRequired[str]
63
+ source_key: NotRequired[str]
64
+ source_revision: NotRequired[str]
65
+ previous_source_revision: NotRequired[str]
66
+ supersedes_evidence_ids: NotRequired[list[str]]
67
+ labels: NotRequired[list[str]]
68
+ metadata: NotRequired[dict[str, Any]]
69
+ force_insert: NotRequired[bool]
70
+
71
+
72
+ class RememberRequest(TypedDict):
73
+ idempotency_key: str
74
+ evidence: list[Evidence]
75
+ relationships: list[RelationshipProposal]
76
+
77
+
78
+ class SessionEvent(TypedDict):
79
+ event_id: str
80
+ text: str
81
+ occurred_at: NotRequired[str]
82
+
83
+
84
+ class SessionRequest(TypedDict):
85
+ idempotency_key: str
86
+ framework: str
87
+ app_name: str
88
+ user_id: str
89
+ session_id: str
90
+ events: list[SessionEvent]
91
+
92
+
93
+ class RecallRequest(TypedDict):
94
+ query: str
95
+ limit: NotRequired[int]
96
+ relationship_limit: NotRequired[int]
97
+ community_limit: NotRequired[int]
98
+ community_relationship_limit: NotRequired[int]
99
+ known_at: NotRequired[str | None]
100
+ valid_at: NotRequired[str | None]
101
+ known_evidence_ids: NotRequired[list[str]]
102
+ known_relationship_ids: NotRequired[list[str]]
103
+ expand_from_entity_ids: NotRequired[list[str]]
104
+
105
+
106
+ class TraceRequest(TypedDict):
107
+ relationship_id: str
108
+ include_evidence_content: NotRequired[bool]
109
+ include_verification: NotRequired[bool]
110
+ include_transitions: NotRequired[bool]
111
+ max_depth: NotRequired[int]
112
+ max_edges: NotRequired[int]
113
+ predicate_keys: NotRequired[list[str]]
114
+ topic: NotRequired[str | None]
115
+ min_relevance: NotRequired[float | None]
densemem/results.py ADDED
@@ -0,0 +1,112 @@
1
+ from typing import Any, Literal, NotRequired, TypedDict
2
+
3
+ SearchState = Literal["current", "not_required", "pending", "failed"]
4
+
5
+
6
+ class PublicError(TypedDict):
7
+ code: str
8
+ message: str
9
+ retryable: bool
10
+ next_action: str
11
+ remediation: str
12
+ reason_code: NotRequired[str]
13
+ correlation_id: NotRequired[str]
14
+ details: NotRequired[dict[str, Any]]
15
+ retry_after_seconds: NotRequired[int]
16
+
17
+
18
+ class RelationshipSplit(TypedDict):
19
+ relationship_id: str
20
+ relationship_version: int
21
+ split_index: int
22
+ status: str
23
+
24
+
25
+ class RelationshipResult(TypedDict):
26
+ ref: str
27
+ disposition: Literal["stored", "not_stored"]
28
+ splits: list[RelationshipSplit]
29
+ reason: NotRequired[str]
30
+ message: NotRequired[str]
31
+ remediation: NotRequired[str]
32
+
33
+
34
+ class EvidenceResult(TypedDict):
35
+ evidence_index: int
36
+ disposition: Literal["stored", "not_stored"]
37
+ superseded_evidence_ids: list[str]
38
+ search_state: SearchState
39
+ evidence_id: NotRequired[str]
40
+ content_hash: NotRequired[str]
41
+ reason: NotRequired[str]
42
+ message: NotRequired[str]
43
+ remediation: NotRequired[str]
44
+ error: NotRequired[PublicError | None]
45
+
46
+
47
+ class TerminalResult(TypedDict):
48
+ contract_version: str
49
+ submission_id: str
50
+ submission_kind: str
51
+ correlation_id: str
52
+ processing_state: Literal["completed", "failed"]
53
+ search_state: SearchState
54
+ relationship_results: list[RelationshipResult]
55
+ errors: list[PublicError]
56
+ warnings: NotRequired[list[str]]
57
+
58
+
59
+ class RememberResult(TerminalResult):
60
+ evidence: list[EvidenceResult]
61
+
62
+
63
+ class SessionEventResult(TypedDict):
64
+ event_id: str
65
+ disposition: Literal["accepted", "duplicate"]
66
+ processing_state: Literal["completed", "failed"]
67
+ evidence_ids: list[str]
68
+
69
+
70
+ class SessionResult(TerminalResult):
71
+ accepted_event_count: int
72
+ duplicate_event_count: int
73
+ events: list[SessionEventResult]
74
+
75
+
76
+ class RecallEvidence(TypedDict):
77
+ evidence_id: str
78
+ context: str
79
+ space_kind: Literal["team_shared", "profile_private", "credential_private"]
80
+ equivalent_evidence_ids: list[str]
81
+ equivalents_truncated: bool
82
+
83
+
84
+ class RecallResult(TypedDict):
85
+ recall_id: str
86
+ results: list[RecallEvidence]
87
+ related_relationships: list[dict[str, Any]]
88
+ related_communities: list[dict[str, Any]]
89
+ related_hypotheses: list[dict[str, Any]]
90
+ conflicts: list[dict[str, Any]]
91
+ search_states: dict[str, SearchState]
92
+ degradations: list[dict[str, Any]]
93
+ suggested_actions: list[dict[str, Any]]
94
+
95
+
96
+ class TraceResult(TypedDict):
97
+ relationship: dict[str, Any] | None
98
+ observations: list[dict[str, Any]]
99
+ evidence_supports: list[dict[str, Any]]
100
+ evidence_support_decision_events: list[dict[str, Any]]
101
+ evidence: list[dict[str, Any]]
102
+ evidence_lifecycle_events: list[dict[str, Any]]
103
+ verification_events: list[dict[str, Any]]
104
+ transitions: list[dict[str, Any]]
105
+ conflicts: list[dict[str, Any]]
106
+ cross_profile_references: list[dict[str, Any]]
107
+ identity_corrections: list[dict[str, Any]]
108
+ supersession_lineage: list[dict[str, Any]]
109
+ semantic_nodes: list[dict[str, Any]]
110
+ semantic_edges: list[dict[str, Any]]
111
+ visited_entity_ids: list[str]
112
+ stopped_reason: str | None
@@ -0,0 +1,188 @@
1
+ Metadata-Version: 2.5
2
+ Name: densemem
3
+ Version: 2.6.6rc12
4
+ Summary: Typed async and sync clients for Dense-Mem MCP
5
+ Project-URL: Source, https://github.com/markhuangai/dense-mem/tree/fbca1dc3969b8e49078dcd67a0b6f368d137995e
6
+ Project-URL: Repository, https://github.com/markhuangai/dense-mem
7
+ Project-URL: Documentation, https://github.com/markhuangai/dense-mem/wiki/Framework-Integrations
8
+ Project-URL: Issues, https://github.com/markhuangai/dense-mem/issues
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Programming Language :: Python :: 3.14
16
+ Classifier: Typing :: Typed
17
+ Requires-Python: <3.15,>=3.11
18
+ Requires-Dist: httpx<1,>=0.28.1
19
+ Requires-Dist: mcp<2,>=1.30.0
20
+ Description-Content-Type: text/markdown
21
+
22
+ # densemem Python client
23
+
24
+ The Dense-Mem Python core client uses the official MCP SDK. It supports Python
25
+ 3.11–3.14 and MCP SDK 1.30 through the compatible 1.x line. This package is being
26
+ prepared for release; PyPI publication is pending. Install a verified wheel:
27
+
28
+ ~~~bash
29
+ python -m pip install /path/to/densemem-VERSION-py3-none-any.whl
30
+ ~~~
31
+
32
+ ADK and LangChain adapters/extras will arrive with issues #220 and #221.
33
+ The core installs neither framework.
34
+
35
+ ## Authentication and operations
36
+
37
+ ~~~python
38
+ from densemem import DenseMemClient
39
+
40
+ client = DenseMemClient("https://memory.example.com/teams/TEAM_UUID/mcp", token=api_key)
41
+ tools = await client.list_tools()
42
+ ~~~
43
+
44
+ Pass exactly one of token or token_provider. A provider is an async callable
45
+ returning a caller-owned access token. The client resolves it once per operation;
46
+ it does not acquire or refresh OAuth credentials. Use an authenticated team URL
47
+ or /mcp. Credentials belong only in the bearer header, never the URL. Configure
48
+ transport trust through the environment's certificate store when using a private CA.
49
+
50
+ Each call owns its SDK session, initialization and transport cleanup. The default
51
+ 190-second total deadline allows the server's bounded 180-second write processing.
52
+ A shorter positive finite timeout is supported through the timeout constructor
53
+ argument. The synchronous SyncDenseMemClient exposes the same methods and rejects
54
+ use inside an active event loop.
55
+
56
+ Methods are initialize, list_tools, remember, ingest_session, recall_memory and
57
+ trace_memory. Requests/results are typed dictionaries with py.typed. Server
58
+ validation and authenticated discovery remain authoritative. Current-server
59
+ compatibility is dense-mem.v2.6.8, including server-supported historical terminal
60
+ replay versions; this does not promise compatibility with older deployments.
61
+
62
+ ## Complete Remember request and safe replay
63
+
64
+ ~~~python
65
+ from densemem import RememberRequest
66
+
67
+ request: RememberRequest = {
68
+ "idempotency_key": retained_operation_key,
69
+ "evidence": [
70
+ {
71
+ "content": "Dense-Mem stores durable memory in PostgreSQL.",
72
+ "source_type": "manual",
73
+ "source": "Python core example",
74
+ "metadata": {"origin": "python-example"},
75
+ }
76
+ ],
77
+ "relationships": [
78
+ {
79
+ "ref": "durable-store",
80
+ "subject": {"name": "Dense-Mem", "entity_kind": "project"},
81
+ "predicate": {"proposed_key": "stores_durable_memory_in"},
82
+ "object": {"entity": {"name": "PostgreSQL", "entity_kind": "product"}},
83
+ "polarity": "+",
84
+ "evidence_indices": [0],
85
+ }
86
+ ],
87
+ }
88
+ result = await client.remember(request)
89
+ ~~~
90
+
91
+ Create the operation key once for a deliberate new operation, and retain this
92
+ entire request before sending it. For a replay, resend this unchanged request,
93
+ including metadata and key. Never rotate a key to bypass a conflict. The client
94
+ never retries automatically or fills in keys/defaults. Remember requires at least
95
+ one proposal citing every evidence item. The client does not infer Relationships.
96
+
97
+ Inspect evidence and relationship_results: completed processing can include
98
+ not_stored proposals and remediation. Returned warnings remain visible. Recall
99
+ results preserve server order, equivalent IDs, conflicts, topic communities,
100
+ hypotheses, provenance, search states and degradations. These frontiers do not
101
+ establish new factual support. Trace requires a returned relationship_id.
102
+
103
+ ## Exact private session ingestion
104
+
105
+ ~~~python
106
+ from densemem import SessionRequest
107
+
108
+ request: SessionRequest = {
109
+ "idempotency_key": retained_session_operation_key,
110
+ "framework": "generic",
111
+ "app_name": "python-example",
112
+ "user_id": "external-user-1",
113
+ "session_id": "session-1",
114
+ "events": [
115
+ {
116
+ "event_id": "user-event-1",
117
+ "text": " Ari uses Go. café 🧭\n",
118
+ "occurred_at": "2026-10-11T12:00:00Z",
119
+ }
120
+ ],
121
+ }
122
+ result = await client.ingest_session(request)
123
+ ~~~
124
+
125
+ Send only exact user-authored events. Event IDs/text/timestamps are immutable;
126
+ the server owns chunking and extraction. External identifiers are provenance,
127
+ never authorization or private-space selection. The server must enable session
128
+ ingestion and the credential must have a writable private binding; discovery
129
+ hides unavailable tools. Remember retains its separate proposal requirements.
130
+ Session semantic acceptance is atomic across the request. A no-fact completed
131
+ result with search_state not_required is valid.
132
+
133
+ ## Failures and unknown outcomes
134
+
135
+ DenseMemAuthenticationError reports token acquisition or HTTP 401/403 failures.
136
+ DenseMemTransportError reports network/HTTP failure. DenseMemProtocolError
137
+ reports MCP/response failure. DenseMemOperationError preserves actionable public
138
+ errors and failed receipts in result, with code, reason_code, retryable,
139
+ next_action, remediation, correlation_id and submission_id when returned.
140
+ DenseMemTimeoutError reports deadlines. DenseMemCancelledError subclasses
141
+ asyncio.CancelledError and preserves a returned cancellation receipt if present.
142
+
143
+ A local timeout, disconnect or cancellation can lose a response after a commit.
144
+ An absent receipt means unknown outcome, not a fabricated failed submission.
145
+ Recovery uses only the unchanged original request/key. There is no polling,
146
+ status tool, background readiness loop or automatic new-key recovery.
147
+
148
+ SDK 1.30 negotiates protocol 2025-11-25. Local cancellation closes the client's
149
+ resources; the server can continue processing under this older protocol and may
150
+ commit or reach its bounded deadline. Cancellation does not prove that a write
151
+ was prevented. Retain the unchanged request/key for recovery.
152
+
153
+ ## Development and release
154
+
155
+ Run packages/python/scripts/check.sh for lint/type/async tests, installed-wheel
156
+ checks, reproducible wheel/sdist builds, vulnerability scanning and SBOM. Run
157
+ packages/python/scripts/matrix.sh with a new output directory for the Python
158
+ version matrix, and scripts/e2e.sh python_client for real server boundaries.
159
+ The example scripts require DENSEMEM_ENDPOINT, DENSEMEM_TOKEN and a retained
160
+ DENSEMEM_OPERATION_KEY. Keep the exact request unchanged when rerunning them.
161
+
162
+ The server prerelease and stable-release workflows call publish-python to build
163
+ and verify artifacts after their release gates pass, then upload through their own
164
+ top-level publishing jobs. Manual recovery uploads directly from publish-python;
165
+ the reusable invocation never uploads to PyPI. Only tags whose exact source belongs
166
+ to merged main are eligible;
167
+ PR branches cannot publish. Python shares the server release version: v2.6.6-rc.10
168
+ becomes 2.6.6rc10 and v2.6.6 becomes 2.6.6. The checkout's 0.0.0 version is for local
169
+ development; release builds stamp the selected tag's version and exact Source URL
170
+ into artifact metadata without changing Git history.
171
+
172
+ Change detection compares packages/python with the last successfully published
173
+ Python source recorded on PyPI. Unchanged prereleases are skipped, and publishing
174
+ a final version after a Python RC does not require another code change. Incomplete
175
+ uploads remain eligible; retries verify every existing artifact's SHA-256 before
176
+ uploading missing files. The manual publish-python workflow accepts the same shared
177
+ tag for recovery. Never overwrite an existing version or silently accept different
178
+ bytes; a broken prerelease may be yanked through a separate maintainer action.
179
+
180
+ Verify control of the densemem PyPI name and register trusted publishers for
181
+ markhuangai/dense-mem, workflows release-rc.yml, release.yml and publish-python.yml,
182
+ each with environment pypi. For a new project, configure one pending publisher for
183
+ the first publishing workflow; after it creates the project, register the other
184
+ two as normal project publishers before using those paths. PyPI does not support
185
+ reusable workflows as trusted publishers. This repository does not register
186
+ publishers or change account settings. Release builds retain the
187
+ installed-wheel/version matrix, reproducibility,
188
+ vulnerability scan, SBOM and provenance gates.
@@ -0,0 +1,10 @@
1
+ densemem/__init__.py,sha256=kdxAAMETozoyTO0nX9pcPsKvmzLduR8REhw7cgJRDAQ,1042
2
+ densemem/client.py,sha256=bVEBqCJ1fYKhRq6-EuYAwT2cgWgh5eI6s9H_v_natNM,12760
3
+ densemem/errors.py,sha256=5NmSuNta1wsFDdKYLgpKwCoZ1EUsFDOYeCe6mYa9oyw,2476
4
+ densemem/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ densemem/requests.py,sha256=2mn8Wg96aZoNGNZMQS-PlliKpoBi4yZ2TZCoy5s-QGE,3162
6
+ densemem/results.py,sha256=BiQTE2LLYZ8GF-29W-rZjUDL3xvERzX5nEDBhdCGfAE,3205
7
+ densemem-2.6.6rc12.dist-info/METADATA,sha256=DAc_Fb0IcIryvzCNf4ZqwDNvUp159t7TjMPctTBG4uk,8974
8
+ densemem-2.6.6rc12.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
9
+ densemem-2.6.6rc12.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
10
+ densemem-2.6.6rc12.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.