memoryintelligence-mcp 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.

Potentially problematic release.


This version of memoryintelligence-mcp might be problematic. Click here for more details.

mi_mcp/client.py ADDED
@@ -0,0 +1,259 @@
1
+ """Async HTTP client for the Memory Intelligence API.
2
+
3
+ Thin wrapper around httpx that handles auth headers, error mapping,
4
+ and provides typed methods matching the canonical SDK surface.
5
+ No encryption — the MCP server is a trusted first-party client
6
+ that sends plaintext over HTTPS directly to the API.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import logging
12
+ from typing import Any
13
+
14
+ import httpx
15
+
16
+ from .config import MIConfig
17
+
18
+ logger = logging.getLogger("mi_mcp.client")
19
+
20
+ # ---------------------------------------------------------------------------
21
+ # Error types
22
+ # ---------------------------------------------------------------------------
23
+
24
+ class MIAPIError(Exception):
25
+ """Raised when the MI API returns a non-2xx response."""
26
+
27
+ def __init__(self, status_code: int, detail: str, endpoint: str):
28
+ self.status_code = status_code
29
+ self.detail = detail
30
+ self.endpoint = endpoint
31
+ super().__init__(f"MI API {status_code} on {endpoint}: {detail}")
32
+
33
+
34
+ # ---------------------------------------------------------------------------
35
+ # Client
36
+ # ---------------------------------------------------------------------------
37
+
38
+ class MIClient:
39
+ """Async client for the Memory Intelligence HTTP API.
40
+
41
+ Designed for use inside the MCP server — one instance per server
42
+ lifetime, reuses a single httpx.AsyncClient connection pool.
43
+ """
44
+
45
+ def __init__(self, config: MIConfig):
46
+ self._config = config
47
+ # NOTE: do NOT set Content-Type as a default header — httpx auto-sets
48
+ # the right one per request (application/json for json=, multipart for
49
+ # files=, etc.). Setting it here breaks the /v1/upload multipart call
50
+ # because the leaked Content-Type confuses FastAPI's body parser.
51
+ # See bug #261.
52
+ self._http = httpx.AsyncClient(
53
+ base_url=config.base_url,
54
+ headers={
55
+ "Authorization": f"Bearer {config.api_key}",
56
+ "User-Agent": "mi-mcp-server/0.1.0",
57
+ "X-MI-Source": "mcp",
58
+ },
59
+ timeout=httpx.Timeout(30.0, connect=10.0),
60
+ )
61
+
62
+ async def close(self):
63
+ await self._http.aclose()
64
+
65
+ # ----- helpers -----
66
+
67
+ async def _request(
68
+ self,
69
+ method: str,
70
+ path: str,
71
+ *,
72
+ json: dict | None = None,
73
+ params: dict | None = None,
74
+ ) -> dict[str, Any]:
75
+ """Make an API request and return the JSON response."""
76
+ resp = await self._http.request(method, path, json=json, params=params)
77
+ if resp.status_code >= 400:
78
+ try:
79
+ body = resp.json()
80
+ detail = body.get("detail", resp.text)
81
+ except Exception:
82
+ detail = resp.text
83
+ raise MIAPIError(resp.status_code, str(detail), f"{method} {path}")
84
+ return resp.json()
85
+
86
+ # ----- Core operations -----
87
+
88
+ async def capture(
89
+ self,
90
+ content: str,
91
+ *,
92
+ source: str = "mcp",
93
+ scope: str | None = None,
94
+ scope_id: str | None = None,
95
+ retention_policy: str | None = None,
96
+ pii_handling: str | None = None,
97
+ metadata: dict | None = None,
98
+ ) -> dict[str, Any]:
99
+ """POST /v1/process — capture content into a UMO."""
100
+ payload: dict[str, Any] = {
101
+ "content": content,
102
+ "source": source,
103
+ "scope": scope or self._config.default_scope,
104
+ }
105
+ if scope_id:
106
+ payload["scope_id"] = scope_id
107
+ if retention_policy:
108
+ payload["retention_policy"] = retention_policy
109
+ else:
110
+ payload["retention_policy"] = self._config.default_retention
111
+ if pii_handling:
112
+ payload["pii_handling"] = pii_handling
113
+ else:
114
+ payload["pii_handling"] = self._config.default_pii_handling
115
+ if metadata:
116
+ payload["metadata"] = metadata
117
+
118
+ return await self._request("POST", "/v1/process", json=payload)
119
+
120
+ async def ask(
121
+ self,
122
+ query: str,
123
+ *,
124
+ scope: str | None = None,
125
+ scope_id: str | None = None,
126
+ limit: int = 10,
127
+ offset: int = 0,
128
+ explain: str | bool = False,
129
+ date_from: str | None = None,
130
+ date_to: str | None = None,
131
+ topics: list[str] | None = None,
132
+ entities: list[str] | None = None,
133
+ ) -> dict[str, Any]:
134
+ """POST /v1/memories/query — semantic search across memories."""
135
+ payload: dict[str, Any] = {
136
+ "query": query,
137
+ "scope": scope or self._config.default_scope,
138
+ "limit": limit,
139
+ "offset": offset,
140
+ }
141
+ if explain:
142
+ payload["explain"] = explain
143
+ if scope_id:
144
+ payload["scope_id"] = scope_id
145
+ if date_from:
146
+ payload["date_from"] = date_from
147
+ if date_to:
148
+ payload["date_to"] = date_to
149
+ if topics:
150
+ payload["topics"] = topics
151
+ if entities:
152
+ payload["entities"] = entities
153
+
154
+ return await self._request("POST", "/v1/memories/query", json=payload)
155
+
156
+ async def list_memories(
157
+ self,
158
+ *,
159
+ limit: int = 20,
160
+ offset: int = 0,
161
+ scope: str | None = None,
162
+ ) -> dict[str, Any]:
163
+ """GET /v1/memories — list UMOs with pagination."""
164
+ params: dict[str, Any] = {"limit": limit, "offset": offset}
165
+ if scope:
166
+ params["scope"] = scope
167
+ return await self._request("GET", "/v1/memories", params=params)
168
+
169
+ async def explain(self, umo_id: str, *, level: str = "full") -> dict[str, Any]:
170
+ """GET /v1/memories/{id}/explain — UMO introspection."""
171
+ return await self._request(
172
+ "GET", f"/v1/memories/{umo_id}/explain", params={"level": level}
173
+ )
174
+
175
+ async def verify(self, umo_id: str) -> dict[str, Any]:
176
+ """GET /v1/memories/{id}/proof — provenance verification."""
177
+ return await self._request("GET", f"/v1/memories/{umo_id}/proof")
178
+
179
+ async def forget(self, umo_id: str) -> dict[str, Any]:
180
+ """DELETE /v1/memories/{id} — delete a UMO with receipt."""
181
+ return await self._request("DELETE", f"/v1/memories/{umo_id}")
182
+
183
+ async def match(
184
+ self,
185
+ source_id: str,
186
+ candidate_id: str,
187
+ *,
188
+ explain: str = "none",
189
+ threshold: float = 0.7,
190
+ ) -> dict[str, Any]:
191
+ """POST /v1/umo/match — compare two UMOs for relevance.
192
+
193
+ `explain` is an enum string, not a boolean. Valid values:
194
+ 'none', 'human', 'audit', 'full'. See bug #260.
195
+ """
196
+ return await self._request(
197
+ "POST",
198
+ "/v1/umo/match",
199
+ json={
200
+ "source_ulid": source_id,
201
+ "candidate_ulid": candidate_id,
202
+ "explain": explain,
203
+ "threshold": threshold,
204
+ },
205
+ )
206
+
207
+ async def batch(
208
+ self,
209
+ items: list[dict[str, Any]],
210
+ *,
211
+ scope: str | None = None,
212
+ ) -> dict[str, Any]:
213
+ """POST /v1/batch — batch capture multiple items."""
214
+ return await self._request(
215
+ "POST",
216
+ "/v1/batch",
217
+ json={
218
+ "items": items,
219
+ "scope": scope or self._config.default_scope,
220
+ },
221
+ )
222
+
223
+ async def upload(
224
+ self,
225
+ file_path: str,
226
+ *,
227
+ scope: str | None = None,
228
+ metadata: dict | None = None,
229
+ ) -> dict[str, Any]:
230
+ """POST /v1/upload — upload a media file for capture.
231
+
232
+ Note: This uses multipart form upload, not JSON.
233
+ """
234
+ import os
235
+ from pathlib import Path
236
+
237
+ path = Path(file_path)
238
+ if not path.exists():
239
+ raise FileNotFoundError(f"File not found: {file_path}")
240
+
241
+ # Build multipart — can't use self._request helper here
242
+ files = {"file": (path.name, open(path, "rb"))}
243
+ data: dict[str, str] = {"scope": scope or self._config.default_scope}
244
+ if metadata:
245
+ import json
246
+ data["metadata"] = json.dumps(metadata)
247
+
248
+ resp = await self._http.post("/v1/upload", files=files, data=data)
249
+ if resp.status_code >= 400:
250
+ try:
251
+ detail = resp.json().get("detail", resp.text)
252
+ except Exception:
253
+ detail = resp.text
254
+ raise MIAPIError(resp.status_code, str(detail), "POST /v1/upload")
255
+ return resp.json()
256
+
257
+ async def account_info(self) -> dict[str, Any]:
258
+ """GET /v1/accounts/me — get current account info and key status."""
259
+ return await self._request("GET", "/v1/accounts/me")
mi_mcp/config.py ADDED
@@ -0,0 +1,121 @@
1
+ """Configuration for the MI MCP Server.
2
+
3
+ All config is resolved from environment variables at startup.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import fnmatch
9
+ import os
10
+ from dataclasses import dataclass, field
11
+ from pathlib import Path
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class MIConfig:
16
+ """Immutable configuration resolved from environment."""
17
+
18
+ # Required
19
+ api_key: str
20
+
21
+ # API endpoint (defaults to production)
22
+ base_url: str = "https://api.memoryintelligence.io"
23
+
24
+ # Optional defaults
25
+ default_scope: str = "user"
26
+ default_retention: str = "meaning_only"
27
+ default_pii_handling: str = "extract_and_redact"
28
+
29
+ # Transport
30
+ transport: str = "stdio"
31
+ host: str = "127.0.0.1" # loopback only; network transports are not part of v0
32
+ port: int = 8100
33
+
34
+ # Tool surface — v0 exposes 3 tools by default; MI_MCP_FULL=1 exposes all 10 (#256).
35
+ full_tools: bool = False
36
+
37
+ @classmethod
38
+ def from_env(cls) -> MIConfig:
39
+ """Build config from environment variables.
40
+
41
+ Required:
42
+ MI_API_KEY — your Memory Intelligence API key
43
+
44
+ Optional:
45
+ MI_BASE_URL — API base URL (default: https://api.memoryintelligence.io)
46
+ MI_DEFAULT_SCOPE — default governance scope (default: user)
47
+ MI_TRANSPORT — stdio | sse | streamable-http (default: stdio)
48
+ MI_HOST — bind host for SSE/HTTP (default: 127.0.0.1, loopback only)
49
+ MI_PORT — bind port for SSE/HTTP (default: 8100)
50
+ MI_MCP_FULL — "1" exposes all 10 tools; otherwise only the 3 core (#256)
51
+ """
52
+ api_key = os.environ.get("MI_API_KEY", "")
53
+ if not api_key:
54
+ raise ValueError(
55
+ "MI_API_KEY is required.\n"
56
+ "Recommended: run `mi-mcp wire` — it resolves the key from your macOS Keychain\n"
57
+ "at launch, so the key never lives in any config file. Or export MI_API_KEY in\n"
58
+ "your shell. Never paste the key into an MCP client config file.\n"
59
+ "Get your key at https://memoryintelligence.io/portal"
60
+ )
61
+
62
+ return cls(
63
+ api_key=api_key,
64
+ base_url=os.environ.get("MI_BASE_URL", cls.base_url).rstrip("/"),
65
+ default_scope=os.environ.get("MI_DEFAULT_SCOPE", cls.default_scope),
66
+ default_retention=os.environ.get("MI_DEFAULT_RETENTION", cls.default_retention),
67
+ default_pii_handling=os.environ.get("MI_DEFAULT_PII_HANDLING", cls.default_pii_handling),
68
+ transport=os.environ.get("MI_TRANSPORT", cls.transport),
69
+ host=os.environ.get("MI_HOST", cls.host),
70
+ port=int(os.environ.get("MI_PORT", str(cls.port))),
71
+ full_tools=os.environ.get("MI_MCP_FULL") == "1",
72
+ )
73
+
74
+
75
+ # =============================================================================
76
+ # Capture consent gate (Story 8) — writes only from opted-in directories
77
+ # =============================================================================
78
+
79
+ OPT_IN_PATHS_FILE = Path.home() / ".mi" / "opt-in-paths"
80
+
81
+
82
+ def load_opt_in_paths(path: Path | None = None) -> list[str]:
83
+ """Load the capture opt-in allowlist.
84
+
85
+ File: ~/.mi/opt-in-paths — one path per line. `~` is expanded; fnmatch
86
+ globs (``*``, ``?``, ``[]``) are supported; blank lines and lines starting
87
+ with ``#`` are ignored. Absent file → empty list → every capture is
88
+ skipped (explicit opt-in required; matches the ownership-first stance).
89
+ """
90
+ path = path or OPT_IN_PATHS_FILE
91
+ if not path.exists():
92
+ return []
93
+ out: list[str] = []
94
+ for raw in path.read_text().splitlines():
95
+ s = raw.strip()
96
+ if not s or s.startswith("#"):
97
+ continue
98
+ out.append(os.path.expanduser(s))
99
+ return out
100
+
101
+
102
+ def is_cwd_opted_in(cwd: str | None = None, patterns: list[str] | None = None) -> bool:
103
+ """Return True if ``cwd`` is covered by the opt-in allowlist.
104
+
105
+ - ``MI_MCP_OPT_IN_ALL=1`` bypasses the check (returns True). Intended for
106
+ testing; the server logs a warning at startup when it is set.
107
+ - A non-glob entry matches its own directory and any subdirectory of it.
108
+ - A glob entry (``*``/``?``/``[]``) is matched with ``fnmatch``.
109
+ """
110
+ if os.environ.get("MI_MCP_OPT_IN_ALL") == "1":
111
+ return True
112
+ cwd_abs = os.path.abspath(cwd if cwd is not None else os.getcwd())
113
+ for p in (patterns if patterns is not None else load_opt_in_paths()):
114
+ if any(c in p for c in "*?["):
115
+ if fnmatch.fnmatch(cwd_abs, p) or fnmatch.fnmatch(cwd_abs, os.path.join(p, "*")):
116
+ return True
117
+ else:
118
+ base = os.path.abspath(os.path.expanduser(p))
119
+ if cwd_abs == base or cwd_abs.startswith(base + os.sep):
120
+ return True
121
+ return False