dsh-project-mcp 0.2.0

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.
package/README.md ADDED
@@ -0,0 +1,983 @@
1
+ # dsh-project-mcp
2
+
3
+ Per-project MCP servers for [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness).
4
+
5
+ DSH normally configures MCP once per **profile** (`cordis.patch.yml`), so every
6
+ session of the process sees the same servers. This plugin adds the missing
7
+ plane: a project declares its MCP servers in its own files, and those servers
8
+ are mounted **only for the sessions working in that project**.
9
+
10
+ Which files a project is read from is a **setting**: `localFiles` lists documents
11
+ relative to the project root, `globalFiles` lists the ones read before them. The
12
+ shipped default reads one document — `<project>/.dsh/mcp.json` — and nothing
13
+ global, so a project mounts exactly what it declares. A Kimi Code project (or any
14
+ other tool's file) is one config line away, never an implicit second source.
15
+
16
+ ```jsonc
17
+ // <project>/.dsh/mcp.json
18
+ {
19
+ "mcpServers": {
20
+ "rider": {
21
+ "type": "http",
22
+ "url": "http://127.0.0.1:64343/stream",
23
+ "headers": { "IJ_MCP_SERVER_PROJECT_PATH": "/abs/path/to/project/src/App" }
24
+ },
25
+ "playwright": { "command": "npx", "args": ["-y", "@playwright/mcp@latest"] },
26
+ "tracker": {
27
+ "command": "uvx",
28
+ "args": ["yandex-tracker-mcp@latest"],
29
+ "env": { "TRACKER_TOKEN": "${YANDEX_TOKEN}" }
30
+ }
31
+ }
32
+ }
33
+ ```
34
+
35
+ ## Table of contents
36
+
37
+ - [Install](#install)
38
+ - [Sources and priority](#sources-and-priority) — [entry mapping](#entry-mapping), [variables](#variables)
39
+ - [Configuration](#configuration) — [`profileWins`](#profilewins)
40
+ - [Runtime status](#runtime-status)
41
+ - [Usage counters](#usage-counters)
42
+ - [Tool policy: mode and pins](#tool-policy-mode-and-pins)
43
+ - [Tool activation and `mcp_search_tools`](#tool-activation-and-mcp_search_tools)
44
+ - [Project guidance in the system prompt](#project-guidance-in-the-system-prompt)
45
+ - [Lazy mounting and idle release](#lazy-mounting-and-idle-release)
46
+ - [Sidebar panel](#sidebar-panel) — [settings page](#settings-page), [writing entries](#writing-entries)
47
+ - [Diagnostics](#diagnostics)
48
+ - [Resource behaviour](#resource-behaviour)
49
+ - [Runtimes](#runtimes)
50
+ - [Verifying](#verifying)
51
+ - [Limitations](#limitations)
52
+ - [Dogfooding](#dogfooding)
53
+
54
+ Implementation notes: [how it works](#how-it-works) · [bundle format](#bundle-format-do-not-fix-this) · [layout](#layout)
55
+
56
+ ## Install
57
+
58
+ ```bash
59
+ pnpm install && pnpm check # typecheck + build + tests under the coverage gate + resource audit
60
+ pnpm coverage # the same suite with the coverage report only
61
+ pnpm pack # -> dsh-project-mcp-0.2.0.tgz
62
+ mv dsh-project-mcp-0.2.0.tgz ~/.dsh/packages/
63
+ dsh plugin --profile web add file:$HOME/.dsh/packages/dsh-project-mcp-0.2.0.tgz
64
+ ```
65
+
66
+ `pnpm check` runs the suite through `--coverage`, and `vitest.config.ts` gates all
67
+ four readings at **80%** over `src/**`: a surface added without its tests fails
68
+ the command a reviewer runs, not a later reading of a report.
69
+
70
+ Bun works as the package manager and runner too:
71
+
72
+ ```bash
73
+ bun install && bun run build
74
+ bun test tests # same suite through the Bun test runner
75
+ ```
76
+
77
+ `dsh plugin add` appends the bundle to `dsh.profile.bundles` and reconciles
78
+ `~/.dsh/profiles/web/package.json`; the bundle's own `cordis.patch.yml` mounts
79
+ the row. Restart the web GUI afterwards. To iterate without re-packing, install
80
+ with `link:/abs/path/to/dsh-project-mcp` and rebuild (`pnpm build`).
81
+
82
+ ## Sources and priority
83
+
84
+ Read for the project of each session, lowest priority first — a later document
85
+ overrides an earlier entry with the same `serverName`. The order is exactly the
86
+ `globalFiles` list followed by the `localFiles` list:
87
+
88
+ | # | Document | Setting |
89
+ |---|---|---|
90
+ | 1 … | the global documents this deployment names | `globalFiles`, default `[]` — none read |
91
+ | … n | the project's own documents, in list order | `localFiles`, default `['.dsh/mcp.json']` |
92
+
93
+ A spec is read the way a shell reads it: `~/…` is `$HOME/…`, `$DSH_HOME/…` is the
94
+ plugin's own home, an absolute path is itself, and anything else is relative to
95
+ the base it belongs to — the project root for `localFiles`, `$HOME` for
96
+ `globalFiles`. So `localFiles: ['.kimi-code/mcp.json', '.dsh/mcp.json']` reads a
97
+ Kimi Code project's file first and lets the DSH file override it, and
98
+ `globalFiles: ['~/.dsh/mcp.json']` adds a machine-wide document below both.
99
+
100
+ A document may be `{ "mcpServers": { ... } }`, `{ "servers": { ... } }`, or a
101
+ bare `name → entry` map. Unknown fields are ignored; a broken row never blocks
102
+ the rest of the document — it surfaces as an `error` row.
103
+
104
+ ### Entry mapping
105
+
106
+ | Input | Result |
107
+ |---|---|
108
+ | `command` / `args` / `env` / `cwd` | `transport: 'stdio'`, `cwd` defaults to the project root |
109
+ | `url` / `headers` | `transport: 'streamable-http'` |
110
+ | `type: 'stdio' \| 'http' \| 'streamable-http' \| 'sse'` | explicit transport; otherwise inferred from `url` |
111
+ | `enabled: false` / `disabled: true` | row stays visible as `disabled`, never mounted |
112
+ | `serverName` | the `mcpServers` key; must match `[A-Za-z0-9_-]{1,32}`, otherwise it is slugified with a warning |
113
+ | `"${VAR}"` | the project's own `.env` files → `process.env.VAR` → the credentials file, else an entry error |
114
+ | `"${input:NAME}"` | plugin `inputs.NAME` → the same chain as `${VAR}` |
115
+ | invalid JSON / bad row | `error` row with the reason; siblings still mount |
116
+
117
+ `${...}` references are expanded in `command`, `args`, `env`, `cwd`, `url` and
118
+ `headers`. Secrets stay out of the project document: they live in
119
+ `process.env`, in the project's own `.env` files, or in
120
+ `~/.dsh/.credentials.yaml`.
121
+
122
+ ### Variables
123
+
124
+ A value a reference needs is looked up in one fixed order, project-local first:
125
+
126
+ | # | Source | Gate |
127
+ |---|---|---|
128
+ | 1 | `<project>/.dsh/.env` | `envFiles` (default `true`) |
129
+ | 2 | `<project>/.env` | `envFiles` (default `true`) |
130
+ | 3 | `process.env` | — |
131
+ | 4 | `KEY` in the credentials file | `credentialsFile` (default `$DSH_HOME/.credentials.yaml`) |
132
+
133
+ Plugin `inputs` sit above all four for `${input:NAME}`. The project-local files
134
+ are ordinary dotenv documents — one `KEY=value` per line, an optional `export `,
135
+ single or double quotes, `#` comments on their own line or after whitespace — and
136
+ an empty value counts as unset, so a blank entry cannot shadow a real one.
137
+
138
+ Both document shapes work: `${VAR}` (what a `mcp.json` written by hand usually
139
+ carries) and `${input:VAR}` (the VS Code spelling). Each document is re-read only
140
+ when its mtime/size changes, and a change to any of the four sources re-expands
141
+ the references and re-mounts the affected servers **without** the `mcp.json`
142
+ being touched. A key any of these sources answered is never written back by the
143
+ editor: it stays masked in the panel and its declared `${...}` text stays in the
144
+ file. `envFiles: false` narrows the chain back to `process.env` + credentials. Keep
145
+ the dotenv documents out of version control — the plugin only ever reads them, but a
146
+ committed `.env` is a committed secret.
147
+
148
+ ## Configuration
149
+
150
+ Plugin config is the `cordis.patch.yml` row (defaults shown):
151
+
152
+ ```yaml
153
+ - id: project-mcp
154
+ config:
155
+ enabled: true # master switch
156
+ localFiles: ['.dsh/mcp.json'] # project documents, lowest priority first
157
+ globalFiles: [] # documents read before a project's own; [] reads none
158
+ envFiles: true # read <project>/.env and <project>/.dsh/.env for ${...}
159
+ inputs: {} # explicit ${input:NAME} values, e.g. COVERAGE_MCP_ALLOWED_ROOT: /repo
160
+ toolCallTimeoutMs: 60000
161
+ failOnStartupError: false # true = a dead server fails its mount instead of reconnecting
162
+ connectTimeoutMs: 60000 # a mount with no tool after this window becomes an error row; 0 disables
163
+ lazy: true # mount a session's project on its first turn, not at session creation
164
+ idleTimeoutMs: 300000 # release a session's mounts after this much inactivity; 0 disables
165
+ activationWaitMs: 2000 # how long the first step of a turn may wait for a pending mount; 0 never waits
166
+ profileWins: true # a profile-level serverName wins; the project row becomes `conflict`
167
+ watch: true # watch project documents for edits
168
+ debounceMs: 300
169
+ rescanIntervalMs: 10000
170
+ credentialsFile: '' # default: $DSH_HOME/.credentials.yaml
171
+ allowGlobalWrite: false # let the editor write the documents of globalFiles
172
+ activationEnabled: true # offer MCP tools through `mcp_search_tools` + activation
173
+ activationSeeded: 8 # counter-seeded tools that are always offered
174
+ activationMinCalls: 5 # calls one tool needs before it is seeded
175
+ toolIdleMs: 1800000 # drop a session-activated tool after this long without a call; 0 disables
176
+ guidanceEnabled: true # one short project-MCP guidance section in the session system prompt
177
+ activationAutoLimit: 12 # names the task-context tier may offer at once; 0 disables that tier
178
+ activationAutoStickySteps: 2 # extra user messages a context offer stays offered
179
+ activationToolBudgetChars: 40000 # serialized MCP surface above which tools are deferred; 0 defers always
180
+ projectMarkers: ['.git', '.dsh', '.kimi-code', 'package.json']
181
+ fileMarkers: ['.sln', '.slnx', '.csproj']
182
+ ```
183
+
184
+ ### Live editing
185
+
186
+ On DSH ≥ 0.1.7 the keys below are **volatile**: the host serves them as a
187
+ config form, an edit commits into the running plugin without a restart, and the
188
+ runtime picks the new value up on the loader's `loader/volatile-update` event.
189
+ Every other key — `enabled`, `localFiles`, `globalFiles`, `projectMarkers`,
190
+ `fileMarkers`, `inputs`, `credentialsFile`, `watch`, `rescanIntervalMs`,
191
+ `failOnStartupError` — is structural and still
192
+ needs a remount (restart or config reload) to take effect. An older host just
193
+ hands over plain values, and nothing about the boot path changes.
194
+
195
+ Volatile keys: `activationEnabled`, `activationSeeded`, `activationMinCalls`,
196
+ `toolIdleMs`, `guidanceEnabled`, `activationAutoLimit`,
197
+ `activationAutoStickySteps`, `activationToolBudgetChars`, `allowGlobalWrite`,
198
+ `envFiles`, `lazy`, `localPrefix`, `profileWins`, `connectTimeoutMs`,
199
+ `toolCallTimeoutMs`, `idleTimeoutMs`, `debounceMs`, `activationWaitMs`.
200
+
201
+ ### `profileWins`
202
+
203
+ - `true` (default) — a project entry whose `serverName` is already live in the
204
+ profile is **not** mounted; its row reads `conflict` with the hint to remove
205
+ the profile entry. Safe: no duplicate processes, no shadowing.
206
+ - `false` — the project instance is mounted too. Nearer scopes shadow the
207
+ profile's tools for that session, so the project's own configuration (for
208
+ example a project-specific `IJ_MCP_SERVER_PROJECT_PATH`) wins. Costs one
209
+ server process/connection per server for as long as a session of that project
210
+ holds it.
211
+
212
+ ## Runtime status
213
+
214
+ The plugin publishes a `projectMcp` service (`snapshot()` reads, `save()` writes
215
+ one entry back, and `setPin()` / `setPolicy()` write the project's tool policy):
216
+
217
+ ```ts
218
+ ctx.get('projectMcp').snapshot()
219
+ // { ready, watchedFiles,
220
+ // projects: [{ projectRoot, policy, sessionIds, rows, issues, sessions, usage }] }
221
+ // row.status: 'active' | 'connecting' | 'idle' | 'disabled' | 'conflict' | 'error'
222
+ // row.entry: the parsed body the editor starts from; row.writeScope / documentRevision
223
+ // sessions: [{ id, rows, issues }] — the same rows split per session
224
+ // policy: { mode, pins } — the project's tool policy, defaulted until it is changed
225
+ // usage: { [serverName]: ServerUsage } — absent until something was counted
226
+ ctx.get('projectMcp').syncNow(root?) // reconcile and await it; `root` scopes it to one project
227
+ ctx.get('projectMcp').syncSoon(root?) // same pass, answered at once — the panel's `Sync`
228
+ ctx.get('projectMcp').retry(root?) // drop the failed mounts, then re-mount them in the background
229
+ ctx.get('projectMcp').subscribe(change => …) // push: the current SnapshotChange at once, then one per change
230
+ // SnapshotChange: { revision, snapshot } — every frame carries the whole snapshot
231
+ ctx.get('projectMcp').save({ projectRoot, server, document, revision, entry })
232
+ // { ok: true, snapshot } | { ok: false, code: 'invalid' | 'blocked' | 'conflict' | 'not-found' | 'failed' }
233
+ ctx.get('projectMcp').setPin({ projectRoot, tool, pinned })
234
+ ctx.get('projectMcp').setPolicy({ projectRoot, mode })
235
+ // { ok: true, snapshot } | { ok: false, code: 'invalid' | 'not-found' | 'failed' }
236
+ ```
237
+
238
+ `projects[].rows` is the merge across that project's sessions, in document
239
+ order. Sessions mount independently, so when they disagree about one server the
240
+ most actionable status wins — `error` > `active` > `connecting` > `conflict` >
241
+ `idle` > `disabled` — and a running or failing server is never reported as idle
242
+ just because a session that has not turned yet was registered first.
243
+ `projects[].sessions` carries the same data split per session, which is what says
244
+ *which* session holds a mount.
245
+
246
+ ## Usage counters
247
+
248
+ The host half counts every tool call whose server **this plugin** mounted, keyed
249
+ by project root and `serverName`, so a project's numbers outlive the sessions
250
+ that produced them:
251
+
252
+ ```ts
253
+ ctx.get('projectMcp').snapshot().projects[0].usage
254
+ // { alpha: { calls: 12, errors: 1, tools: { search: 9, fetch: 3 },
255
+ // lastUsedAt: '2024-05-06T07:08:09.000Z' } }
256
+ ```
257
+
258
+ - `calls` counts every dispatched call, `errors` those whose result carried an
259
+ error, and `lastUsedAt` (ISO) moves on success only. `tools` keys the tool name
260
+ as the server declares it, without the `mcp__<serverName>__` prefix.
261
+ - Attribution never parses the prefix blindly: only tool names belonging to a
262
+ server this plugin mounted for the calling agent's project are counted, so a
263
+ profile-level `mcp__*` server never lands in a project's counters, and a
264
+ registry name truncated to the function-name budget still resolves to its own
265
+ server.
266
+ - The counters live in `$DSH_HOME/dsh-project-mcp-usage.json`, a versioned
267
+ document (`{ version: 1, projects: … }`) written atomically (temp file +
268
+ rename) on a debounce — never on the tool-call path. A missing, unparsable or
269
+ older-version document starts clean, and a failed write is logged and dropped:
270
+ counting is never a reason for a tool call or the plugin to fail.
271
+ - `usage` is absent for a project with no counted calls yet.
272
+
273
+ ## Tool policy: mode and pins
274
+
275
+ The panel's `Tools` surface overrides the shipped presentation per project, and
276
+ that decision is **plugin state**, not project configuration: it lives in
277
+ `$DSH_HOME/dsh-project-mcp-policy.json`, the same kind of document as the counters
278
+ (versioned, written atomically through a temp file + rename, written on a debounce,
279
+ and a missing, corrupt or older-version file starting from the defaults rather
280
+ than failing):
281
+
282
+ ```json
283
+ { "version": 1, "projects": { "<root>": { "mode": "disclosure", "pins": ["mcp__tglider__workspace"] } } }
284
+ ```
285
+
286
+ - **Mode** (`ProjectSnapshot.policy.mode`):
287
+ - `disclosure` (default) — everything *Tool activation* below describes: the
288
+ budget, the counter baseline, on-demand activations, the context tier and
289
+ `mcp_search_tools`.
290
+ - `direct` — defers nothing: the request carries the whole mounted catalogue,
291
+ `deferring` is `false` and the discovery tool is not advertised.
292
+ - `off` — offers none of the project's tools: the assembly listener adds
293
+ nothing. Registering `mcp_search_tools` in the session scope cannot be
294
+ cancelled (a DSH limitation, not a choice), so it stays registered but is not
295
+ advertised either.
296
+ - The mode is read on **every** assembly, so a change applies from the next
297
+ model step on, with no re-mint of the session scope.
298
+ - The mode decides all three fields of `SessionTools`, because that row is
299
+ *this plugin's contribution* to the request, not what the model finally sees:
300
+
301
+ | Mode | `baseline` | `deferred` | `deferring` |
302
+ |---|---|---|---|
303
+ | `disclosure` | pins ∪ hot names | mounted minus offered | surface over budget |
304
+ | `direct` | pins ∪ hot names | empty | `false` |
305
+ | `off` | **empty** | **every mounted name** | `false` |
306
+
307
+ `deferring` is about the budget, never about the mode: `direct` and `off`
308
+ defer nothing by size, they either filter nothing or offer nothing. A panel
309
+ has to read `policy.mode` before the numbers — in `off` it says "this
310
+ project's tools are off" rather than "N hidden", because a model can still
311
+ see them when no other presentation plugin filters the assembly.
312
+ - **Pins** (`ProjectSnapshot.policy.pins`) — the names the user insists on:
313
+ - A pinned name is offered from the first step of every request, whatever the
314
+ counters and the budget say. It joins `SessionTools.baseline`, so the panel
315
+ counts it as offered and it never lands in `deferred` — `baseline` is pins
316
+ plus the names the counters heated up, and `deferred.length` is what is
317
+ hidden.
318
+ - A pin is project state, not session state: it survives idle pruning and
319
+ `compaction/end` exactly like the counter baseline.
320
+ - A name the project no longer mounts stays pinned — the declaration may come
321
+ back, and a pin that silently disappeared would be a surprise. The list is
322
+ delivered separately from the rest of `baseline`, because it is what the user
323
+ pinned by hand rather than what the counters seeded.
324
+ - `off` does not erase pins; it just does not offer them — the row's
325
+ `baseline` is empty and every mounted name is `deferred` — so switching back
326
+ to `disclosure` finds them again.
327
+
328
+ Both changes go over the panel routes, in the same envelope as a save and without
329
+ a rescan — the policy is not part of any declaring document, so the snapshot is
330
+ rebuilt in place:
331
+
332
+ ```ts
333
+ POST /project-mcp/pin { projectRoot, tool, pinned } // PinRequest
334
+ POST /project-mcp/policy { projectRoot, mode } // PolicyRequest
335
+ // 200 { ok: true, value: <fresh snapshot> }
336
+ // 400 unknown project (not-found) or unknown mode (invalid)
337
+ ```
338
+
339
+ ## Tool activation and `mcp_search_tools`
340
+
341
+ A project can mount a large MCP surface, and every one of those tools in every
342
+ request is expensive. The host half presents them the way a progressive-tools
343
+ deployment wants, without touching the registry (this is the `disclosure` mode of
344
+ *Tool policy* above; a project can be switched to `direct` or `off` instead):
345
+
346
+ - **Hot tools are offered directly.** A tool whose project counters reached
347
+ `activationMinCalls` (default 5) is seeded into a **baseline** that appears in
348
+ the request from the first step on; `activationSeeded` (default 8) caps how
349
+ many names the counters may seed. The counters are the ones above, so the
350
+ baseline is remembered across sessions and restarts.
351
+ - **Matching tools are offered from the task context.** The host ranks the
352
+ project's mounted tools against the newest task text with BM25 — over the tool
353
+ name and description, tokenized on case boundaries, separators and punctuation,
354
+ `k1 = 1.2`, `b = 0.75`, name matches weighted above description ones — and
355
+ offers the best matches. `activationAutoLimit` (default 12) caps how many
356
+ names one task may offer; matches below a score floor are dropped, and a tool
357
+ that does not match stays reachable through `mcp_search_tools`.
358
+ - **Only a large surface is deferred at all.** The session's mounted schemas are
359
+ measured as the request would carry them — name, description and serialized
360
+ parameters. If that total is at or below `activationToolBudgetChars` (default
361
+ `40000`, roughly 10K tokens) every tool is offered exactly as the rest of the
362
+ harness assembled it. `0` switches the gate off and defers every surface.
363
+ The counters keep accumulating either way, so the decision follows a project
364
+ as it grows.
365
+ - **The offered set is sticky, so it rarely changes.** A name stays offered for
366
+ the task text that offered it plus `activationAutoStickySteps` (default 2)
367
+ later messages, one input per recomputation, so several steps share one tool
368
+ list instead of following every dip of the ranking. Because the inner listeners
369
+ rebuild the registry list on every step, the additions are re-applied each time
370
+ from what those listeners actually returned; when that list already carries
371
+ everything, the listener hands back the **identical** assembly object. A
372
+ changing tool list rewrites the prompt prefix and invalidates the model's
373
+ cache, so the plugin changes it deliberately and rarely.
374
+ - **The rest are found, not listed.** The plugin registers `mcp_search_tools` in
375
+ the session's own scope and also offers it from its own assembly listener — a
376
+ presentation plugin that trims the list to an allowlist would otherwise drop
377
+ the one tool that makes the deferred layer reachable. The discovery tool is
378
+ **pinned**: it appears in every `disclosure` assembly, whatever the budget
379
+ says, so the model can always discover tools as the project grows. A call
380
+ searches the MCP tools of *this project* — never a profile-level tool or
381
+ another project's server — activates up to `limit` (default 8) matches, and
382
+ returns their names and descriptions. The query matches case-insensitively
383
+ and **word by word**: the whole query as one substring of a name or
384
+ description ranks highest, and every word of it then scores its own hit (a
385
+ word in a name outweighs the same word in a description; words shorter than
386
+ two characters are ignored, and only the first eight distinct words count),
387
+ so `issue get create update` finds `…-issue_get`, `…-issue_create` and
388
+ `…-issue_update` even though no tool contains that phrase verbatim. The
389
+ activated tools join the offered
390
+ list from the **next** model step on; only the tools already listed are
391
+ reliable until then.
392
+ - **Everything falls away again.** A session-activated tool that is not called
393
+ within `toolIdleMs` (default 30 minutes) is dropped at the next `agent/status`
394
+ transition, and a `compaction/end` clears the session's activations and the
395
+ context offers outright. The counter baseline survives both — it is derived
396
+ from durable counters, not from the session — and a pin survives them for the
397
+ same reason (*Tool policy* above).
398
+
399
+ **Where the task text comes from.** The context tier reads the session's own
400
+ `session/event` stream: the newest committed `user/message` supplies the text,
401
+ and `tool/call` events supply recently called names (a called tool is offered
402
+ only when the plugin mounted it for this project). Only a message whose source
403
+ is `user` counts: the same event type carries every plugin-authored context
404
+ injection — runtime-context snapshots, agent instructions, skill catalogues,
405
+ memory recalls, cron notices — and ranking a tool offer against one of those
406
+ instead of the task would be worse than ranking against nothing. The timing
407
+ follows the harness: a turn's messages reach the log *after* the assembly that
408
+ opens the turn, so the first step of a turn ranks against the previous message
409
+ and the current one takes effect from the next step. Idle pruning, the counter
410
+ baseline, and `mcp_search_tools` are unaffected by this read.
411
+
412
+ This is presentation, not permission. A tool the model cannot see is still
413
+ callable when the model already knows its name, and the model may call it
414
+ directly; only what is *listed* changes. Nothing is ever unregistered: each
415
+ request gets the registry's own tool list plus the active schemas, deduplicated
416
+ by name, and `activationEnabled: false` turns the whole mechanism off (every
417
+ mounted tool is listed exactly as before, and no search tool is registered).
418
+
419
+ Implementation note — the presentation rides the agent's own
420
+ `system-prompt/assemble` waterfall, registered *prepended* so it runs outermost
421
+ and sees the list after other presentation plugins (for example
422
+ `dsh-progressive-tools`) filtered it. That listener is contained: if this
423
+ plugin's own work fails, the assembly the rest of the harness produced is
424
+ returned unchanged, so a broken probe can never break a model request. One
425
+ residual ordering risk remains: a presentation plugin that trims the list to its
426
+ own allowlist and ends up *outside* this listener (it registered its own
427
+ prepended listener later) drops the schemas this plugin added, leaving only the
428
+ tools that plugin allows. What that surfaces looked like is why the discovery
429
+ tool is offered by this listener rather than left to the registry — but it is
430
+ still trimmed in that nesting. A deployment that wants the discovery path in
431
+ spite of it can name `mcp_search_tools` in that plugin's own allowlist (in
432
+ `dsh-progressive-tools` that is `eagerTools`), which makes the tool survive in
433
+ either nesting; the MCP schemas themselves cannot be pinned that way, because
434
+ they are project data, not configuration.
435
+
436
+ ## Project guidance in the system prompt
437
+
438
+ The per-server `mcp:<server>` sections mcp-client publishes say what a server
439
+ *is*, and the activation surface above makes many of its tools invisible — but
440
+ nothing told the model that a tool it cannot see may still be asked for. The
441
+ host half adds one short section (`guidanceEnabled: true`, the default) that
442
+ says exactly that, next to the mounts it describes:
443
+
444
+ ```text
445
+ ## Project MCP servers
446
+
447
+ Project `project1` mounts 2 MCP server(s) in this session.
448
+
449
+ - memory (stdio, active)
450
+ - tglider (stdio, active) — code intelligence
451
+
452
+ Most used in this project's sessions, offered from the first step on: recall,
453
+ find_symbol — call them directly, no search needed.
454
+
455
+ 3 of 14 MCP tool(s) are offered directly; the other 11 are offered on demand —
456
+ call `mcp_search_tools` with a keyword or a tool name (several words are
457
+ matched one by one), and a tool it activates becomes callable from the next
458
+ step. Search once with the best keywords you have; when the search reports no
459
+ match, this project mounts no such tool — report the gap instead of rephrasing
460
+ the search or guessing a name.
461
+
462
+ On demand right now: batch_rename, changed_symbols, diagnostics, find_callers
463
+ +7 more — every one of them runs when called by its exact full name
464
+ `mcp__<server>__<tool>`; search a name with `mcp_search_tools` first to see its
465
+ description and parameters.
466
+ ```
467
+
468
+ - **Deterministic and bounded.** Servers are listed in code-unit name order,
469
+ and the deferred surface is one flat names line — sorted, deduped, capped at
470
+ twelve names with `+N more`. The whole section is capped at 1200 characters,
471
+ so an extreme project loses trailing server bullets (folded into
472
+ `… and N more server(s)`) before it loses the on-demand instruction and the
473
+ names line.
474
+ - **A names line instead of schemas.** Descriptions and parameters are the
475
+ expensive part, so the section lists bare names only: the model picks the
476
+ tool it needs and runs one targeted `mcp_search_tools` query instead of
477
+ probing blindly. The line also states the direct-call contract — deferral
478
+ trims the assembled request list, it never unregisters the tool, so a call by
479
+ the exact full name `mcp__<server>__<tool>` still executes; searching first
480
+ is how the model sees the description and parameters, not a gate.
481
+ - **A most-used line from the durable counters.** When the seeded baseline is
482
+ non-empty, the section names the project's hot tools (most-called first, up
483
+ to four names with `+N more`) and says they are offered from the first step
484
+ on — so the model calls them directly instead of searching for what it
485
+ already has. With `activationEnabled: false` the line is dropped, like the
486
+ rest of the activation story.
487
+ - **An anti-loop hint.** The on-demand paragraph ends with the search
488
+ etiquette: one search with the best description at hand, and a no-match
489
+ answer means the project mounts no such tool — report the gap instead of
490
+ rephrasing the search or inventing a name.
491
+ - **Placed with the MCP sections.** The section is registered through
492
+ `ctx.inject(['systemPrompt'], …)` at the `MCP_SERVERS` order, with a name
493
+ (`mcp-project-guidance`) whose code-unit order precedes every `mcp:<server>`
494
+ instruction block — the same convention `mcp-resource-servers` uses — so the
495
+ guidance is read ahead of the servers it introduces.
496
+ - **Live, and released with the scope.** `text` is a callback: it reads the
497
+ session's mounts and the registry at every assembly, so a rescan that mounted
498
+ or dropped a server changes the text without re-registering anything. The
499
+ registration is owned by the agent scope and released exactly where its mounts
500
+ are (`projectMcp.release()`, idle timeout, agent disposal).
501
+ - **No local identifiers.** The project is named by its `~`-collapsed directory
502
+ label, never by its absolute root, and the section carries no endpoint, no
503
+ argument and no document path. A section that fails to build returns `''`
504
+ rather than failing the model request that asked for the assembly.
505
+
506
+ `guidanceEnabled: false` registers no section at all. With `activationEnabled:
507
+ false` the section still lists the mounts but drops the on-demand paragraph,
508
+ the names line and the most-used line, because nothing is deferred and nothing
509
+ is seeded.
510
+
511
+ ## Lazy mounting and idle release
512
+
513
+ A profile with twenty project folders must not start twenty projects' worth of
514
+ servers. A session's project is mounted on its **first turn**, and the mount is
515
+ scoped to the session that asked for it:
516
+
517
+ ```
518
+ session created → nothing runs; rows read `idle`
519
+ one session's turn → that session's project starts, nothing else
520
+ idle for idleTimeoutMs → scope disposed; rows read `idle` again
521
+ next turn → mounted again from scratch
522
+ ```
523
+
524
+ The isolation rule is one pure, exported function — `mountTrigger` in
525
+ `src/runtime.ts`. A pass starts a session's servers only when *that* session
526
+ asks: its own turn, an operator request that names it, `lazy: false`, or a
527
+ session that already holds mounts and is being reconciled. A session that is
528
+ merely live — restored, listed, idle, or another session's neighbour — never
529
+ starts anything, so a twenty-project profile stays at zero children until one of
530
+ its own sessions works there.
531
+
532
+ Two agent-plane events drive it: `agent/status` (`idle`/`running`) marks
533
+ activity, and `agent/pre-step` is awaited by the loop, so the plugin can wait
534
+ for a pending mount (`activationWaitMs`, default 2 s) and the step's request
535
+ already sees the project's tools. The hook always continues the waterfall — a
536
+ project MCP server is never a reason to block an agent step.
537
+
538
+ A mount is released on the first path that exists; only the quiet session needs
539
+ a clock:
540
+
541
+ - a session the host no longer lists releases its mounts on the next pass — no
542
+ timer, no status event, and it works with `idleTimeoutMs: 0`;
543
+ - `agent/disposed`, an explicit `projectMcp.release()`, and a move to another
544
+ project dispose the session's scope where it lives;
545
+ - the idle sweep releases a quiet session after `idleTimeoutMs`. It reads the
546
+ host's own `agent.status` where the composition publishes one, so a session
547
+ whose `idle` transition never reaches the plugin cannot pin its mounts behind
548
+ a stale flag.
549
+
550
+ - `lazy: false` restores eager mounting at session creation; idle release still applies.
551
+ - `activationWaitMs: 0` never waits: the first request of a reactivated session
552
+ may run without the project's tools, which appear from the next step on.
553
+ - An operator call — `projectMcp.syncNow()`, `projectMcp.syncSoon()`,
554
+ `projectMcp.retry()` — requests every listed session, or only one project's
555
+ when it names a root, so it mounts a lazy declaration without a turn. That is
556
+ the one path that starts a server for a session which is not working, and it
557
+ is deliberate: the `POST sync|retry` routes and scripted reconciliation call
558
+ it. `syncSoon()` and `retry()` answer as soon as the request is accepted — the
559
+ pass is background work, and the panel reads its outcome off the status
560
+ channel instead of holding a response open for `connectTimeoutMs`.
561
+ - Every created process writes exactly one `info` line naming the session, the
562
+ project root its working directory resolved to, and the trigger (`turn`,
563
+ `mounted`, `eager`, `operator`). It is written when the mount is created, never
564
+ by a rescan pass that re-derives the same mount.
565
+
566
+ ## Sidebar panel
567
+
568
+ The package has a browser half (`./client`) that registers a tab with
569
+ [`dsh-better-sidebar`](https://github.com/omdsh-dev/DSH-better-sidebar). A tab
570
+ belongs to one conversation, so it shows **only that session's project** — never
571
+ another one: the servers it declares and their merged live status, then the same
572
+ project broken down **per session** — which session holds a mount, which has not
573
+ turned yet, which one is this tab's — with `Sync` / `Release` actions. `Release`
574
+ gives one session's hold back: the shared instance keeps running while another
575
+ session of the project holds it, and stops when it was the last holder.
576
+
577
+ Both operator actions are **scoped to the project the surface shows**: the tab
578
+ and the settings page name that root in the request, the host touches only its
579
+ servers and answers with its slice of the snapshot (the settings page asks for
580
+ the whole snapshot back, since it lists every project), and the pass is queued
581
+ rather than awaited — the answer arrives immediately, not after the servers have
582
+ settled.
583
+
584
+ Four view modes, switched in the toolbar and remembered in `localStorage`:
585
+ `Servers` (everything, the default), `Tools` (what the model sees of this
586
+ project — pins, disclosed and hidden tools, the budget line), `Problems` (only
587
+ `error` / `conflict` / `connecting`, grouped in that order, with `Retry failed`
588
+ alongside `Sync`) and `Logs` (the plugin's own event ring, below). Every state
589
+ that has nothing to list names what is missing instead of showing an empty box —
590
+ no session, no project marker above the session cwd, no declared server, or
591
+ nothing that needs attention.
592
+
593
+ The same tab declares its own settings panel in the side card settings popup, and
594
+ that panel is where the whole picture lives: **every** project with a live
595
+ session, not just this tab's, plus the panel's poll interval, persisted in the
596
+ sidebar's `pluginSettings`.
597
+
598
+ `ctx.betterSidebar` exists only in the browser half, so the panel does not call
599
+ the runtime in process: the host half registers HTTP routes on the DSH web server
600
+ (`/project-mcp/snapshot|events|logs|sync|retry|release|save|pin|policy`, see
601
+ `src/ui.ts`) and the panel fetches them. Responses are `{ ok: true, value }` or
602
+ `{ ok: false, error }`.
603
+
604
+ `GET /project-mcp/events` is the status channel: Server-Sent Events, one frame
605
+ per change (`event: change`, `data: { revision, snapshot }`), and a `hello` frame
606
+ carrying the current picture the moment a panel subscribes. DSH's web server
607
+ hands a route the raw response and exempts `text/event-stream` from its gzip
608
+ filter, so the stream is not buffered; a comment frame every 15 s keeps an idle
609
+ connection warm. The panel stops polling while the stream is open and falls back
610
+ to its poll — `DEFAULT_REFRESH_MS`, or the interval from the settings popup —
611
+ whenever it is not (an older host half, a browser without `EventSource`, a
612
+ dropped connection, which `EventSource` reconnects on its own).
613
+
614
+ `Logs` is the tab's fourth mode and reads the plugin's own event ring
615
+ (`src/logs.ts`): up to 200 events per project, the snapshot carrying the latest
616
+ 50 and `GET /project-mcp/logs` paging the rest (`before` cursor, `limit`). One
617
+ event is `info` / `up` / `warn` / `error`, carries the project root, optionally a
618
+ session and a server, and one line of message. The runtime publishes each of its
619
+ five lifecycle events once, through the notification service
620
+ (`src/notifications.ts`) — mounting, `is up`, a stall, a failed mount, unmounting
621
+ — and both readers subscribe to that publication: the ring, and the line the host
622
+ log gets. The tab and the log therefore carry the same event, with no second
623
+ write path to keep in step. Filters (`this session` / `all sessions`, `all levels` /
624
+ `errors`) are client-side and remembered per browser; the level opens on `errors`
625
+ and an empty list under that filter says the ring holds other events instead of
626
+ claiming there are none. `Clear` is a client mark in `localStorage` (`logsClearedAt`) —
627
+ there is no clear route. A page that fails to arrive is a line under the list,
628
+ not a broken tab.
629
+
630
+ Toasts are the same picture on the frame: a server that starts or stops while a
631
+ panel is subscribed floats a banner in DSH's `shell.overlay` floating layer
632
+ (`src/client/toasts.ts`) instead of only changing a row in a tab nobody is
633
+ looking at. They are fed by the same status channel — `serverTransitions()` diffs
634
+ what the `change` frames of `GET /project-mcp/events` say, and the baseline
635
+ `hello` frame only resets it, so a page load or a reconnect never reads as twenty
636
+ servers starting at once.
637
+
638
+ ```
639
+ browser: ctx.inject(['betterSidebar'], s => s.betterSidebar.registerTab({ … }))
640
+ fetch('/project-mcp/snapshot')
641
+ host: ctx.webServer.register({ kind: 'prefix', path: '/project-mcp', … })
642
+ ```
643
+
644
+ Requirements: `react` in the composition. If the host already provides a
645
+ `betterSidebar` service, the sidebar tab is registered; otherwise the host half
646
+ keeps mounting servers. Client changes hot-reload (hard-refresh the browser);
647
+ host changes need a `dsh web` restart.
648
+
649
+ ### Settings page
650
+
651
+ The browser half also contributes a page to DSH's own Settings
652
+ (`settings.section`, kind `list`, scope `root`, declared by the settings shell), a
653
+ Plugins settings section). That is the one surface where **every** project with a
654
+ live session is visible: a project picker plus two remembered views — `Table` (a
655
+ dense overview of server, transport, status, source and the `enabled` switch) and
656
+ `By files` (one card per declaring document, in priority order, each card showing
657
+ the servers it declares and the `overrides <name> from <file>` line a later
658
+ document caused). The view is remembered in browser-local storage
659
+ (`dsh-project-mcp:settings-view`); the page has no `pluginSettings` blob of its
660
+ own.
661
+
662
+ Alongside the two server views the same section carries the project's `Tools`
663
+ page, and every figure on it is the host's own: the mode and the pin list come
664
+ from the project policy (`setPin` / `setPolicy` write them back), the per-server
665
+ counters are read from the session's visible and deferred tool names by the
666
+ `mcp__<server>__` prefix, and the request preview is the visible list plus the
667
+ serialized sizes (`visibleChars` / `deferredChars`, tokens = characters / 4).
668
+ There is no slot figure and no prefix switch: the budget is measured in
669
+ characters, and the `mcp__<server>__` prefix is applied by
670
+ `@deepseek-ai/dsh-mcp-client`, not configured here.
671
+
672
+ Selecting a server opens the split editor: the project's servers on the left, the
673
+ parsed entry as a form in the middle, and a JSON pane on the right showing the
674
+ difference between what the document declares and the edit. The host half serves
675
+ the write path behind that form (`POST /project-mcp/save`, see *Writing entries*
676
+ below and `docs/design/contracts/write-path.md`); creating and deleting servers is a
677
+ separate step and is not part of it.
678
+
679
+ Registration is two-step and deliberately partial:
680
+
681
+ ```ts
682
+ ctx.inject(['slots', 'locale'], (scope) => { // optional client services
683
+ scope.locale.addLanguage({ id: 'ru', label: 'Русский', fallback: 'en' })
684
+ scope.effect(() => scope.locale.register(NS, { zh, en, ru })) // + a second register for projectMcp.host
685
+ // The slot is declared by the Plugins section at runtime, and
686
+ // `slots.register` throws while it is undeclared — so wait for it.
687
+ scope.slots.inject('settings.section', () => scope.slots.register({ … }, SettingsTab))
688
+ })
689
+ ```
690
+
691
+ The module-level `inject` is empty, and neither `betterSidebar` nor `locale` is
692
+ listed there: an entry that waits on an optional service stays **pending**, and
693
+ DSH's web boot audit refuses to start while any entry is pending. Both are read
694
+ without gating the entry instead — the sidebar tab parks behind
695
+ `ctx.inject(['betterSidebar'], …)` (so it registers whenever that service exists,
696
+ in a composition that has one), and the tab's translate seat comes from
697
+ `ctx.get('locale')`. A property read of a service the fiber did not declare
698
+ throws `cannot get property "…" without inject` and fails the entry, which is
699
+ what took the whole GUI down in 0.1.9. The host half and every slot-based surface
700
+ continue without either service. The bundle requests
701
+ `@deepseek-ai/dsh-client-ui-slots` (a baseline platform module) and
702
+ `package.json` declares `@deepseek-ai/dsh-client-locale` and
703
+ `@deepseek-ai/dsh-client-ui-settings` under `dsh.client.inject` — package-name
704
+ materialization edges, not Cordis services.
705
+
706
+ ### Writing entries
707
+
708
+ `POST /project-mcp/save` writes **one existing entry** back to the document that
709
+ declares it (`ServerRow.source` — even when a higher-priority document overrides
710
+ it, because that is where the entry lives). The request carries the entry body,
711
+ the declaring document and the `documentRevision` the editor was built from.
712
+
713
+ Tiers (`ServerRow.writeScope`):
714
+
715
+ | Tier | Documents | Condition |
716
+ |---|---|---|
717
+ | `project` | the resolved `localFiles` of the project | form confirmation |
718
+ | `global` | the resolved `globalFiles` of the deployment | `consent: true` **and** `allowGlobalWrite: true` |
719
+ | `readonly` | profile, `<DSH_HOME>`, bundled | never; `writeBlockedReason` says why |
720
+
721
+ Order of the checks, all before a byte is written: the row exists (`not-found`);
722
+ the document belongs to a writable tier and, for `global`, both gates are open
723
+ (`blocked`); the request's revision equals the document's (`conflict`,
724
+ `documentRevision` is a short SHA-256 prefix of the bytes); the edited entry
725
+ passes the same parse path as mounting (`invalid`). Only then is the document
726
+ replaced: `<document>.bak` first, then a temporary file in the same directory,
727
+ then `rename` over the original — a failure at any step leaves the document
728
+ exactly as it was, and a write failure answers `failed`. Formatting is
729
+ normalized (two spaces, trailing newline) while every other key of the document
730
+ and every key the editor does not present are preserved. After the write the
731
+ project is rescanned and the answer carries the fresh snapshot
732
+ (`{ ok: true, value: <snapshot> }`).
733
+
734
+ Secrets: `env`/`headers` values are handed to the editor only when the document
735
+ holds them literally. A masked key submitted without a `value` keeps what the
736
+ document declares, a key with a `value` writes that value, and a key the
737
+ submission omits is removed — so an editor that cannot see a secret can neither
738
+ erase nor replace it (`value: ''` is an empty value, not an omission). A key
739
+ answered outside the document — by the project's `.env` or by the credentials file
740
+ — is marked `fromCredentials` and its resolved value is never written back: the
741
+ declared text (usually a `${input:NAME}` reference) stays as it is.
742
+
743
+ Errors keep the plugin's envelope and code: `400` for `invalid`, `blocked`,
744
+ `not-found`; `409` for `conflict`; `500` for `failed`.
745
+
746
+ ## Diagnostics
747
+
748
+ A server that never comes up is the one failure a project-scoped mount cannot
749
+ recover from on its own, so it is reported instead of being retried forever.
750
+
751
+ - **`connecting`** — mounted, no tool yet. Normal while a command boots.
752
+ - **`error` after `connectTimeoutMs`** — the mount produced no `mcp__<name>__*`
753
+ tool inside the window. The row (and a matching `issues[]` entry) then carries a
754
+ facts an operator needs: the server name and how long it has been waiting, its
755
+ endpoint, and the document that declared it.
756
+
757
+ ```
758
+ gateway: no tool appeared in 4m 27s
759
+ endpoint: stdio docker
760
+ declared in: /repo/.dsh/mcp.json
761
+ ```
762
+
763
+ Facts only, on purpose: the row already carries the status, the transport chip
764
+ and a `Retry` button, and a stdio server's own reason is on its stderr — in the
765
+ DSH log.
766
+
767
+ The watchdog is read-only: it never disposes a slow server, and a mount that
768
+ connects later goes back to `active` with the detail cleared.
769
+ - **`error` from activation** — with `failOnStartupError: true` the failing
770
+ attempt itself rejects, and the row carries the underlying error plus the same
771
+ context; such a mount is never retried implicitly.
772
+ - **No respawn storms** — a failed or stalled mount is not re-mounted on later
773
+ passes. Fix the cause, then call `projectMcp.retry()` (or edit the declaration,
774
+ which re-mounts it too).
775
+
776
+ Error text is redacted on purpose: it names the command but never its arguments,
777
+ and an HTTP endpoint keeps its path but drops the query string, because both can
778
+ carry credentials.
779
+
780
+ ## Resource behaviour
781
+
782
+ Measured by `scripts/audit.mjs` against the real `mcp-client` and real child
783
+ processes (with a 400-tool catalog stub) on Node 24.13 and Bun 1.4.2 — every
784
+ check passes on both:
785
+
786
+ | scenario | result |
787
+ |---|---|
788
+ | idle project, 4 s | 0 passes, 0 catalog scans, ~1 ms CPU (Node) |
789
+ | 600 unrelated writes (`node_modules`, `dist`, `.git`) | 3 watch events → 1 pass, 0 catalog scans, 0 remounts |
790
+ | mount → dispose | MCP child process exits, its pid file is removed |
791
+ | server that cannot start | one detailed `error` row, no respawn storm, no leaked child |
792
+ | 10 × session create/dispose | 0 surviving children, file descriptors flat, heap +0.9 MB |
793
+ | two sessions, one project | 1 mount attempt, 1 child, 1 creation line — the second session's turn reuses it |
794
+ | a release while another session holds | child stays up for the remaining holder, goes down with the last one |
795
+ | teardown | watchers closed, descriptors released, 0 passes and ~1 ms CPU afterwards |
796
+
797
+ What keeps it that way: only the project's own document directories are watched
798
+ recursively (a flat watch on the project root notices a config directory
799
+ appearing), watcher events are debounced, a rescan compares config digests and
800
+ returns without doing anything when nothing changed, and the rescan timer,
801
+ watchers and every scope the plugin minted — per session and per project — are
802
+ released by the plugin fiber.
803
+
804
+ ## Runtimes
805
+
806
+ Verified with **Node 24.13** and **Bun 1.4.2** — both the plugin and its checks:
807
+
808
+ | | Node | Bun |
809
+ |---|---|---|
810
+ | `test` | `pnpm test` (vitest) | `bun test tests` |
811
+ | resource audit | `pnpm audit` | `bun scripts/audit.mjs` |
812
+ | live smoke | `node scripts/live-smoke.mjs` | `bun scripts/live-smoke.mjs` |
813
+ | build | `pnpm build` | `bun run build` |
814
+ | host runtime | `dsh` (Node) | `bun $(which dsh)` |
815
+
816
+ The plugin imports only `node:fs`, `node:os` and `node:path`, reads the ambient
817
+ `process.env`, and spawns MCP servers through `@deepseek-ai/dsh-mcp-client`, so it
818
+ behaves the same under either runtime. Watches prefer `fs.watch({ recursive: true })`
819
+ and fall back to flat watches on the project root and each config directory when a
820
+ runtime or platform cannot watch a tree recursively — the rescan timer covers the
821
+ rest either way.
822
+
823
+ ## Verifying
824
+
825
+ ```bash
826
+ # real Cordis host + real @deepseek-ai/dsh-mcp-client + a fixture stdio server
827
+ pnpm build && node scripts/live-smoke.mjs # prints the registered tool + snapshot
828
+ bun scripts/live-smoke.mjs # same check under Bun
829
+
830
+ # mount a real project's own documents and report what the servers publish
831
+ pnpm check:config . # -> tools: mcp__tglider__*
832
+ CHECK_CONFIG_TOOL=mcp__tglider__server_status pnpm check:config . # call one tool
833
+
834
+ # the sidebar tab against the frozen surface contract, out of a live profile
835
+ # (needs a profile that links this checkout: `dsh plugin --profile test-web add link:<workspace>`)
836
+ pnpm design:parity # PASS / ACCEPTED / SKIP / FAIL per element
837
+ ```
838
+
839
+ `design:parity` boots the `test-web` profile's own `dsh web` (which must
840
+ `link:<workspace>` this checkout), opens the tab and compares the computed
841
+ styles of what the panel draws, row by row, with the expected values frozen as
842
+ literals inside `scripts/design-parity.mjs` — in the live shell's own theme.
843
+ The rationale for each rule lives in `docs/design/contracts/surfaces.md` §9 and
844
+ `docs/design/contracts/single-surface.md`: the doc explains, the script decides,
845
+ and a surface change updates both in the same pass. The gate no longer diffs
846
+ against a picture: the design stand (`docs/design/mockups/harness.html`) is a
847
+ proposal allowed to run ahead of the product. The panel is fed a payload of the host's own
848
+ shape, because a profile started only for this measurement has no live agent
849
+ until a session runs a turn, and the plugin publishes a project only for a live
850
+ agent: the fixture puts every state the contract names on screen at once. It
851
+ prints the profile, the session and the bundle (path, size, build time, sha256)
852
+ it used. `ACCEPTED` is a documented exception with its authority named in the
853
+ contract, and it fails as soon as that authority moves under it; `SKIP` is a row
854
+ the run could not observe, and is never counted as a pass. `--dump` prints both
855
+ raw captures, `--watch` the panel's own reading once a second.
856
+
857
+ Manual acceptance on a running GUI:
858
+
859
+ 1. A session whose `cwd` is inside a project with `.dsh/mcp.json` (or whichever
860
+ document `localFiles` names) sees that project's `mcp__<name>__*` tools (check
861
+ the session tool catalog), and a second live session of the same project
862
+ resolves the same instance rather than a second process.
863
+ 2. A session in a project without such a file sees **no** project tools.
864
+ 3. Two sessions in two projects see different sets; the same `serverName` in
865
+ both projects resolves to different servers.
866
+ 4. Editing the file adds/removes tools after the debounce (~300 ms), without a
867
+ restart and without disturbing the profile-level servers.
868
+
869
+ ## Limitations
870
+
871
+ - Per-project cost: one MCP instance per project per server, shared by every
872
+ session working there (a subagent in the same project does not start a second
873
+ one). HTTP servers are cheap; `npx`/`uvx`/`dnx` stdio servers spawn a process
874
+ each, so a wide multi-project session graph still costs one child per project.
875
+ Use `enabled: false`, or keep a server in the profile when every project needs
876
+ it.
877
+ - Writes edit existing entries only: the editor replaces
878
+ `mcpServers[<server>]` in the document that declares it. Creating and deleting
879
+ servers, and writing a document that does not use an `mcpServers` object, are
880
+ not supported (the latter answers `blocked`).
881
+ - A config edit that keeps `JSON.stringify` of the generated config identical is
882
+ a no-op by design (no remount, no dropped connections).
883
+ - `profileWins` cannot un-mount a profile entry; remove it from
884
+ `cordis.patch.yml` to hand a server over to the project plane.
885
+
886
+ ## Dogfooding
887
+
888
+ This repository declares its own MCP server in `.dsh/mcp.json` — `tglider`
889
+ (TypeScript/JavaScript code intelligence) with `--workspace .`, which the plugin
890
+ resolves against the project root it launches in. `pnpm check:config .` mounts
891
+ that file through the plugin and lists the published `mcp__tglider__*` tools.
892
+
893
+ ## How it works
894
+
895
+ 1. **Project discovery** — for every live agent (session), the plugin walks up
896
+ from `agent.session.header.cwd` to the first directory carrying a project
897
+ marker (`.git`, `.dsh`, `.kimi-code`, `package.json`, `*.sln`/`*.slnx`/`*.csproj`).
898
+ 2. **Scope minting** — the project's servers are mounted **once per project**
899
+ inside a Cordis scope minted for it (`createScope(hostCtx, projectKey)`), the
900
+ same pattern the in-box `browser-use-runtime` uses for MCP servers. Every
901
+ session of that project gets its own scope, parented to the project's
902
+ (`bindScopeParent(agent, projectKey)`): the tools registry resolves a
903
+ session's catalog through that chain, so one instance serves every session
904
+ working in the project — subagents and Agent-Teams members included — and a
905
+ session of another project never resolves it.
906
+
907
+ `dsh-scope` binds a key's parent **once**, and a session composed from an
908
+ agent preset — every session of the Web GUI — has its key parented to that
909
+ preset's standing scope by the harness before the session is published. Such
910
+ a session cannot join the project's layer at all, so the plugin mounts the
911
+ same declarations **under the session's own scope** instead: an exact-key
912
+ layer always resolves for its own key, with no parent link to lose. That is
913
+ one instance per session rather than one per project, and the `info` line
914
+ says which of the two shapes a session got.
915
+
916
+ Reading the project's servers only after that link, or reporting a mount the
917
+ session cannot resolve as connected, is what the 60-second `no tool appeared`
918
+ row used to be: a healthy child process paired with an empty catalogue.
919
+ 3. **Lifecycle** — `agent/created` mounts, `agent/disposed` (and the agent's own
920
+ effect) tears down, a debounced `fs.watch` plus a rescan timer pick up config
921
+ edits, and a config change disposes and re-mounts only the affected server.
922
+ The shared instance follows the project's **last holder**: a session that goes
923
+ idle, releases, is disposed, or moves to another project gives its hold back,
924
+ and the servers stop exactly when the last of them lets go.
925
+
926
+ Because `@deepseek-ai/dsh-mcp-client` reserves a `serverName` per *registration
927
+ scope*, two different projects may declare the same name (`rider`, `gitea`, …)
928
+ without colliding with each other or with the profile.
929
+
930
+ ```
931
+ profile scope : gitea, context7, ... → every session
932
+ agent scope A : .dsh/mcp.json of project A → only sessions in A
933
+ agent scope B : .dsh/mcp.json of project B → only sessions in B
934
+ ```
935
+
936
+ ## Bundle format (do not "fix" this)
937
+
938
+ DSH does not `import` a plugin bundle. The web client concatenates several
939
+ plugins' `client.js` into **one classic script** and materializes each through a
940
+ Lazy-CJS module table:
941
+
942
+ ```js
943
+ // lib/client.js — generated by scripts/wrap-client.mjs
944
+ window.__ModuleLoader__.load({
945
+ id: 'dsh-project-mcp',
946
+ factory: (require) => { /* CJS body; require('react') resolves against the platform table */ },
947
+ })
948
+ ```
949
+
950
+ Three consequences, each guarded by a check:
951
+
952
+ - the client target builds as **CJS** (`tsdown format: ['cjs']`) and is wrapped
953
+ by `scripts/wrap-client.mjs`, which runs as part of `pnpm build`;
954
+ - the bundle must contain no statement-level `import`/`export` — it would be a
955
+ syntax error that aborts the whole batch, taking unrelated plugins down;
956
+ - every `require(...)` must be a baseline module (`react`, `react/jsx-runtime`,
957
+ …). Anything else throws at materialization, because the `require` handed to a
958
+ factory is synchronous and cannot await a fetch.
959
+
960
+ `tests/bundle.spec.ts` replays that exact load path against the built bundle and
961
+ `pnpm audit` re-checks the shell, the ESM-free body and the module requests.
962
+
963
+ ## Layout
964
+
965
+ ```
966
+ src/index.ts plugin entry: Config schema, apply, projectMcp service
967
+ src/runtime.ts per-agent scope minting, mounting, diffing, watchers
968
+ src/discovery.ts project root + document paths + credentials + project .env files
969
+ src/parse.ts mcpServers -> mcp-client config, ${VAR}/${input:...}, dotenv/credentials, merge
970
+ src/write.ts editor write path: revision, declaration, atomic replace
971
+ src/ui.ts host HTTP routes: snapshot, events (SSE), sync, retry, release, save, pin, policy
972
+ src/usage.ts durable per-project tool-call counters
973
+ src/policy.ts durable per-project tool policy: mode (disclosure/direct/off), pins
974
+ src/guidance.ts project-MCP guidance section: deterministic text + wiring
975
+ src/types.ts snapshot/row vocabulary
976
+ src/client/ browser half: sidebar tab, side card settings, native
977
+ Settings page (`settings.section`), shared view helpers
978
+ tests/ unit tests (parse, discovery, runtime, guidance, both views),
979
+ plus a load-path guard for the wrapped client bundle
980
+ scripts/ MCP fixture server, live smoke test, resource audit,
981
+ project-config checker, bundle wrapper, panel screenshot and
982
+ the surface-parity check
983
+ ```