memoryintelligence-mcp 0.2.5__tar.gz → 0.2.7__tar.gz

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.

Files changed (23) hide show
  1. {memoryintelligence_mcp-0.2.5 → memoryintelligence_mcp-0.2.7}/CHANGELOG.md +94 -0
  2. {memoryintelligence_mcp-0.2.5 → memoryintelligence_mcp-0.2.7}/PKG-INFO +38 -6
  3. {memoryintelligence_mcp-0.2.5 → memoryintelligence_mcp-0.2.7}/README.md +37 -5
  4. {memoryintelligence_mcp-0.2.5 → memoryintelligence_mcp-0.2.7}/pyproject.toml +1 -1
  5. {memoryintelligence_mcp-0.2.5 → memoryintelligence_mcp-0.2.7}/src/mi_mcp/__init__.py +1 -1
  6. {memoryintelligence_mcp-0.2.5 → memoryintelligence_mcp-0.2.7}/src/mi_mcp/cli.py +83 -14
  7. {memoryintelligence_mcp-0.2.5 → memoryintelligence_mcp-0.2.7}/src/mi_mcp/client.py +87 -6
  8. {memoryintelligence_mcp-0.2.5 → memoryintelligence_mcp-0.2.7}/src/mi_mcp/config.py +2 -2
  9. {memoryintelligence_mcp-0.2.5 → memoryintelligence_mcp-0.2.7}/src/mi_mcp/server.py +355 -17
  10. {memoryintelligence_mcp-0.2.5 → memoryintelligence_mcp-0.2.7}/.gitignore +0 -0
  11. {memoryintelligence_mcp-0.2.5 → memoryintelligence_mcp-0.2.7}/CONTRIBUTING.md +0 -0
  12. {memoryintelligence_mcp-0.2.5 → memoryintelligence_mcp-0.2.7}/LICENSE +0 -0
  13. {memoryintelligence_mcp-0.2.5 → memoryintelligence_mcp-0.2.7}/src/mi_mcp/__main__.py +0 -0
  14. {memoryintelligence_mcp-0.2.5 → memoryintelligence_mcp-0.2.7}/src/mi_mcp/embedder.py +0 -0
  15. {memoryintelligence_mcp-0.2.5 → memoryintelligence_mcp-0.2.7}/src/mi_mcp/indexer.py +0 -0
  16. {memoryintelligence_mcp-0.2.5 → memoryintelligence_mcp-0.2.7}/src/mi_mcp/keys.py +0 -0
  17. {memoryintelligence_mcp-0.2.5 → memoryintelligence_mcp-0.2.7}/src/mi_mcp/local_index.py +0 -0
  18. {memoryintelligence_mcp-0.2.5 → memoryintelligence_mcp-0.2.7}/src/mi_mcp/localreads.py +0 -0
  19. {memoryintelligence_mcp-0.2.5 → memoryintelligence_mcp-0.2.7}/src/mi_mcp/paths.py +0 -0
  20. {memoryintelligence_mcp-0.2.5 → memoryintelligence_mcp-0.2.7}/src/mi_mcp/recall_guard.py +0 -0
  21. {memoryintelligence_mcp-0.2.5 → memoryintelligence_mcp-0.2.7}/src/mi_mcp/scrub.py +0 -0
  22. {memoryintelligence_mcp-0.2.5 → memoryintelligence_mcp-0.2.7}/src/mi_mcp/umo_format.py +0 -0
  23. {memoryintelligence_mcp-0.2.5 → memoryintelligence_mcp-0.2.7}/src/mi_mcp/vault.py +0 -0
@@ -3,6 +3,100 @@
3
3
  All notable changes to `memoryintelligence-mcp` are documented here.
4
4
  The format follows [Keep a Changelog](https://keepachangelog.com/); this project uses [Semantic Versioning](https://semver.org/).
5
5
 
6
+ ## [0.2.7] — 2026-08-03
7
+
8
+ ### Added — `mi_ask` / `mi_list` take a `workspace_id` (#385 UC2)
9
+ Symmetric with `mi_capture` (one mental model: *omit = personal, pass an id = that
10
+ workspace*). Omit it and the read is personal, byte-for-byte as before — no wrapper,
11
+ no extra key, no extra round-trip. Pass a workspace you belong to and the read is
12
+ scoped to it; a workspace you do **not** belong to is refused rather than silently
13
+ downgraded to personal, so the scope a result reports is never a lie.
14
+
15
+ Two things specific to this surface:
16
+
17
+ - **A workspace read never comes from the on-device index.** `MI_MCP_LOCAL=1`
18
+ serves reads locally, and the local index has no workspace concept — answering
19
+ from it would return personal memories under a workspace label. A workspace
20
+ target forces the cloud path, the same way advanced filters already do.
21
+ - **The result says whether other members' memories are actually included.**
22
+ Server-side workspace read-isolation (`MI_WORKSPACE_READ_ISOLATION`) is **off by
23
+ default**, and with it off a member-targeted read returns exactly what a personal
24
+ read returns. The scope block therefore carries `member_wide_reads`
25
+ (`true` / `false` / `"unknown"`), read from the server's own `/health`
26
+ capabilities and cached per process. When it is not `true` on a multi-member
27
+ workspace the block also carries a `note` telling the agent not to claim it
28
+ searched the whole team. **Without this, `shared: true, member_count: 4` on an
29
+ owner-scoped read is an overclaim waiting to be repeated to a user.**
30
+
31
+ Requires an API server new enough to advertise
32
+ `capabilities.workspace_read_isolation` in `/health`; older servers report
33
+ `"unknown"` rather than a guess. The remote MCP surface reports the same field
34
+ (read directly from the flag, since it runs inside the API process), so both
35
+ surfaces describe a workspace read the same way.
36
+
37
+ ### Added — `mi_capture(workspace_id=…)` — workspace routing actually works (#385 UC1)
38
+ Routing a capture to a specific workspace was **documented as shipped and was not
39
+ implemented on this surface**. The backend has honored it since #736/#385 and the
40
+ REMOTE MCP sends it — but the local package had no way to *express* a target:
41
+ `mi_capture` had no `workspace_id` argument and `MIClient.capture()` sent no
42
+ routing header. `mi_workspaces` (added in 0.2.6) listed workspaces the tools then
43
+ could not capture into, and its description told agents to pass the workspace ULID
44
+ as `scope_id`, which routes nothing (`scope`/`scope_id` is the separate governance-scope
45
+ axis, sent in the request body). Now:
46
+
47
+ - **`mi_capture(content, workspace_id?, confirm?)`** routes the capture. Omit
48
+ `workspace_id` and the capture goes to your home workspace exactly as before —
49
+ personal is still the default, and an untargeted capture costs no extra API call.
50
+ - **A shared-workspace write is gated.** Targeting a workspace with more than one
51
+ member without `confirm=true` returns `{"status": "confirm_required", …}` and
52
+ **saves nothing** — a single silent call can never post a memory into a team
53
+ space. Solo and personal captures need no confirm.
54
+ - **Every routed capture names where it landed** — the response carries
55
+ `destination: {workspace_id, name, role, shared, member_count}`.
56
+ - **A workspace you are not a member of is refused, not silently downgraded** to
57
+ personal, so a reported destination is never a lie. Authorization itself stays
58
+ server-side; this mirrors it so the feedback is accurate.
59
+
60
+ This matches the remote surface's contract (`mi_capture` there already took
61
+ `workspace_id` + `confirm`), so both MCP surfaces now route captures identically.
62
+
63
+ Note on the wire: the target is sent as a **header**, and the API has two names for
64
+ it depending on the auth plane — `X-MI-Workspace` (API-key plane, which this package
65
+ uses) and `X-Workspace-Id` (JWT plane, what the remote sends). The client sends both,
66
+ so routing is correct on either plane.
67
+
68
+ ## [0.2.6] — 2026-08-03
69
+
70
+ ### Changed — the local server is now named `mi-local` (#1320)
71
+ The local stdio server announced itself as `Server("memoryintelligence")` and
72
+ `mi-mcp setup`/`wire` registered it under the config key `memoryintelligence` —
73
+ while the REMOTE MCP surface (`api.memoryintelligence.io/v1/mcp`) announces
74
+ `memoryintelligence-remote` but is typically added to claude.ai/Desktop under
75
+ the display name "memoryintelligence". On any client hosting both, the two
76
+ surfaces were indistinguishable and tool calls silently resolved to the wrong
77
+ one: during a 2026-08-02 debug, the local server's tools masqueraded as the
78
+ remote's, and `mi_workspaces` "didn't exist" because the remote was never
79
+ called. The local server now announces `mi-local` and wires under that key.
80
+
81
+ **Migration is automatic and guarded**: re-running `mi-mcp setup` or
82
+ `mi-mcp wire` renames an existing `memoryintelligence` (or pre-0.1.8
83
+ `memory-intelligence`) config entry to `mi-local` — but ONLY when that entry
84
+ points at the mi-mcp launcher (`run-mi-mcp.sh`, `python -m mi_mcp`, or the
85
+ `mi-mcp` binary). An identically-named entry pointing anywhere else is left
86
+ untouched. `mi-mcp doctor` detects a pending rename and tells you to run
87
+ `mi-mcp wire`. Idempotent — re-running is always safe.
88
+
89
+ Which server am I talking to? The local announces `mi-local` (7 tools by
90
+ default, 11 with `MI_MCP_FULL=1`); the remote announces
91
+ `memoryintelligence-remote` (4 tools).
92
+
93
+ ### Added — `mi_workspaces` (tool-surface parity with the remote, #1320)
94
+ The remote surface added `mi_workspaces` for workspace routing; the local
95
+ package now has it too, in the default surface: lists the workspaces you can
96
+ capture into (id, name, your role, member count) via `GET /v1/workspaces` —
97
+ the same endpoint the remote calls, so "does mi_workspaces exist" answers the
98
+ same on both surfaces. Default surface is now 7 tools; the full surface is 11.
99
+
6
100
  ## [0.2.5] — 2026-07-24
7
101
 
8
102
  ### Fixed — capture now works on Claude Desktop / claude.ai connector / Cowork
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: memoryintelligence-mcp
3
- Version: 0.2.5
3
+ Version: 0.2.7
4
4
  Summary: MCP server for MemoryIntelligence — give Claude a memory you own, set up in one command
5
5
  Project-URL: Homepage, https://memoryintelligence.io
6
6
  Project-URL: Repository, https://github.com/somewhere11/memoryintelligence-mcp
@@ -86,10 +86,37 @@ And four things that make it more than a notepad:
86
86
  - **Owned** — memories are portable structured objects in *your* account, not locked in a model.
87
87
  - **Private** — capture is opt-in per project; PII is redacted from what the agent sees.
88
88
 
89
- > Set `MI_MCP_FULL=1` for the full surface (`mi_upload`, `mi_verify`, `mi_forget`,
89
+ > The default surface is 7 tools (also `mi_upload`, `mi_verify`, `mi_forget`,
90
+ > `mi_workspaces`). Set `MI_MCP_FULL=1` for the full 11-tool surface (adds
90
91
  > `mi_batch`, `mi_explain`, `mi_match`, `mi_account`). Tools outside the active
91
92
  > surface are rejected at the call boundary, not just hidden.
92
93
 
94
+ ### Capturing into a shared workspace
95
+
96
+ By default every capture is **personal** — it lands in your home workspace and
97
+ nobody else sees it. To put one in a team space, name it:
98
+
99
+ > *"List my workspaces."* → `mi_workspaces`
100
+ > *"Save that to Somewhere Inc."* → `mi_capture(workspace_id=…)`
101
+
102
+ Two rules keep a shared space from filling up by accident:
103
+
104
+ - **A workspace with more than one member needs an explicit confirm.** The first
105
+ call returns a preview — *"this posts to Somewhere Inc, visible to 4 members"* —
106
+ and **saves nothing**. Only after you say yes does the agent re-call with
107
+ `confirm=true`. A fresh chat can't inherit that approval.
108
+ - **Every capture tells you where it went**, and a workspace you don't belong to is
109
+ refused rather than quietly saved somewhere else.
110
+
111
+ Reading works the same way — `mi_ask` and `mi_list` take the same `workspace_id`:
112
+
113
+ > *"What did the team decide about billing?"* → `mi_ask(workspace_id=…)`
114
+
115
+ Omit it and you search your own memories. One caveat worth knowing: whether a
116
+ workspace read returns *other members'* memories is a server-side setting that is
117
+ **off by default**. The result's `scope` block reports `member_wide_reads` so the
118
+ assistant can tell you what it actually searched instead of assuming.
119
+
93
120
  ## How it works
94
121
 
95
122
  ```
@@ -132,7 +159,7 @@ and never leaves your machine except to authenticate.
132
159
  redacts PII from what the agent sees (your own portal shows it raw).
133
160
  - **stdio only — no open port.** Runs as a local subprocess; networked transports are
134
161
  disabled in this version (they return with OAuth 2.1 + TLS later).
135
- - **Off switch.** Clear `opt-in-paths`, or remove the `memoryintelligence` entry from
162
+ - **Off switch.** Clear `opt-in-paths`, or remove the `mi-local` entry from
136
163
  your config to fully unwire.
137
164
 
138
165
  Found a vulnerability? [SECURITY.md](SECURITY.md) — report privately to connect@somewheremedia.com.
@@ -147,7 +174,7 @@ Found a vulnerability? [SECURITY.md](SECURITY.md) — report privately to connec
147
174
  |----------|---------|-------------|
148
175
  | `MI_API_KEY` | — | Resolved by the launcher from Keychain / keyfile — don't set inline in configs |
149
176
  | `MI_BASE_URL` | `https://api.memoryintelligence.io` | API base URL |
150
- | `MI_MCP_FULL` | _(off)_ | `1` exposes all 10 tools; otherwise the 3 core |
177
+ | `MI_MCP_FULL` | _(off)_ | `1` exposes all 11 tools; otherwise the 7-tool default surface |
151
178
  | `MI_VAULT` | `~/Somewhere` (set by `wire`) | Local `.umo` vault — `wire`/`setup` point it at `~/Somewhere` so it's shared with the MemorySpace Desktop app. Unwired fallback is `~/MemoryIntelligence`; an explicit value here always wins. |
152
179
  | `MI_DEFAULT_SCOPE` · `MI_DEFAULT_RETENTION` · `MI_DEFAULT_PII_HANDLING` | `user` · `meaning_only` · `extract_and_redact` | Governance defaults |
153
180
 
@@ -158,7 +185,7 @@ Found a vulnerability? [SECURITY.md](SECURITY.md) — report privately to connec
158
185
  | `MemoryIntelligence` | the brand |
159
186
  | `memoryintelligence-mcp` | the PyPI package (`pip install`) |
160
187
  | `mi-mcp` | the command you run (`mi-mcp setup`) |
161
- | `memoryintelligence` | the server id in your MCP config |
188
+ | `mi-local` | the server id in your MCP config — distinct from the REMOTE MCP surface, which announces `memoryintelligence-remote` (#1320). `memoryintelligence` (≤0.2.5) is legacy; `mi-mcp wire` renames it |
162
189
  | `MI_*` | env vars / Keychain service |
163
190
 
164
191
  **On disk** — one namespace:
@@ -199,6 +226,11 @@ mi-mcp doctor # checks binary, PATH, key, wiring, opt-in, vault path
199
226
  mi-mcp status # wired surfaces + opt-in allowlist
200
227
  mi-mcp wire --dry-run # preview wiring changes
201
228
  ```
229
+
230
+ **Which server am I talking to?** The local server announces `mi-local`; the
231
+ remote MCP surface announces `memoryintelligence-remote`. The local default
232
+ surface is 7 tools; the remote is 4 — if the tool list doesn't match what you
233
+ expect, the client resolved the other surface (#1320).
202
234
  </details>
203
235
 
204
236
  <details>
@@ -209,7 +241,7 @@ VS Code / Copilot read a different config than Claude: servers live under `"serv
209
241
  it, or add per-workspace `.vscode/mcp.json`:
210
242
 
211
243
  ```json
212
- { "servers": { "memoryintelligence": { "type": "stdio", "command": "mi-mcp" } } }
244
+ { "servers": { "mi-local": { "type": "stdio", "command": "mi-mcp" } } }
213
245
  ```
214
246
 
215
247
  Then open Copilot Chat in **Agent** mode — the memory tools only appear there.
@@ -47,10 +47,37 @@ And four things that make it more than a notepad:
47
47
  - **Owned** — memories are portable structured objects in *your* account, not locked in a model.
48
48
  - **Private** — capture is opt-in per project; PII is redacted from what the agent sees.
49
49
 
50
- > Set `MI_MCP_FULL=1` for the full surface (`mi_upload`, `mi_verify`, `mi_forget`,
50
+ > The default surface is 7 tools (also `mi_upload`, `mi_verify`, `mi_forget`,
51
+ > `mi_workspaces`). Set `MI_MCP_FULL=1` for the full 11-tool surface (adds
51
52
  > `mi_batch`, `mi_explain`, `mi_match`, `mi_account`). Tools outside the active
52
53
  > surface are rejected at the call boundary, not just hidden.
53
54
 
55
+ ### Capturing into a shared workspace
56
+
57
+ By default every capture is **personal** — it lands in your home workspace and
58
+ nobody else sees it. To put one in a team space, name it:
59
+
60
+ > *"List my workspaces."* → `mi_workspaces`
61
+ > *"Save that to Somewhere Inc."* → `mi_capture(workspace_id=…)`
62
+
63
+ Two rules keep a shared space from filling up by accident:
64
+
65
+ - **A workspace with more than one member needs an explicit confirm.** The first
66
+ call returns a preview — *"this posts to Somewhere Inc, visible to 4 members"* —
67
+ and **saves nothing**. Only after you say yes does the agent re-call with
68
+ `confirm=true`. A fresh chat can't inherit that approval.
69
+ - **Every capture tells you where it went**, and a workspace you don't belong to is
70
+ refused rather than quietly saved somewhere else.
71
+
72
+ Reading works the same way — `mi_ask` and `mi_list` take the same `workspace_id`:
73
+
74
+ > *"What did the team decide about billing?"* → `mi_ask(workspace_id=…)`
75
+
76
+ Omit it and you search your own memories. One caveat worth knowing: whether a
77
+ workspace read returns *other members'* memories is a server-side setting that is
78
+ **off by default**. The result's `scope` block reports `member_wide_reads` so the
79
+ assistant can tell you what it actually searched instead of assuming.
80
+
54
81
  ## How it works
55
82
 
56
83
  ```
@@ -93,7 +120,7 @@ and never leaves your machine except to authenticate.
93
120
  redacts PII from what the agent sees (your own portal shows it raw).
94
121
  - **stdio only — no open port.** Runs as a local subprocess; networked transports are
95
122
  disabled in this version (they return with OAuth 2.1 + TLS later).
96
- - **Off switch.** Clear `opt-in-paths`, or remove the `memoryintelligence` entry from
123
+ - **Off switch.** Clear `opt-in-paths`, or remove the `mi-local` entry from
97
124
  your config to fully unwire.
98
125
 
99
126
  Found a vulnerability? [SECURITY.md](SECURITY.md) — report privately to connect@somewheremedia.com.
@@ -108,7 +135,7 @@ Found a vulnerability? [SECURITY.md](SECURITY.md) — report privately to connec
108
135
  |----------|---------|-------------|
109
136
  | `MI_API_KEY` | — | Resolved by the launcher from Keychain / keyfile — don't set inline in configs |
110
137
  | `MI_BASE_URL` | `https://api.memoryintelligence.io` | API base URL |
111
- | `MI_MCP_FULL` | _(off)_ | `1` exposes all 10 tools; otherwise the 3 core |
138
+ | `MI_MCP_FULL` | _(off)_ | `1` exposes all 11 tools; otherwise the 7-tool default surface |
112
139
  | `MI_VAULT` | `~/Somewhere` (set by `wire`) | Local `.umo` vault — `wire`/`setup` point it at `~/Somewhere` so it's shared with the MemorySpace Desktop app. Unwired fallback is `~/MemoryIntelligence`; an explicit value here always wins. |
113
140
  | `MI_DEFAULT_SCOPE` · `MI_DEFAULT_RETENTION` · `MI_DEFAULT_PII_HANDLING` | `user` · `meaning_only` · `extract_and_redact` | Governance defaults |
114
141
 
@@ -119,7 +146,7 @@ Found a vulnerability? [SECURITY.md](SECURITY.md) — report privately to connec
119
146
  | `MemoryIntelligence` | the brand |
120
147
  | `memoryintelligence-mcp` | the PyPI package (`pip install`) |
121
148
  | `mi-mcp` | the command you run (`mi-mcp setup`) |
122
- | `memoryintelligence` | the server id in your MCP config |
149
+ | `mi-local` | the server id in your MCP config — distinct from the REMOTE MCP surface, which announces `memoryintelligence-remote` (#1320). `memoryintelligence` (≤0.2.5) is legacy; `mi-mcp wire` renames it |
123
150
  | `MI_*` | env vars / Keychain service |
124
151
 
125
152
  **On disk** — one namespace:
@@ -160,6 +187,11 @@ mi-mcp doctor # checks binary, PATH, key, wiring, opt-in, vault path
160
187
  mi-mcp status # wired surfaces + opt-in allowlist
161
188
  mi-mcp wire --dry-run # preview wiring changes
162
189
  ```
190
+
191
+ **Which server am I talking to?** The local server announces `mi-local`; the
192
+ remote MCP surface announces `memoryintelligence-remote`. The local default
193
+ surface is 7 tools; the remote is 4 — if the tool list doesn't match what you
194
+ expect, the client resolved the other surface (#1320).
163
195
  </details>
164
196
 
165
197
  <details>
@@ -170,7 +202,7 @@ VS Code / Copilot read a different config than Claude: servers live under `"serv
170
202
  it, or add per-workspace `.vscode/mcp.json`:
171
203
 
172
204
  ```json
173
- { "servers": { "memoryintelligence": { "type": "stdio", "command": "mi-mcp" } } }
205
+ { "servers": { "mi-local": { "type": "stdio", "command": "mi-mcp" } } }
174
206
  ```
175
207
 
176
208
  Then open Copilot Chat in **Agent** mode — the memory tools only appear there.
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "memoryintelligence-mcp"
7
- version = "0.2.5"
7
+ version = "0.2.7"
8
8
  description = "MCP server for MemoryIntelligence — give Claude a memory you own, set up in one command"
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
@@ -1,3 +1,3 @@
1
1
  """MI MCP Server — MemoryIntelligence tools for Claude."""
2
2
 
3
- __version__ = "0.2.5"
3
+ __version__ = "0.2.7"
@@ -41,11 +41,39 @@ from pathlib import Path
41
41
  from . import __version__, paths
42
42
  from .config import load_opt_in_paths
43
43
 
44
- SERVER_KEY = "memoryintelligence"
45
- # Pre-0.1.8 server ids we replace on wire so an upgrade leaves no orphaned entry.
46
- # (0.1.7 and earlier registered the server as "memory-intelligence" — the one
47
- # dash-seam that didn't match the brand/package "memoryintelligence".)
48
- LEGACY_SERVER_KEYS = ("memory-intelligence",)
44
+ # "mi-local" (#1320): the local stdio server's config id. It was
45
+ # "memoryintelligence" through 0.2.5, which collided with the REMOTE MCP surface
46
+ # (announced "memoryintelligence-remote" but added to claude.ai/Desktop under the
47
+ # display name "memoryintelligence") — on a client hosting both, the two were
48
+ # indistinguishable and tool calls silently resolved to the wrong surface.
49
+ SERVER_KEY = "mi-local"
50
+ # Older server ids we migrate on wire so an upgrade leaves no orphaned entry:
51
+ # "memoryintelligence" — 0.1.8 … 0.2.5 (renamed to "mi-local" in 0.2.6, #1320)
52
+ # "memory-intelligence" — 0.1.7 and earlier
53
+ # Migration is GUARDED: an entry under a legacy id is only removed/renamed when it
54
+ # actually points at the mi-mcp launcher (see _is_mi_launcher_entry) — an entry a
55
+ # user pointed elsewhere (e.g. a remote connector they named "memoryintelligence")
56
+ # is never touched.
57
+ LEGACY_SERVER_KEYS = ("memoryintelligence", "memory-intelligence")
58
+
59
+
60
+ def _is_mi_launcher_entry(entry: object) -> bool:
61
+ """True when a client-config server entry points at OUR launcher.
62
+
63
+ Recognizes every shape mi-mcp has ever written: the run-mi-mcp.sh wrapper
64
+ (Code/Cursor/VS Code), the sandbox-safe ``python -m mi_mcp`` Desktop entry,
65
+ and a bare ``mi-mcp`` binary path. Anything else is not ours to migrate.
66
+ """
67
+ if not isinstance(entry, dict):
68
+ return False
69
+ blob = " ".join(
70
+ [str(entry.get("command", "")), *(str(a) for a in (entry.get("args") or []))]
71
+ )
72
+ return (
73
+ "run-mi-mcp" in blob
74
+ or "mi_mcp" in blob
75
+ or blob.rstrip().endswith("mi-mcp")
76
+ )
49
77
 
50
78
  # Wrapper rendered by `wire`. __MI_MCP_BIN__ is replaced with the absolute path
51
79
  # to the mi-mcp binary (resolved at wire time) so the host can spawn it even
@@ -187,9 +215,18 @@ def _wire_code_via_cli(home: Path, wrapper: Path, dry_run: bool) -> bool:
187
215
  print(f" would run: {' '.join(add_cmd)}")
188
216
  return True
189
217
  # idempotent + migrate: drop any existing entry — current id AND the legacy
190
- # pre-0.1.8 ids — before re-adding, so an upgrade leaves no orphan.
191
- for key in (SERVER_KEY, *LEGACY_SERVER_KEYS):
192
- subprocess.run([claude, "mcp", "remove", key], capture_output=True, text=True)
218
+ # ids — before re-adding, so an upgrade leaves no orphan. Legacy ids are only
219
+ # removed when `claude mcp get` shows they point at OUR launcher (#1320): a
220
+ # server the user registered under "memoryintelligence" that isn't mi-mcp
221
+ # (e.g. the remote connector) must not be deleted out from under them.
222
+ subprocess.run([claude, "mcp", "remove", SERVER_KEY], capture_output=True, text=True)
223
+ for key in LEGACY_SERVER_KEYS:
224
+ g = subprocess.run([claude, "mcp", "get", key], capture_output=True, text=True)
225
+ blob = (g.stdout or "") + (g.stderr or "")
226
+ # "mi-mcp" also matches the wrapper's "run-mi-mcp.sh".
227
+ if g.returncode == 0 and ("mi-mcp" in blob or "mi_mcp" in blob):
228
+ subprocess.run([claude, "mcp", "remove", key], capture_output=True, text=True)
229
+ print(f" migrated legacy id {key} → {SERVER_KEY}")
193
230
  r = subprocess.run(add_cmd, capture_output=True, text=True)
194
231
  if r.returncode != 0:
195
232
  print(f" ! claude mcp add failed ({r.stderr.strip()[:160]}); falling back to file")
@@ -303,17 +340,39 @@ def do_wire(home: Path, surfaces: list[str], dry_run: bool,
303
340
  cfg_key = _surface_key(s)
304
341
  cfg = _load_json(cfg_path)
305
342
  servers = cfg.setdefault(cfg_key, {})
306
- # Migrate: drop any pre-0.1.8 id (e.g. "memory-intelligence") so the
307
- # rename to "memoryintelligence" doesn't leave a duplicate/orphan entry.
308
- migrated = [k for k in LEGACY_SERVER_KEYS if servers.pop(k, None) is not None]
343
+ # Migrate: drop any legacy id ("memoryintelligence" ≤0.2.5, or the
344
+ # pre-0.1.8 "memory-intelligence") so the rename to "mi-local" (#1320)
345
+ # doesn't leave a duplicate/orphan entry. GUARDED: only entries that
346
+ # point at the mi-mcp launcher are ours to migrate — a legacy-named
347
+ # entry the user pointed elsewhere is left exactly as it is.
348
+ migrated, foreign = [], []
349
+ # Keep the first migrated entry's contents: a ≤0.2.5 user's overrides
350
+ # (MI_VAULT, MI_MCP_OPT_IN_ALL) live under the LEGACY key, and the
351
+ # desktop branch below reads `prior` to preserve exactly those. Popping
352
+ # without remembering silently reset them on upgrade (Copilot, #1326).
353
+ legacy_prior = None
354
+ for k in LEGACY_SERVER_KEYS:
355
+ if k not in servers:
356
+ continue
357
+ if _is_mi_launcher_entry(servers[k]):
358
+ popped = servers.pop(k)
359
+ if legacy_prior is None:
360
+ legacy_prior = popped
361
+ migrated.append(k)
362
+ else:
363
+ foreign.append(k)
309
364
  if migrated:
310
365
  print(f" {s:8} migrated id {', '.join(migrated)} → {SERVER_KEY}")
366
+ if foreign:
367
+ print(f" {s:8} left {', '.join(foreign)} untouched — not an mi-mcp launcher entry")
311
368
  # Build this surface's entry. capture_anywhere is tri-state: True enables,
312
369
  # False disables, None preserves the current setting (so a plain re-wire
313
370
  # never silently flips a capture choice the user made).
314
371
  env: dict[str, str] = {}
315
372
  if s == "desktop":
316
- prior = servers.get(SERVER_KEY)
373
+ # A mi-local entry wins; else the legacy entry we just migrated —
374
+ # so a ≤0.2.5 upgrade carries its env forward instead of resetting it.
375
+ prior = servers.get(SERVER_KEY) or legacy_prior
317
376
  prior_env = prior.get("env") if isinstance(prior, dict) else None
318
377
  # D7: point the local .umo vault at the MemorySpace Desktop vault (~/Somewhere) so
319
378
  # both surfaces resolve ONE vault. The shell wrapper used to set this at launch;
@@ -465,10 +524,20 @@ def cmd_doctor(argv: list[str]) -> int:
465
524
  for s, p in _surface_paths(home).items():
466
525
  servers = _load_json(p).get(_surface_key(s), {})
467
526
  wired = SERVER_KEY in servers
468
- legacy = [k for k in LEGACY_SERVER_KEYS if k in servers]
527
+ # #1320 migration detection: a legacy id ("memoryintelligence" ≤0.2.5,
528
+ # "memory-intelligence" ≤0.1.7) counts only when its entry actually points
529
+ # at the mi-mcp launcher — an identically-named entry the user pointed at
530
+ # something else (e.g. the remote connector) is not ours and is ignored.
531
+ legacy = [
532
+ k for k in LEGACY_SERVER_KEYS
533
+ if k in servers and _is_mi_launcher_entry(servers[k])
534
+ ]
469
535
  detail = str(p) if wired else "(not wired)"
470
536
  if legacy and not wired:
471
- detail = f"legacy id {', '.join(legacy)} present — run `mi-mcp wire` to migrate"
537
+ detail = (f"legacy id {', '.join(legacy)} points at the mi-mcp launcher — "
538
+ f"run `mi-mcp wire` to rename it to {SERVER_KEY} (#1320)")
539
+ elif legacy:
540
+ detail += f" (stale legacy id {', '.join(legacy)} also present — `mi-mcp wire` cleans it up)"
472
541
  check(f"{s} wired", wired, detail, critical=False)
473
542
 
474
543
  # #1135 — the escalated-user failure this check exists to catch in ONE
@@ -124,9 +124,13 @@ class MIClient:
124
124
  json: dict | None = None,
125
125
  params: dict | None = None,
126
126
  idempotent: bool = False,
127
+ headers: dict[str, str] | None = None,
127
128
  ) -> dict[str, Any]:
128
129
  """Make an API request and return the JSON response.
129
130
 
131
+ ``headers`` are merged over the client's defaults for this one request
132
+ (used by the workspace-routing headers — see ``_workspace_headers``).
133
+
130
134
  Idempotent reads (ask/list/explain/verify/match/account_info) are retried
131
135
  on a read timeout or a transient 5xx, with exponential backoff. The hosted
132
136
  API can intermittently cold-start or saturate
@@ -140,7 +144,9 @@ class MIClient:
140
144
  for attempt in range(attempts):
141
145
  is_last = attempt + 1 >= attempts
142
146
  try:
143
- resp = await self._http.request(method, path, json=json, params=params)
147
+ resp = await self._http.request(
148
+ method, path, json=json, params=params, headers=headers
149
+ )
144
150
  except httpx.TimeoutException:
145
151
  if is_last:
146
152
  raise
@@ -169,6 +175,30 @@ class MIClient:
169
175
 
170
176
  # ----- Core operations -----
171
177
 
178
+ @staticmethod
179
+ def _workspace_headers(workspace_id: str | None) -> dict[str, str] | None:
180
+ """Headers that route a request to a specific workspace (#385 UC1).
181
+
182
+ BOTH names are sent on purpose — the API has two headers for this one
183
+ concept, and which one is honored depends on the auth plane:
184
+
185
+ * ``X-MI-Workspace`` — the API-KEY plane (``deps.py::get_api_key``, #736).
186
+ This is the one that matters for this package, which always authenticates
187
+ with an ``mi_sk_*`` / ``mi_beta_*`` key.
188
+ * ``X-Workspace-Id`` — the JWT plane (``deps.py::get_api_key_or_jwt``),
189
+ which is what the REMOTE MCP surface (``api/public/mcp_resource.py``)
190
+ sends. ``get_api_key_or_jwt`` forwards only ``X-MI-Workspace`` down to
191
+ ``get_api_key``, so a key-authenticated ``X-Workspace-Id`` is IGNORED.
192
+
193
+ Sending both means routing is correct on either plane instead of silently
194
+ no-op'ing if this client is ever pointed at a JWT-authenticated deployment.
195
+ The unhonored name is inert, and both planes fail CLOSED (403) on a
196
+ workspace the caller is not a member of — enforcement stays server-side.
197
+ """
198
+ if not workspace_id:
199
+ return None
200
+ return {"X-MI-Workspace": workspace_id, "X-Workspace-Id": workspace_id}
201
+
172
202
  async def capture(
173
203
  self,
174
204
  content: str,
@@ -176,6 +206,7 @@ class MIClient:
176
206
  source: str | None = None,
177
207
  scope: str | None = None,
178
208
  scope_id: str | None = None,
209
+ workspace_id: str | None = None,
179
210
  retention_policy: str | None = None,
180
211
  pii_handling: str | None = None,
181
212
  metadata: dict | None = None,
@@ -188,6 +219,14 @@ class MIClient:
188
219
  capture persists as a parent + one child per claim, each independently
189
220
  recallable. Short single-claim captures stay a single UMO (the server's
190
221
  <=1-claim guard), so this is safe to leave on by default.
222
+
223
+ ``workspace_id`` (#385 UC1) routes the capture to a specific workspace via
224
+ the routing headers. Omit it and the capture goes to the caller's HOME
225
+ workspace (the server's agent-source home-binding), which is personal for
226
+ most users. The server validates membership and 403s a workspace the caller
227
+ does not belong to — this client cannot route anywhere it shouldn't.
228
+ ``scope``/``scope_id`` are a DIFFERENT axis (governance scope in the request
229
+ body); they do not route between workspaces.
191
230
  """
192
231
  payload: dict[str, Any] = {
193
232
  "content": content,
@@ -210,7 +249,10 @@ class MIClient:
210
249
  if metadata:
211
250
  payload["metadata"] = metadata
212
251
 
213
- return await self._request("POST", "/v1/process", json=payload)
252
+ return await self._request(
253
+ "POST", "/v1/process", json=payload,
254
+ headers=self._workspace_headers(workspace_id),
255
+ )
214
256
 
215
257
  async def ask(
216
258
  self,
@@ -218,6 +260,7 @@ class MIClient:
218
260
  *,
219
261
  scope: str | None = None,
220
262
  scope_id: str | None = None,
263
+ workspace_id: str | None = None,
221
264
  limit: int = 10,
222
265
  offset: int = 0,
223
266
  explain: str | bool = "none",
@@ -226,7 +269,13 @@ class MIClient:
226
269
  topics: list[str] | None = None,
227
270
  entities: list[str] | None = None,
228
271
  ) -> dict[str, Any]:
229
- """POST /v1/memories/query — semantic search across memories."""
272
+ """POST /v1/memories/query — semantic search across memories.
273
+
274
+ ``workspace_id`` (#385 UC2) targets a workspace you are a member of; omit
275
+ for personal (owner-scoped) search. Same routing headers as capture. Note
276
+ the server only *widens* the read to every member's memories when its
277
+ workspace read-isolation flag is on — see ``health()``.
278
+ """
230
279
  payload: dict[str, Any] = {
231
280
  "query": query,
232
281
  "scope": scope or self._config.default_scope,
@@ -253,7 +302,8 @@ class MIClient:
253
302
  payload["entities"] = entities
254
303
 
255
304
  return await self._request(
256
- "POST", "/v1/memories/query", json=payload, idempotent=True
305
+ "POST", "/v1/memories/query", json=payload, idempotent=True,
306
+ headers=self._workspace_headers(workspace_id),
257
307
  )
258
308
 
259
309
  async def list_memories(
@@ -262,12 +312,33 @@ class MIClient:
262
312
  limit: int = 20,
263
313
  offset: int = 0,
264
314
  scope: str | None = None,
315
+ workspace_id: str | None = None,
265
316
  ) -> dict[str, Any]:
266
- """GET /v1/memories — list UMOs with pagination."""
317
+ """GET /v1/memories — list UMOs with pagination.
318
+
319
+ ``workspace_id`` (#385 UC2) targets a workspace you are a member of; omit
320
+ for personal. See :meth:`ask` for the read-isolation caveat.
321
+ """
267
322
  params: dict[str, Any] = {"limit": limit, "offset": offset}
268
323
  if scope:
269
324
  params["scope"] = scope
270
- return await self._request("GET", "/v1/memories", params=params, idempotent=True)
325
+ return await self._request(
326
+ "GET", "/v1/memories", params=params, idempotent=True,
327
+ headers=self._workspace_headers(workspace_id),
328
+ )
329
+
330
+ async def health(self) -> dict[str, Any]:
331
+ """GET /health — server status + capability discovery.
332
+
333
+ Used for one thing here: reading
334
+ ``capabilities.workspace_read_isolation.enabled``, which decides whether a
335
+ workspace-targeted READ actually returns every member's memories or only
336
+ the caller's own. Without it a workspace read looks successful and
337
+ identical to a personal one, and any "searched the team workspace" claim
338
+ would be unverifiable. Unauthenticated on the server side; we send the
339
+ client's normal headers anyway (harmless).
340
+ """
341
+ return await self._request("GET", "/health", idempotent=True)
271
342
 
272
343
  async def explain(self, umo_id: str, *, level: str = "full") -> dict[str, Any]:
273
344
  """GET /v1/memories/{id}/explain — UMO introspection."""
@@ -378,3 +449,13 @@ class MIClient:
378
449
  async def account_info(self) -> dict[str, Any]:
379
450
  """GET /v1/accounts/me — get current account info and key status."""
380
451
  return await self._request("GET", "/v1/accounts/me", idempotent=True)
452
+
453
+ async def workspaces(self) -> dict[str, Any]:
454
+ """GET /v1/workspaces — list the caller's workspaces (mi_workspaces, #1320).
455
+
456
+ Returns ``{"workspaces": [...], "count": N}`` where each entry carries
457
+ id, name, the caller's role, and member_count — the routing directory
458
+ for workspace-targeted captures. Same endpoint the remote MCP surface's
459
+ mi_workspaces calls, so both surfaces answer identically.
460
+ """
461
+ return await self._request("GET", "/v1/workspaces", idempotent=True)
@@ -63,7 +63,7 @@ class MIConfig:
63
63
  host: str = "127.0.0.1" # loopback only; network transports are not part of v0
64
64
  port: int = 8100
65
65
 
66
- # Tool surface — v0 exposes 3 tools by default; MI_MCP_FULL=1 exposes all 10 (#256).
66
+ # Tool surface — v0 exposes 7 tools by default; MI_MCP_FULL=1 exposes all 11 (#256, #1320).
67
67
  full_tools: bool = False
68
68
 
69
69
  # Local reads (#432 Phase 1): when True AND a built index sidecar exists, route
@@ -84,7 +84,7 @@ class MIConfig:
84
84
  MI_TRANSPORT — stdio | sse | streamable-http (default: stdio)
85
85
  MI_HOST — bind host for SSE/HTTP (default: 127.0.0.1, loopback only)
86
86
  MI_PORT — bind port for SSE/HTTP (default: 8100)
87
- MI_MCP_FULL — "1" exposes all 10 tools; otherwise only the core set (#256)
87
+ MI_MCP_FULL — "1" exposes all 11 tools; otherwise only the core set (#256)
88
88
  MI_MCP_LOCAL — "1" routes mi_ask/mi_list to the local vault index when
89
89
  one is built (network-free); falls back to cloud on error
90
90
  """
@@ -11,6 +11,13 @@ Tools map 1:1 to the canonical SDK surface:
11
11
  mi_upload → mi.upload() — media file capture
12
12
  mi_match → mi.match() — compare two UMOs
13
13
  mi_account → account info — key status and quotas
14
+ mi_workspaces → workspace list — id, name, role, member_count (routing)
15
+
16
+ Server name: "mi-local" (#1320). The REMOTE MCP surface announces
17
+ "memoryintelligence-remote"; the local stdio server used to announce plain
18
+ "memoryintelligence", so a client hosting both could not tell them apart and
19
+ silently resolved to the wrong one. Distinct names make the answering surface
20
+ visible in initialize/ListTools.
14
21
 
15
22
  Resources expose UMOs as readable content:
16
23
  mi://memories — list of all memories
@@ -40,7 +47,7 @@ from .config import MIConfig, capture_gate
40
47
  logger = logging.getLogger("mi_mcp")
41
48
 
42
49
  # v0 tool surface (resolves #256): only these tools are visible by default.
43
- # Set MI_MCP_FULL=1 to expose the full 10-tool surface. Narrowing the default
50
+ # Set MI_MCP_FULL=1 to expose the full 11-tool surface. Narrowing the default
44
51
  # surface reduces agent decision-noise; the hidden tools stay callable by name.
45
52
  # mi_forget is exposed so owners can delete their own memories; it is guarded by
46
53
  # confirm=true + an ownership-checked soft-delete with a recovery grace window.
@@ -50,7 +57,15 @@ logger = logging.getLogger("mi_mcp")
50
57
  # mi_verify joins the default surface (0.2.4): the provenance-proof tool is the
51
58
  # product's core claim ("we cite, we don't hallucinate") — hiding it behind
52
59
  # MI_MCP_FULL meant the differentiator was invisible on the surface agents use.
53
- V0_VISIBLE_TOOLS = frozenset({"mi_capture", "mi_upload", "mi_ask", "mi_list", "mi_forget", "mi_verify"})
60
+ # mi_workspaces joins the default surface (0.2.6, #1320): workspace routing is a
61
+ # first-class concept (mi_capture takes workspace_id — 0.2.7, #385 UC1; NOT
62
+ # scope/scope_id, which is the separate governance-scope axis), and tool-surface
63
+ # parity with the remote MCP means "does mi_workspaces exist" answers the same
64
+ # both ways.
65
+ V0_VISIBLE_TOOLS = frozenset({
66
+ "mi_capture", "mi_upload", "mi_ask", "mi_list", "mi_forget", "mi_verify",
67
+ "mi_workspaces",
68
+ })
54
69
 
55
70
  # Write tools — gated by the cwd consent allowlist (~/.memoryintelligence/mcp/opt-in-paths, Story 8).
56
71
  # Read tools are never gated; reading your own memory is always safe.
@@ -73,6 +88,8 @@ _TOOL_ANNOTATIONS = {
73
88
  "mi_upload": ToolAnnotations(title="Upload media", readOnlyHint=False),
74
89
  "mi_match": ToolAnnotations(title="Compare memories", readOnlyHint=True),
75
90
  "mi_account": ToolAnnotations(title="Account info", readOnlyHint=True),
91
+ # Matches the remote surface's annotation for the same tool (#1321).
92
+ "mi_workspaces": ToolAnnotations(title="List workspaces", readOnlyHint=True),
76
93
  }
77
94
 
78
95
 
@@ -250,7 +267,11 @@ async def _route_ask(config: MIConfig, client: MIClient, arguments: dict) -> Any
250
267
  limit = arguments.get("limit", 10)
251
268
  offset = arguments.get("offset", 0)
252
269
  advanced = any(arguments.get(k) for k in ("date_from", "date_to", "topics", "scope_id"))
253
- if localreads.available(config) and not advanced:
270
+ # A workspace-targeted read MUST go to the cloud (#385 UC2). The on-device index
271
+ # has no workspace concept at all — serving it locally would answer from personal
272
+ # memories while the response claimed a workspace scope. Same reason `advanced`
273
+ # forces cloud: local v0 cannot honor the filter, so it must not pretend to.
274
+ if localreads.available(config) and not advanced and not arguments.get("workspace_id"):
254
275
  try:
255
276
  return localreads.ask_local(
256
277
  arguments["query"], limit=limit, offset=offset,
@@ -261,7 +282,8 @@ async def _route_ask(config: MIConfig, client: MIClient, arguments: dict) -> Any
261
282
  return await client.ask(
262
283
  query=arguments["query"], limit=limit, offset=offset,
263
284
  explain=arguments.get("explain", "none"), scope=arguments.get("scope"),
264
- scope_id=arguments.get("scope_id"), date_from=arguments.get("date_from"),
285
+ scope_id=arguments.get("scope_id"), workspace_id=arguments.get("workspace_id"),
286
+ date_from=arguments.get("date_from"),
265
287
  date_to=arguments.get("date_to"), topics=arguments.get("topics"),
266
288
  entities=arguments.get("entities"),
267
289
  )
@@ -270,12 +292,219 @@ async def _route_ask(config: MIConfig, client: MIClient, arguments: dict) -> Any
270
292
  async def _route_list(config: MIConfig, client: MIClient, arguments: dict) -> Any:
271
293
  limit = arguments.get("limit", 20)
272
294
  offset = arguments.get("offset", 0)
273
- if localreads.available(config):
295
+ # See _route_ask: a workspace target is not answerable from the local index.
296
+ if localreads.available(config) and not arguments.get("workspace_id"):
274
297
  try:
275
298
  return localreads.list_local(limit=limit, offset=offset)
276
299
  except Exception as e:
277
300
  logger.warning("local mi_list failed (%s) — falling back to cloud", e)
278
- return await client.list_memories(limit=limit, offset=offset, scope=arguments.get("scope"))
301
+ return await client.list_memories(
302
+ limit=limit, offset=offset, scope=arguments.get("scope"),
303
+ workspace_id=arguments.get("workspace_id"),
304
+ )
305
+
306
+
307
+ # =============================================================================
308
+ # Workspace READS for mi_ask / mi_list (#385 UC2) — module-level, testable
309
+ # =============================================================================
310
+ # Symmetric with mi_capture's routing (D3 = option A): omit workspace_id → personal
311
+ # (owner-scoped, the default); pass one you're a member of → that workspace. Reads
312
+ # are non-destructive, so there is NO confirm — but a non-member target is REFUSED
313
+ # rather than silently downgraded to personal, so the reported scope is never a lie.
314
+ #
315
+ # ⚠️ THE THING THIS SURFACE MUST NOT OVERCLAIM.
316
+ # Whether a workspace read actually returns OTHER members' memories is decided
317
+ # server-side by the read-isolation flag (`MI_WORKSPACE_READ_ISOLATION`, #736),
318
+ # which is **OFF by default** and blocked behind a pre-flip audit (#1112). With it
319
+ # off, `auth["workspace_id"]` is None, so `workspace_scope` is False and the read
320
+ # stays owner-scoped — a member-targeted read returns EXACTLY what a personal one
321
+ # returns. Nothing in the read response reveals which happened.
322
+ #
323
+ # So we ask the server (`/health` → capabilities.workspace_read_isolation) and put
324
+ # the answer in the scope block as `member_wide_reads`. An agent that reads
325
+ # `shared: true, member_count: 4` would otherwise reasonably tell the user "I
326
+ # searched the whole team workspace" when it searched only their own memories.
327
+
328
+ _WIDENING_UNKNOWN = "unknown"
329
+ _widening_cache: dict = {} # base_url -> bool; per-process, only cached on success
330
+
331
+
332
+ async def _member_wide_reads_enabled(client: MIClient):
333
+ """True/False if the server told us, else ``"unknown"`` — never a guess.
334
+
335
+ Cached per process: the flag is an env var, so it cannot change without a
336
+ redeploy, and a read must not pay a /health round-trip every call.
337
+ """
338
+ key = str(getattr(client, "_config", None) and client._config.base_url)
339
+ if key in _widening_cache:
340
+ return _widening_cache[key]
341
+ try:
342
+ health = await client.health()
343
+ caps = (health or {}).get("capabilities") or {}
344
+ enabled = (caps.get("workspace_read_isolation") or {}).get("enabled")
345
+ except Exception as e:
346
+ logger.warning("workspace read-isolation probe failed (%s) — reporting unknown", e)
347
+ return _WIDENING_UNKNOWN
348
+ if not isinstance(enabled, bool):
349
+ # An older server that predates the capability. Do NOT infer a value —
350
+ # "unknown" is the honest answer and stays uncached so a later deploy
351
+ # can start answering.
352
+ return _WIDENING_UNKNOWN
353
+ _widening_cache[key] = enabled
354
+ return enabled
355
+
356
+
357
+ def _with_scope(shaped: Any, scope: dict) -> Any:
358
+ """Attach the read's scope block to a shaped result — workspace reads only.
359
+
360
+ A PERSONAL read is returned byte-identical to before UC2 existed: no wrapper,
361
+ no extra key. The rule an agent can rely on is "a `scope` block means you
362
+ targeted a workspace; its absence means personal", and existing behaviour is
363
+ untouched for every call that doesn't opt in.
364
+
365
+ `_shape_ask` yields a dict (gets the key) and `_shape_list` yields a bare list
366
+ (gets wrapped in `{scope, items}`), so both carry it the same way.
367
+ """
368
+ if scope.get("scope") != "workspace":
369
+ return shaped
370
+ if isinstance(shaped, dict):
371
+ return {**shaped, "scope": scope}
372
+ return {"scope": scope, "items": shaped}
373
+
374
+
375
+ async def _resolve_read_scope(client: MIClient, workspace_id: str | None):
376
+ """Resolve the scope of a read. Returns ``(scope, blocked)``.
377
+
378
+ ``blocked`` is an error payload to return INSTEAD of reading, or None.
379
+ """
380
+ if not workspace_id:
381
+ return {"scope": "personal", "shared": False}, None
382
+
383
+ listing = await client.workspaces()
384
+ entries = (listing or {}).get("workspaces") or []
385
+ info = next(
386
+ (w for w in entries if isinstance(w, dict) and w.get("workspace_id") == workspace_id),
387
+ None,
388
+ )
389
+ if info is None:
390
+ return None, {
391
+ "status": "not_a_member",
392
+ "message": (
393
+ "You are not a member of the requested workspace — call mi_workspaces "
394
+ "to see the ones you can read, or omit workspace_id to search your "
395
+ "personal memories."
396
+ ),
397
+ }
398
+
399
+ member_count = info.get("member_count") or 1
400
+ widening = await _member_wide_reads_enabled(client)
401
+ scope = {
402
+ "scope": "workspace",
403
+ "workspace_id": workspace_id,
404
+ "name": info.get("name"),
405
+ "role": info.get("role"),
406
+ "shared": member_count > 1,
407
+ "member_count": member_count,
408
+ # The honest bit — see the block comment above.
409
+ "member_wide_reads": widening,
410
+ }
411
+ if widening is not True and member_count > 1:
412
+ scope["note"] = (
413
+ "This workspace has other members, but the server is NOT returning their "
414
+ "memories — workspace read-isolation is "
415
+ + ("off" if widening is False else "of unknown state")
416
+ + " on this deployment, so this read is scoped to your own memories only. "
417
+ "Do not tell the user you searched the whole team workspace."
418
+ )
419
+ return scope, None
420
+
421
+
422
+ # =============================================================================
423
+ # Workspace routing for mi_capture (#385 UC1 + UC1.5) — module-level, testable
424
+ # =============================================================================
425
+ # Mirrors the REMOTE surface's contract (api/public/mcp_resource.py::_capture) so
426
+ # both MCP surfaces route captures identically:
427
+ #
428
+ # 1. PERSONAL IS THE DEFAULT. No workspace_id → no routing header, no extra
429
+ # round-trip, behaviour unchanged from before this existed.
430
+ # 2. A write to a genuinely SHARED workspace (>1 member) requires an explicit
431
+ # confirm and saves NOTHING without it — a single silent call can never post
432
+ # to a team space. Because the agent must seek approval per conversation, a
433
+ # brand-new chat cannot inherit a shared write.
434
+ # 3. EVERY routed capture NAMES its destination in the response, so a capture is
435
+ # never blind about where it landed.
436
+ #
437
+ # The real authorization gate is server-side (deps.py validates membership and
438
+ # 403s a non-member). This mirrors it so the *feedback* is accurate — the agent
439
+ # should never tell the user "saved to Somewhere Inc" when the server refused.
440
+
441
+ async def _resolve_capture_destination(client: MIClient, workspace_id: str | None):
442
+ """Resolve where a capture will land. Returns ``(destination, blocked)``.
443
+
444
+ ``blocked`` is a confirm_required payload to return INSTEAD of capturing, or
445
+ None to proceed. Raises MIAPIError if the workspace lookup itself fails — a
446
+ capture is never routed on an unverified destination.
447
+ """
448
+ if not workspace_id:
449
+ return {"scope": "personal", "shared": False}, None
450
+
451
+ listing = await client.workspaces()
452
+ entries = (listing or {}).get("workspaces") or []
453
+ info = next(
454
+ (w for w in entries if isinstance(w, dict) and w.get("workspace_id") == workspace_id),
455
+ None,
456
+ )
457
+ if info is None:
458
+ # Not a member (or no such workspace) — refuse locally rather than let the
459
+ # server 403 with a message the agent would have to interpret. Same
460
+ # least-disclosure posture as the API: we don't say which of the two it is.
461
+ return None, {
462
+ "status": "not_a_member",
463
+ "message": (
464
+ "You are not a member of the requested workspace — call mi_workspaces "
465
+ "to see the ones you can capture into, or omit workspace_id to keep "
466
+ "this memory personal."
467
+ ),
468
+ }
469
+
470
+ member_count = info.get("member_count") or 1
471
+ destination = {
472
+ "scope": "workspace",
473
+ "workspace_id": workspace_id,
474
+ "name": info.get("name"),
475
+ "role": info.get("role"),
476
+ "shared": member_count > 1,
477
+ "member_count": member_count,
478
+ }
479
+ return destination, None
480
+
481
+
482
+ def _confirmed(arguments: dict) -> bool:
483
+ """True only when `confirm` is the LITERAL boolean true.
484
+
485
+ Not truthiness. The tool schema declares a boolean, but the caller is a language
486
+ model and an argument can arrive as the STRING ``"false"`` — for which ``bool()``
487
+ is True, opening a gate the user never opened. Every confirm gate on this surface
488
+ (the destructive-tool check for mi_forget, and the shared-write check for
489
+ mi_capture) fails closed on anything that is not literally ``true``.
490
+ """
491
+ return arguments.get("confirm") is True
492
+
493
+
494
+ def _shared_write_confirm_required(destination: dict, confirm: bool) -> dict | None:
495
+ """The UC1.5 hard gate: a SHARED destination without confirm=true saves nothing."""
496
+ if not destination.get("shared") or confirm:
497
+ return None
498
+ return {
499
+ "status": "confirm_required",
500
+ "destination": destination,
501
+ "message": (
502
+ f"This will post to '{destination.get('name')}', a SHARED workspace with "
503
+ f"{destination.get('member_count')} members — everyone in it will see it. "
504
+ f"Nothing has been saved. Confirm with the user, then re-call mi_capture "
505
+ f"with confirm=true. Omit workspace_id to keep it personal instead."
506
+ ),
507
+ }
279
508
 
280
509
 
281
510
  # =============================================================================
@@ -333,7 +562,11 @@ def create_server(config: MIConfig | None = None) -> Server:
333
562
  config = MIConfig.from_env()
334
563
 
335
564
  client = MIClient(config)
336
- server = Server("memoryintelligence", instructions=SERVER_INSTRUCTIONS)
565
+ # "mi-local", NOT "memoryintelligence" (#1320): the remote MCP announces
566
+ # "memoryintelligence-remote", and a plain "memoryintelligence" here made the
567
+ # two surfaces indistinguishable on any client hosting both — the local's
568
+ # tools silently masqueraded as the remote's during the 2026-08-02 debug.
569
+ server = Server("mi-local", instructions=SERVER_INSTRUCTIONS)
337
570
 
338
571
  if os.environ.get("MI_MCP_OPT_IN_ALL") == "1":
339
572
  logger.warning(
@@ -398,7 +631,27 @@ def create_server(config: MIConfig | None = None) -> Server:
398
631
  "type": "string",
399
632
  "description": (
400
633
  "Scope identifier (required for client/project/team scopes). "
401
- "E.g., a project ULID."
634
+ "E.g., a project ULID. NOT a workspace — use workspace_id "
635
+ "to route this memory to a workspace."
636
+ ),
637
+ },
638
+ "workspace_id": {
639
+ "type": "string",
640
+ "description": (
641
+ "Target workspace ULID to route this memory to (e.g. a shared "
642
+ "team space). Omit to keep it PERSONAL (the default). Call "
643
+ "mi_workspaces to list your workspaces + IDs. You must be a "
644
+ "member; the server rejects anything else."
645
+ ),
646
+ },
647
+ "confirm": {
648
+ "type": "boolean",
649
+ "description": (
650
+ "Required to post into a SHARED workspace (>1 member). Without "
651
+ "it, mi_capture returns a confirm_required preview and saves "
652
+ "NOTHING — ask the user before setting confirm=true. Never set "
653
+ "it yourself for a shared workspace without the user's explicit "
654
+ "approval."
402
655
  ),
403
656
  },
404
657
  "retention_policy": {
@@ -466,7 +719,19 @@ def create_server(config: MIConfig | None = None) -> Server:
466
719
  },
467
720
  "scope_id": {
468
721
  "type": "string",
469
- "description": "Scope identifier for filtering.",
722
+ "description": "Scope identifier for filtering. NOT a workspace.",
723
+ },
724
+ "workspace_id": {
725
+ "type": "string",
726
+ "description": (
727
+ "Search a workspace you are a member of instead of your "
728
+ "personal memories. Omit for PERSONAL (the default). Call "
729
+ "mi_workspaces for IDs. The result's `scope` block reports "
730
+ "what was actually searched — including `member_wide_reads`, "
731
+ "which is false when the server is NOT returning other "
732
+ "members' memories. Read it before telling the user you "
733
+ "searched a whole team workspace."
734
+ ),
470
735
  },
471
736
  "date_from": {
472
737
  "type": "string",
@@ -513,7 +778,17 @@ def create_server(config: MIConfig | None = None) -> Server:
513
778
  "scope": {
514
779
  "type": "string",
515
780
  "enum": ["user", "client", "project", "team", "org", "all"],
516
- "description": "Scope to list. Default: 'user'.",
781
+ "description": "Scope to list. Default: 'user'. NOT a workspace.",
782
+ },
783
+ "workspace_id": {
784
+ "type": "string",
785
+ "description": (
786
+ "List a workspace you are a member of instead of your "
787
+ "personal memories. Omit for PERSONAL (the default). Call "
788
+ "mi_workspaces for IDs. See the result's `scope` block — "
789
+ "`member_wide_reads` tells you whether other members' "
790
+ "memories are actually included."
791
+ ),
517
792
  },
518
793
  },
519
794
  },
@@ -718,15 +993,31 @@ def create_server(config: MIConfig | None = None) -> Server:
718
993
  "properties": {},
719
994
  },
720
995
  ),
996
+ Tool(
997
+ # Mirrors the remote MCP surface's tool of the same name (#1320):
998
+ # both surfaces answer "what workspaces do I have" identically.
999
+ name="mi_workspaces",
1000
+ description=(
1001
+ "List the workspaces you can capture into and read from — id, "
1002
+ "name, your role, member count. Use a workspace's id as the "
1003
+ "workspace_id of mi_capture (route a memory there), mi_ask or "
1004
+ "mi_list (read it). The first entry is your default (home) "
1005
+ "workspace."
1006
+ ),
1007
+ inputSchema={
1008
+ "type": "object",
1009
+ "properties": {},
1010
+ },
1011
+ ),
721
1012
  ]
722
1013
  for _t in all_tools:
723
1014
  _t.annotations = _TOOL_ANNOTATIONS.get(_t.name)
724
1015
  if config.full_tools:
725
1016
  return all_tools
726
1017
  # v0 default: only the core tools (V0_VISIBLE_TOOLS — capture, upload, ask,
727
- # list, forget) are visible (resolves #256). MI_MCP_FULL=1 exposes all 10.
728
- # Hidden tools remain callable by name — decision-noise narrowing, not an
729
- # auth gate.
1018
+ # list, forget, verify, workspaces) are visible (resolves #256).
1019
+ # MI_MCP_FULL=1 exposes all 11. Hidden tools remain callable by name —
1020
+ # decision-noise narrowing, not an auth gate.
730
1021
  return [t for t in all_tools if t.name in V0_VISIBLE_TOOLS]
731
1022
 
732
1023
  # =========================================================================
@@ -761,7 +1052,7 @@ def create_server(config: MIConfig | None = None) -> Server:
761
1052
  }))]
762
1053
 
763
1054
  # Human-in-the-loop for destructive (irreversible) ops.
764
- if name in DESTRUCTIVE_TOOLS and arguments.get("confirm") is not True:
1055
+ if name in DESTRUCTIVE_TOOLS and not _confirmed(arguments):
765
1056
  logger.info(f"[CONFIRM] {name} requires confirm=true")
766
1057
  return [TextContent(type="text", text=_fmt({
767
1058
  "status": "confirmation_required",
@@ -796,6 +1087,32 @@ def create_server(config: MIConfig | None = None) -> Server:
796
1087
 
797
1088
  match name:
798
1089
  case "mi_capture":
1090
+ # Workspace routing (#385 UC1): resolve + name the destination
1091
+ # BEFORE writing, and hard-gate a shared-workspace write on an
1092
+ # explicit confirm (UC1.5). Personal (no workspace_id) costs no
1093
+ # extra round-trip and is unchanged.
1094
+ ws_id = arguments.get("workspace_id")
1095
+ destination, blocked = await _resolve_capture_destination(client, ws_id)
1096
+ if blocked is not None:
1097
+ return [TextContent(type="text", text=_fmt(blocked))]
1098
+ # _confirmed(), not bool(): a shared-workspace write is a hard
1099
+ # safety contract and `bool("false")` is True — see the helper.
1100
+ needs_confirm = _shared_write_confirm_required(
1101
+ destination, _confirmed(arguments)
1102
+ )
1103
+ if needs_confirm is not None:
1104
+ logger.info(
1105
+ "[WORKSPACE] mi_capture held for confirm — shared workspace %s "
1106
+ "(%s members); nothing saved",
1107
+ ws_id, destination.get("member_count"),
1108
+ )
1109
+ return [TextContent(type="text", text=_fmt(needs_confirm))]
1110
+ if destination.get("shared"):
1111
+ logger.info(
1112
+ "[WORKSPACE] confirmed shared-workspace capture ws=%s members=%s",
1113
+ ws_id, destination.get("member_count"),
1114
+ )
1115
+
799
1116
  # Claim-granular by default (#446); an agent can opt out per call.
800
1117
  # source: caller's own value wins; else the connector-origin tag
801
1118
  # from the gate (a no-project-cwd surface), else the config default.
@@ -804,22 +1121,39 @@ def create_server(config: MIConfig | None = None) -> Server:
804
1121
  source=arguments.get("source") or capture_source_hint,
805
1122
  scope=arguments.get("scope"),
806
1123
  scope_id=arguments.get("scope_id"),
1124
+ workspace_id=ws_id,
807
1125
  retention_policy=arguments.get("retention_policy"),
808
1126
  pii_handling=arguments.get("pii_handling"),
809
1127
  metadata=arguments.get("metadata"),
810
1128
  claim_granular=arguments.get("claim_granular", True),
811
1129
  claim_level=arguments.get("claim_level"),
812
1130
  )
1131
+ if isinstance(result, dict):
1132
+ result["destination"] = destination # where it actually landed
813
1133
  return [TextContent(type="text", text=_fmt(result))]
814
1134
 
815
1135
  case "mi_ask":
1136
+ # #385 UC2: resolve + report the read scope. A non-member target
1137
+ # is refused rather than silently downgraded to personal.
1138
+ scope, blocked = await _resolve_read_scope(
1139
+ client, arguments.get("workspace_id")
1140
+ )
1141
+ if blocked is not None:
1142
+ return [TextContent(type="text", text=_fmt(blocked))]
816
1143
  result = await _route_ask(config, client, arguments)
1144
+ shaped = _shape_ask(result, explain=arguments.get("explain", "none"))
817
1145
  return [TextContent(type="text", text=_fmt_untrusted(
818
- _shape_ask(result, explain=arguments.get("explain", "none"))))]
1146
+ _with_scope(shaped, scope)))]
819
1147
 
820
1148
  case "mi_list":
1149
+ scope, blocked = await _resolve_read_scope(
1150
+ client, arguments.get("workspace_id")
1151
+ )
1152
+ if blocked is not None:
1153
+ return [TextContent(type="text", text=_fmt(blocked))]
821
1154
  result = await _route_list(config, client, arguments)
822
- return [TextContent(type="text", text=_fmt_untrusted(_shape_list(result)))]
1155
+ return [TextContent(type="text", text=_fmt_untrusted(
1156
+ _with_scope(_shape_list(result), scope)))]
823
1157
 
824
1158
  case "mi_explain":
825
1159
  result = await client.explain(
@@ -836,7 +1170,7 @@ def create_server(config: MIConfig | None = None) -> Server:
836
1170
  # Destructive: honor the confirm gate the tool schema advertises.
837
1171
  # Without confirm=true, return confirmation_required and delete
838
1172
  # nothing — an injected or accidental call can't silently destroy.
839
- if not arguments.get("confirm"):
1173
+ if not _confirmed(arguments):
840
1174
  return [TextContent(type="text", text=_fmt({
841
1175
  "status": "confirmation_required",
842
1176
  "umo_id": arguments["umo_id"],
@@ -873,6 +1207,10 @@ def create_server(config: MIConfig | None = None) -> Server:
873
1207
  result = await client.account_info()
874
1208
  return [TextContent(type="text", text=_fmt(result))]
875
1209
 
1210
+ case "mi_workspaces":
1211
+ result = await client.workspaces()
1212
+ return [TextContent(type="text", text=_fmt(result))]
1213
+
876
1214
  case _:
877
1215
  return [TextContent(type="text", text=f"Unknown tool: {name}")]
878
1216