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/src/index.ts ADDED
@@ -0,0 +1,685 @@
1
+ /**
2
+ * `dsh-project-mcp` — per-project MCP servers for DeepSeek Harness.
3
+ *
4
+ * The host half reads a project's own MCP documents and mounts the declared
5
+ * servers on the Cordis context of every session (`agent`) whose working
6
+ * directory resolves to that project. Servers therefore exist exactly where
7
+ * they are declared, and two projects may declare the same `serverName`
8
+ * without colliding with each other or with profile-level entries.
9
+ *
10
+ * Sources, in increasing priority (later documents override by `serverName`):
11
+ * 1. the global documents this deployment lists in `globalFiles` — none by default
12
+ * 2. the project-relative documents it lists in `localFiles` —
13
+ * `<project>/.dsh/mcp.json` out of the box
14
+ *
15
+ * @module dsh-project-mcp
16
+ */
17
+
18
+ import type { Context } from '@deepseek-ai/cordis'
19
+ import z from '@deepseek-ai/schemastery'
20
+ import {
21
+ DEFAULT_ACTIVATION_ENABLED,
22
+ DEFAULT_ACTIVATION_MIN_CALLS,
23
+ DEFAULT_ACTIVATION_SEEDED,
24
+ DEFAULT_AUTO_ACTIVATION_LIMIT,
25
+ DEFAULT_AUTO_ACTIVATION_STICKY_STEPS,
26
+ DEFAULT_TOOL_BUDGET_CHARS,
27
+ DEFAULT_TOOL_IDLE_MS,
28
+ } from './activation.ts'
29
+ import {
30
+ DEFAULT_FILE_MARKERS,
31
+ DEFAULT_GLOBAL_FILES,
32
+ DEFAULT_LOCAL_FILES,
33
+ DEFAULT_PROJECT_MARKERS,
34
+ defaultCredentialsPath,
35
+ } from './discovery.ts'
36
+ import { DEFAULT_GUIDANCE_ENABLED } from './guidance.ts'
37
+ import { isValidLocalPrefix } from './naming.ts'
38
+ import { PolicyStore } from './policy.ts'
39
+ import { ProjectMcpRuntime } from './runtime.ts'
40
+ import type {
41
+ AgentLike,
42
+ AgentScopeLike,
43
+ PolicyOutcome,
44
+ RuntimeConfig,
45
+ RuntimeOptions,
46
+ SaveOutcome,
47
+ } from './runtime.ts'
48
+ import type { ConflictRequest, PinRequest, PolicyRequest, SaveRequest } from './shared.ts'
49
+ import { UsageStore, observeToolResults } from './usage.ts'
50
+ import type { ToolResultEventLike, ToolResultLike } from './usage.ts'
51
+ import { disposeRegistration, registerRoutes } from './ui.ts'
52
+ import type { WebServerLike } from './ui.ts'
53
+ import type { McpSnapshot, SnapshotChange } from './types.ts'
54
+
55
+ export { ProjectMcpRuntime, mountTrigger } from './runtime.ts'
56
+ export type {
57
+ AgentLike,
58
+ AgentMounts,
59
+ AgentScopeLike,
60
+ MountDecision,
61
+ MountTrigger,
62
+ PolicyOutcome,
63
+ PolicySource,
64
+ RuntimeConfig,
65
+ RuntimeOptions,
66
+ SaveOutcome,
67
+ UsageSource,
68
+ } from './runtime.ts'
69
+ export {
70
+ POLICY_FILE_NAME,
71
+ POLICY_VERSION,
72
+ PolicyStore,
73
+ TOOL_MODES,
74
+ isToolMode,
75
+ parsePolicyDocument,
76
+ policyFor,
77
+ withMode,
78
+ withPin,
79
+ } from './policy.ts'
80
+ export type {
81
+ PolicyDocument,
82
+ PolicyLogger,
83
+ PolicyState,
84
+ PolicyStoreOptions,
85
+ } from './policy.ts'
86
+ export { findProjectRoot, configDirectories, expandConfigPath, globalConfigPaths, localConfigPaths } from './discovery.ts'
87
+ export { parseDocument, mergeEntries, parseCredentials } from './parse.ts'
88
+ export {
89
+ DEFAULT_ACTIVATION_ENABLED,
90
+ DEFAULT_ACTIVATION_MIN_CALLS,
91
+ DEFAULT_ACTIVATION_SEEDED,
92
+ DEFAULT_SEARCH_LIMIT,
93
+ DEFAULT_TOOL_IDLE_MS,
94
+ MAX_SEARCH_LIMIT,
95
+ MAX_SEARCH_TOKENS,
96
+ SEARCH_TOOL_NAME,
97
+ activate,
98
+ createActivationState,
99
+ createSearchTool,
100
+ installActivation,
101
+ noteUse,
102
+ onCompaction,
103
+ presentedNames,
104
+ pruneIdle,
105
+ seedFromUsage,
106
+ withActiveTools,
107
+ } from './activation.ts'
108
+ export type {
109
+ ActivationContextLike,
110
+ ActivationState,
111
+ ActivationWiringOptions,
112
+ AssembleListener,
113
+ AssemblyLike,
114
+ ListenerLike,
115
+ SearchToolOptions,
116
+ SeedOptions,
117
+ SessionEventLike,
118
+ TextBlockLike,
119
+ ToolDefinitionLike,
120
+ ToolSchemaLike,
121
+ } from './activation.ts'
122
+ export {
123
+ DEFAULT_GUIDANCE_ENABLED,
124
+ GUIDANCE_SECTION_NAME,
125
+ MAX_GUIDANCE_CHARS,
126
+ MAX_GUIDANCE_PURPOSE,
127
+ MAX_GUIDANCE_SERVERS,
128
+ MAX_GUIDANCE_HIDDEN_NAMES,
129
+ buildGuidance,
130
+ installGuidance,
131
+ projectLabel,
132
+ } from './guidance.ts'
133
+ export type {
134
+ GuidanceContextLike,
135
+ GuidanceInput,
136
+ GuidancePromptLike,
137
+ GuidancePromptScopeLike,
138
+ GuidanceSectionLike,
139
+ GuidanceServer,
140
+ GuidanceWiringOptions,
141
+ } from './guidance.ts'
142
+ export {
143
+ USAGE_FILE_NAME,
144
+ USAGE_VERSION,
145
+ UsageStore,
146
+ matchServer,
147
+ observeToolResults,
148
+ parseUsageDocument,
149
+ recordUsage,
150
+ usageEventFor,
151
+ } from './usage.ts'
152
+ export { createRouteHandler, disposeRegistration, registerRoutes } from './ui.ts'
153
+ export { ROUTE_PREFIX, TAB_ID } from './shared.ts'
154
+ export type { RouteHandler, WebServerLike } from './ui.ts'
155
+ export type {
156
+ McpSnapshot,
157
+ ProjectSnapshot,
158
+ ServerRow,
159
+ ServerStatus,
160
+ ServerUsage,
161
+ SessionSnapshot,
162
+ SnapshotChange,
163
+ SnapshotIssue,
164
+ } from './types.ts'
165
+ export type {
166
+ ToolResultEventLike,
167
+ ToolResultLike,
168
+ ToolResultObserverOptions,
169
+ UsageCall,
170
+ UsageDocument,
171
+ UsageEvent,
172
+ UsageLogger,
173
+ UsageState,
174
+ UsageStoreOptions,
175
+ } from './usage.ts'
176
+
177
+ /**
178
+ * Plugin config: everything two deployments may want to set differently.
179
+ *
180
+ * Live editing: on DSH ≥ 0.1.7 the keys of {@link VOLATILE_CONFIG_KEYS} arrive
181
+ * not as plain values but as volatile refs (`{ get(): T }`, see
182
+ * {@link VolatileLike}) that the host re-points on every profile edit and
183
+ * re-reads on `loader/volatile-update`. Every read of those keys goes through
184
+ * {@link liveValue}, which accepts both shapes, so a plain object — yaml
185
+ * config on an older host, and every test fixture — keeps working unchanged.
186
+ */
187
+ export interface Config {
188
+ /** Master switch; `false` mounts nothing and reads nothing. */
189
+ enabled?: boolean
190
+ /**
191
+ * Project-relative MCP documents to read, lowest priority first — a later
192
+ * document overrides an earlier entry of the same `serverName`. A spec is
193
+ * relative to the project root, or absolute, or `~/…` / `$DSH_HOME/…`.
194
+ * Default: `['.dsh/mcp.json']`.
195
+ */
196
+ localFiles?: string[]
197
+ /**
198
+ * Global MCP documents read before a project's own, lowest priority first.
199
+ * A relative spec resolves against `$HOME`; `~`, `$DSH_HOME` and absolute
200
+ * paths work as in {@link localFiles}. Empty — the default — reads none, so
201
+ * a project never inherits a server it did not declare.
202
+ *
203
+ * A boolean is accepted as a **migration guard only**, for a config written
204
+ * when this key was the switch "also read `~/.dsh/mcp.json` and
205
+ * `~/.kimi-code/mcp.json`": `true` reads `~/.dsh/mcp.json`, `false` reads
206
+ * nothing. Set a list instead.
207
+ */
208
+ globalFiles?: string[] | boolean
209
+ /** Read `<project>/.env` and `<project>/.dsh/.env` for `${...}` values. */
210
+ envFiles?: boolean
211
+ /** Values for `${input:NAME}` references, consulted before env and credentials. */
212
+ inputs?: Record<string, string>
213
+ /** Directory names that terminate the upward project-root walk. */
214
+ projectMarkers?: string[]
215
+ /** File suffixes that also terminate the upward project-root walk. */
216
+ fileMarkers?: string[]
217
+ /** Timeout for every generated mcp-client config. */
218
+ toolCallTimeoutMs?: number
219
+ /** Whether a failed initial MCP connection should fail the mount. */
220
+ failOnStartupError?: boolean
221
+ /** Report a mount that produced no tool within this window as an error row; `0` disables. */
222
+ connectTimeoutMs?: number
223
+ /** Mount a session's project on its first turn instead of at session creation. */
224
+ lazy?: boolean
225
+ /** Release a session's mounts after this much inactivity; `0` disables. */
226
+ idleTimeoutMs?: number
227
+ /** How long the first step of a turn may wait for a pending mount; `0` never waits. */
228
+ activationWaitMs?: number
229
+ /** Profile-level `serverName` reservations win; the project row becomes `conflict`. */
230
+ profileWins?: boolean
231
+ /**
232
+ * Local namespace a project entry mounts under when the profile already owns
233
+ * its `serverName` and the user chose to see this project's copy as well,
234
+ * at most five characters (`[A-Za-z0-9_-]`, {@link isValidLocalPrefix}).
235
+ * Empty — the default — derives one from the project's own folder, so a
236
+ * conflict has an answer without a setting. Only the local answer reads it:
237
+ * the choice that mounts the entry under its declared name needs no prefix.
238
+ */
239
+ localPrefix?: string
240
+ /** Watch project config documents for edits and re-sync. */
241
+ watch?: boolean
242
+ /** Debounce applied to watcher and lifecycle events (ms). */
243
+ debounceMs?: number
244
+ /** Safety-net rescan interval (ms). */
245
+ rescanIntervalMs?: number
246
+ /** Credentials document consulted for `${input:NAME}` values. */
247
+ credentialsFile?: string
248
+ /**
249
+ * Offer the session's MCP tools through `mcp_search_tools` + activation, and
250
+ * put the active ones back into each assembled request. `false` restores the
251
+ * plain registry presentation: every mounted tool is always listed.
252
+ */
253
+ activationEnabled?: boolean
254
+ /** Tools the durable counters may seed into the always-offered baseline; `0` seeds none. */
255
+ activationSeeded?: number
256
+ /** Calls one tool needs in the counters before it is seeded into the baseline. */
257
+ activationMinCalls?: number
258
+ /** Drop a session-activated tool after this long without a call; `0` disables. */
259
+ toolIdleMs?: number
260
+ /**
261
+ * Publish one short project-MCP guidance section in the session's system
262
+ * prompt, ahead of the per-server `mcp:<server>` instruction blocks, so the
263
+ * model knows the rest of the project's tools can be requested. `false`
264
+ * registers no section at all.
265
+ */
266
+ guidanceEnabled?: boolean
267
+ /**
268
+ * Cap on the names the context-driven tier offers at once; `0` disables the
269
+ * tier. Optional so a config object that predates this feature keeps the
270
+ * shipped default.
271
+ */
272
+ activationAutoLimit?: number
273
+ /** Extra advances one context-driven offer survives after leaving the ranking. */
274
+ activationAutoStickySteps?: number
275
+ /**
276
+ * Serialized size of a session's MCP surface, in characters, above which its
277
+ * tools are offered on demand instead of being listed; `0` defers every
278
+ * surface, however small.
279
+ */
280
+ activationToolBudgetChars?: number
281
+ /**
282
+ * Permit the panel to write the documents of the `globalFiles` list. `false`
283
+ * keeps them read-only; a write also needs an explicit per-write consent, so
284
+ * both gates must be open. Default `false`.
285
+ */
286
+ allowGlobalWrite?: boolean
287
+ }
288
+
289
+ const DEFAULTS = {
290
+ enabled: true,
291
+ localFiles: [...DEFAULT_LOCAL_FILES],
292
+ globalFiles: [...DEFAULT_GLOBAL_FILES],
293
+ envFiles: true,
294
+ toolCallTimeoutMs: 60_000,
295
+ failOnStartupError: false,
296
+ connectTimeoutMs: 60_000,
297
+ lazy: true,
298
+ idleTimeoutMs: 300_000,
299
+ activationWaitMs: 2_000,
300
+ profileWins: true,
301
+ localPrefix: '',
302
+ watch: true,
303
+ debounceMs: 300,
304
+ rescanIntervalMs: 10_000,
305
+ activationEnabled: DEFAULT_ACTIVATION_ENABLED,
306
+ activationSeeded: DEFAULT_ACTIVATION_SEEDED,
307
+ activationMinCalls: DEFAULT_ACTIVATION_MIN_CALLS,
308
+ toolIdleMs: DEFAULT_TOOL_IDLE_MS,
309
+ guidanceEnabled: DEFAULT_GUIDANCE_ENABLED,
310
+ activationAutoLimit: DEFAULT_AUTO_ACTIVATION_LIMIT,
311
+ activationAutoStickySteps: DEFAULT_AUTO_ACTIVATION_STICKY_STEPS,
312
+ activationToolBudgetChars: DEFAULT_TOOL_BUDGET_CHARS,
313
+ allowGlobalWrite: false,
314
+ } as const
315
+
316
+ const nonEmptyString = z.string().min(1)
317
+
318
+ /**
319
+ * The volatile-ref shape a DSH ≥ 0.1.7 host hands a volatile config field: a
320
+ * stable reference whose `get()` reads the current, live-edited value.
321
+ * Declared locally so no cordis version is needed to name it; an older host
322
+ * passes the plain value instead, which {@link liveValue} also accepts.
323
+ */
324
+ interface VolatileLike<T> {
325
+ get(): T
326
+ }
327
+
328
+ // The loader's event typing ships with `@deepseek-ai/cordis-plugin-loader`,
329
+ // which this plugin does not depend on; declaring the one event it listens to
330
+ // keeps the dependency surface unchanged. The signature matches the loader's
331
+ // own augmentation, so both merge cleanly where the loader's types are loaded.
332
+ declare module '@deepseek-ai/cordis' {
333
+ interface Events {
334
+ /**
335
+ * Volatile config values were committed into the running fiber without a
336
+ * remount; dispatched to the owning fiber only.
337
+ * @param paths - changed config paths as key arrays.
338
+ */
339
+ 'loader/volatile-update'(paths: readonly (readonly string[])[]): void
340
+ }
341
+ }
342
+
343
+ /**
344
+ * Mark a config field volatile — live-editable from Plugins → dsh-project-mcp
345
+ * on DSH ≥ 0.1.7 — when the installed schemastery knows the flag. An older
346
+ * schemastery at runtime gets the schema back unchanged, and the field stays
347
+ * yaml-only there.
348
+ */
349
+ function volatileField<S>(schema: S): S {
350
+ const mark = (schema as unknown as { volatile?: unknown }).volatile
351
+ if (typeof mark !== 'function') return schema
352
+ return (mark as (this: unknown) => S).call(schema)
353
+ }
354
+
355
+ /**
356
+ * Read one config field that may be a live-edited volatile ref.
357
+ * @param field - plain value, or a {@link VolatileLike} ref wrapping it.
358
+ * @returns the current value, whichever shape arrived.
359
+ */
360
+ export function liveValue<T>(field: T | VolatileLike<T> | undefined): T | undefined {
361
+ if (
362
+ typeof field === 'object' &&
363
+ field !== null &&
364
+ typeof (field as VolatileLike<T>).get === 'function'
365
+ ) {
366
+ return (field as VolatileLike<T>).get()
367
+ }
368
+ return field as T | undefined
369
+ }
370
+
371
+ /**
372
+ * The {@link Config} keys a DSH ≥ 0.1.7 host may live-edit without restarting
373
+ * the entry: all of them are read at use time, so merging them into the
374
+ * running config is safe. Every other key is structural or boot-time
375
+ * (documents, markers, credentials, the watch switch) and stays yaml-only.
376
+ */
377
+ export const VOLATILE_CONFIG_KEYS: readonly (keyof RuntimeConfig)[] = [
378
+ 'activationEnabled',
379
+ 'activationSeeded',
380
+ 'activationMinCalls',
381
+ 'toolIdleMs',
382
+ 'guidanceEnabled',
383
+ 'activationAutoLimit',
384
+ 'activationAutoStickySteps',
385
+ 'activationToolBudgetChars',
386
+ 'allowGlobalWrite',
387
+ 'envFiles',
388
+ 'lazy',
389
+ 'localPrefix',
390
+ 'profileWins',
391
+ 'connectTimeoutMs',
392
+ 'toolCallTimeoutMs',
393
+ 'idleTimeoutMs',
394
+ 'debounceMs',
395
+ 'activationWaitMs',
396
+ ]
397
+
398
+ /** Validated Loader schema for {@link Config}. */
399
+ export const Config: z<Config> = z.object({
400
+ enabled: z.boolean().default(DEFAULTS.enabled),
401
+ localFiles: z.array(nonEmptyString).default([...DEFAULT_LOCAL_FILES]),
402
+ // The union is a migration guard, not a second setting: a document still
403
+ // carrying the boolean this key used to be validates instead of failing the
404
+ // entry, and `configuredFiles` reads its intent.
405
+ globalFiles: z.union([z.array(nonEmptyString), z.boolean()]).default([...DEFAULT_GLOBAL_FILES]),
406
+ envFiles: volatileField(z.boolean().default(DEFAULTS.envFiles)),
407
+ inputs: z.dict(String).default({}),
408
+ projectMarkers: z.array(nonEmptyString).default([...DEFAULT_PROJECT_MARKERS]),
409
+ fileMarkers: z.array(nonEmptyString).default([...DEFAULT_FILE_MARKERS]),
410
+ toolCallTimeoutMs: volatileField(z.number().step(1).min(1).default(DEFAULTS.toolCallTimeoutMs)),
411
+ failOnStartupError: z.boolean().default(DEFAULTS.failOnStartupError),
412
+ connectTimeoutMs: volatileField(z.number().step(1).min(0).default(DEFAULTS.connectTimeoutMs)),
413
+ lazy: volatileField(z.boolean().default(DEFAULTS.lazy)),
414
+ idleTimeoutMs: volatileField(z.number().step(1).min(0).default(DEFAULTS.idleTimeoutMs)),
415
+ activationWaitMs: volatileField(
416
+ z.number().step(1).min(0).max(30_000).default(DEFAULTS.activationWaitMs),
417
+ ),
418
+ profileWins: volatileField(z.boolean().default(DEFAULTS.profileWins)),
419
+ localPrefix: volatileField(z.string().default(DEFAULTS.localPrefix)),
420
+ watch: z.boolean().default(DEFAULTS.watch),
421
+ debounceMs: volatileField(z.number().step(1).min(0).max(60_000).default(DEFAULTS.debounceMs)),
422
+ rescanIntervalMs: z.number().step(1).min(1_000).default(DEFAULTS.rescanIntervalMs),
423
+ credentialsFile: z.string().default(''),
424
+ activationEnabled: volatileField(z.boolean().default(DEFAULTS.activationEnabled)),
425
+ activationSeeded: volatileField(z.number().step(1).min(0).default(DEFAULTS.activationSeeded)),
426
+ activationMinCalls: volatileField(
427
+ z.number().step(1).min(0).default(DEFAULTS.activationMinCalls),
428
+ ),
429
+ toolIdleMs: volatileField(z.number().step(1).min(0).default(DEFAULTS.toolIdleMs)),
430
+ guidanceEnabled: volatileField(z.boolean().default(DEFAULTS.guidanceEnabled)),
431
+ activationAutoLimit: volatileField(
432
+ z.number().step(1).min(0).default(DEFAULTS.activationAutoLimit),
433
+ ),
434
+ activationAutoStickySteps: volatileField(
435
+ z.number().step(1).min(0).default(DEFAULTS.activationAutoStickySteps),
436
+ ),
437
+ activationToolBudgetChars: volatileField(
438
+ z.number().step(1).min(0).default(DEFAULTS.activationToolBudgetChars),
439
+ ),
440
+ allowGlobalWrite: volatileField(z.boolean().default(DEFAULTS.allowGlobalWrite)),
441
+ })
442
+
443
+ /** Cordis plugin name used by loader diagnostics. */
444
+ export const name = 'project-mcp'
445
+
446
+ /** Services required before project MCP servers can be mounted. */
447
+ export const inject = ['tools']
448
+
449
+ /** Service name under which the runtime publishes its snapshot. */
450
+ export const SERVICE_NAME = 'projectMcp'
451
+
452
+ /** Read-only handle published as the `projectMcp` service. */
453
+ export interface ProjectMcpService {
454
+ /** Current rows per project with live sessions, merged and split per session. */
455
+ snapshot(): McpSnapshot
456
+ /**
457
+ * Run one reconciliation pass immediately and await it, as the operator call:
458
+ * it may start a session's declared servers without that session having
459
+ * started a turn. Every other pass — a turn, an event, the rescan tick —
460
+ * mounts only the sessions whose own working directory asked for their
461
+ * project.
462
+ * @param projectRoot - restricts the pass to one project's sessions.
463
+ */
464
+ syncNow(projectRoot?: string): Promise<void>
465
+ /**
466
+ * Ask for the same pass and answer at once, without waiting for it: the
467
+ * panel's `Sync`. Scripted reconciliation awaits {@link ProjectMcpService.syncNow}.
468
+ * @param projectRoot - restricts the pass to one project's sessions.
469
+ */
470
+ syncSoon(projectRoot?: string): void
471
+ /**
472
+ * Drop the failed mounts and re-mount them (after fixing their cause). Answers
473
+ * as soon as they are dropped; the pass that mounts them again runs in the
474
+ * background, because waiting for it is what made the panel's `Retry` look
475
+ * hung while a server was still connecting.
476
+ * @param projectRoot - restricts the drop and the pass to one project.
477
+ */
478
+ retry(projectRoot?: string): Promise<void>
479
+ /**
480
+ * Watch the picture instead of asking for it: the listener is told the current
481
+ * state at once, then once per change that changes something. Backs the
482
+ * panel's status channel, so an open panel polls nothing.
483
+ * @param listener - told the revision and the whole snapshot it belongs to.
484
+ * @returns a disposer that stops watching.
485
+ */
486
+ subscribe(listener: (change: SnapshotChange) => void): () => void
487
+ /** Give one session's servers back now, or every mounted session's when no id is given. */
488
+ release(agentId?: string): Promise<void>
489
+ /**
490
+ * Write one edited entry back to the document that declares it.
491
+ * @param request - entry body, declaring document and the revision it was read at.
492
+ * @returns the fresh snapshot, or the coded refusal the route maps to a status.
493
+ */
494
+ save(request: SaveRequest): Promise<SaveOutcome>
495
+ /**
496
+ * Pin or unpin one tool of one project. Durable, and never a rescan: the policy
497
+ * is not part of any declaring document.
498
+ * @param request - project root, public tool name and the wanted pin state.
499
+ * @returns the fresh snapshot, or the coded refusal the route maps to a status.
500
+ */
501
+ setPin(request: PinRequest): PolicyOutcome
502
+ /**
503
+ * Store one project's tool mode (`disclosure` | `direct` | `off`).
504
+ * @param request - project root and the mode to store.
505
+ * @returns the fresh snapshot, or the coded refusal the route maps to a status.
506
+ */
507
+ setPolicy(request: PolicyRequest): PolicyOutcome
508
+ /**
509
+ * Choose which declaration of one contested `serverName` this project shows.
510
+ * Durable, and followed by a reconcile: the choice is what moves the entry
511
+ * between a conflict report and a mount under its local name.
512
+ * @param request - project root, contested name and the declaration to show.
513
+ * @returns the fresh snapshot, or the coded refusal the route maps to a status.
514
+ */
515
+ setConflictChoice(request: ConflictRequest): PolicyOutcome
516
+ }
517
+
518
+ /**
519
+ * Mount project-declared MCP servers per session scope.
520
+ * @param ctx - host context of the plugin entry.
521
+ * @param config - validated plugin configuration.
522
+ */
523
+ export async function apply(ctx: Context, config: Config): Promise<void> {
524
+ if (config.enabled === false) {
525
+ ctx.logger.info('project-mcp: disabled by configuration')
526
+ return
527
+ }
528
+ const usage = new UsageStore({ logger: ctx.logger })
529
+ // The per-project tool policy is durable state of the same kind as the
530
+ // counters, so it is loaded once here and published by the same runtime.
531
+ const policy = new PolicyStore({ logger: ctx.logger })
532
+ const runtime = new ProjectMcpRuntime(ctx, resolveConfig(config), { usage, policy })
533
+ // A volatile-capable host (DSH ≥ 0.1.7) re-points the volatile refs inside
534
+ // `config` on every profile edit and announces it here instead of restarting
535
+ // the entry; an older host never emits the event, so this subscribes
536
+ // unconditionally. `resolveConfig` re-reads the refs through `liveValue`,
537
+ // and the runtime merges only the volatile keys.
538
+ ctx.on('loader/volatile-update', () => {
539
+ runtime.applyLiveConfig(resolveConfig(config))
540
+ })
541
+ const service: ProjectMcpService = {
542
+ snapshot: () => runtime.snapshot(),
543
+ syncNow: (projectRoot) => runtime.syncNow(projectRoot),
544
+ syncSoon: (projectRoot) => runtime.syncSoon(projectRoot),
545
+ retry: (projectRoot) => runtime.retry(projectRoot),
546
+ release: (agentId) => runtime.release(agentId),
547
+ save: (request) => runtime.saveEntry(request),
548
+ setPin: (request) => runtime.setPin(request),
549
+ setPolicy: (request) => runtime.setPolicy(request),
550
+ setConflictChoice: (request) => runtime.setConflictChoice(request),
551
+ subscribe: (listener) => runtime.subscribe(listener),
552
+ }
553
+ // `agents` exists in every interactive composition but is resolved lazily so
554
+ // the plugin still loads when a deployment mounts it without the agent plane.
555
+ ctx.inject(['agents'], (scope) => {
556
+ runtime.attach(scope as unknown as AgentScopeLike)
557
+ scope.provide(SERVICE_NAME, service)
558
+ })
559
+ // The sidebar panel runs in the browser half, where it can reach neither this
560
+ // service nor `ctx.betterSidebar` of the host half: publish the same surface
561
+ // over HTTP when the composition has a web server.
562
+ ctx.inject(['webServer'], (scope) => {
563
+ const webServer = (scope as unknown as { webServer?: WebServerLike }).webServer
564
+ if (webServer === undefined) return
565
+ scope.effect(() => {
566
+ const registration = registerRoutes(webServer, service)
567
+ return () => disposeRegistration(registration)
568
+ }, 'project-mcp: panel routes')
569
+ })
570
+ ctx.effect(
571
+ () => () => {
572
+ void runtime.disposeAll()
573
+ },
574
+ 'project-mcp: runtime',
575
+ )
576
+ // Counters ride the registry's own result event: one listener for every
577
+ // agent, attributed through the runtime's agent -> project mapping, so only
578
+ // servers this plugin mounted can be counted. Activation freshness rides the
579
+ // same event — a real call is what keeps an activated tool offered — so no
580
+ // second `tools/result` subscription exists.
581
+ ctx.effect(() => {
582
+ const dispose = observeToolResults({
583
+ on: (event, handler) =>
584
+ ctx.on(event, (exec: ToolResultEventLike, result: ToolResultLike) => {
585
+ runtime.noteToolUse(exec.agent?.id, exec.name)
586
+ return handler(exec, result)
587
+ }),
588
+ mountsFor: (agentId) => runtime.mountsFor(agentId),
589
+ store: usage,
590
+ })
591
+ return () => {
592
+ dispose()
593
+ usage.dispose()
594
+ }
595
+ }, 'project-mcp: usage counters')
596
+ // The policy store owns the same debounced write the counters do, so it is
597
+ // flushed and stopped with the fiber that created it.
598
+ ctx.effect(
599
+ () => () => {
600
+ policy.dispose()
601
+ },
602
+ 'project-mcp: tool policy',
603
+ )
604
+ }
605
+
606
+ /**
607
+ * The local prefix one config asks for.
608
+ *
609
+ * A value the `serverName` alphabet cannot carry, or one longer than the five
610
+ * characters the panel promises, is refused rather than trimmed: a silently
611
+ * different namespace would rename a project's tools behind the user's back.
612
+ * The empty string — the default and the answer to a refused value — asks for
613
+ * the prefix derived from the project's own folder.
614
+ *
615
+ * @param value - raw `localPrefix` from the config.
616
+ * @returns a valid prefix, or `''` for the derived one.
617
+ */
618
+ function localPrefixOf(value: string | undefined): string {
619
+ if (value === undefined || value === '') return ''
620
+ if (value === value.trim() && isValidLocalPrefix(value)) return value
621
+ return ''
622
+ }
623
+
624
+ /**
625
+ * One configured document list, from either shape the config can carry.
626
+ *
627
+ * A list is used as written. A boolean is the migration guard of the key that
628
+ * used to be the switch "also read the global documents": `true` meant the
629
+ * documents in `legacyTrue` (what that switch turned on), `false` meant none.
630
+ * An absent value falls back to the default list.
631
+ *
632
+ * @param value - raw `localFiles` or `globalFiles`.
633
+ * @param fallback - list used when the config says nothing.
634
+ * @param legacyTrue - documents a legacy `true` stands for.
635
+ * @returns specs, lowest priority first, with blanks dropped.
636
+ */
637
+ function configuredFiles(
638
+ value: readonly string[] | boolean | undefined,
639
+ fallback: readonly string[],
640
+ legacyTrue: readonly string[],
641
+ ): string[] {
642
+ if (value === undefined) return [...fallback]
643
+ if (Array.isArray(value)) return value.filter((spec) => spec !== '')
644
+ return value ? [...legacyTrue] : []
645
+ }
646
+
647
+ /** Resolve the plugin config into the runtime's fully-defaulted shape. */
648
+ export function resolveConfig(config: Config): RuntimeConfig {
649
+ return {
650
+ localFiles: configuredFiles(config.localFiles, DEFAULTS.localFiles, DEFAULT_LOCAL_FILES),
651
+ // The only key whose boolean is legacy: it used to switch the DSH home
652
+ // document on, so that is what `true` keeps meaning here.
653
+ globalFiles: configuredFiles(config.globalFiles, DEFAULTS.globalFiles, ['$DSH_HOME/mcp.json']),
654
+ envFiles: liveValue(config.envFiles) ?? DEFAULTS.envFiles,
655
+ inputs: config.inputs ?? {},
656
+ projectMarkers: [...(config.projectMarkers ?? DEFAULT_PROJECT_MARKERS)],
657
+ fileMarkers: [...(config.fileMarkers ?? DEFAULT_FILE_MARKERS)],
658
+ toolCallTimeoutMs: liveValue(config.toolCallTimeoutMs) ?? DEFAULTS.toolCallTimeoutMs,
659
+ failOnStartupError: config.failOnStartupError ?? DEFAULTS.failOnStartupError,
660
+ connectTimeoutMs: liveValue(config.connectTimeoutMs) ?? DEFAULTS.connectTimeoutMs,
661
+ lazy: liveValue(config.lazy) ?? DEFAULTS.lazy,
662
+ idleTimeoutMs: liveValue(config.idleTimeoutMs) ?? DEFAULTS.idleTimeoutMs,
663
+ activationWaitMs: liveValue(config.activationWaitMs) ?? DEFAULTS.activationWaitMs,
664
+ profileWins: liveValue(config.profileWins) ?? DEFAULTS.profileWins,
665
+ localPrefix: localPrefixOf(liveValue(config.localPrefix)),
666
+ watch: config.watch ?? DEFAULTS.watch,
667
+ debounceMs: liveValue(config.debounceMs) ?? DEFAULTS.debounceMs,
668
+ rescanIntervalMs: config.rescanIntervalMs ?? DEFAULTS.rescanIntervalMs,
669
+ credentialsFile:
670
+ config.credentialsFile !== undefined && config.credentialsFile !== ''
671
+ ? config.credentialsFile
672
+ : defaultCredentialsPath(),
673
+ activationEnabled: liveValue(config.activationEnabled) ?? DEFAULTS.activationEnabled,
674
+ activationSeeded: liveValue(config.activationSeeded) ?? DEFAULTS.activationSeeded,
675
+ activationMinCalls: liveValue(config.activationMinCalls) ?? DEFAULTS.activationMinCalls,
676
+ toolIdleMs: liveValue(config.toolIdleMs) ?? DEFAULTS.toolIdleMs,
677
+ guidanceEnabled: liveValue(config.guidanceEnabled) ?? DEFAULTS.guidanceEnabled,
678
+ activationAutoLimit: liveValue(config.activationAutoLimit) ?? DEFAULTS.activationAutoLimit,
679
+ activationAutoStickySteps:
680
+ liveValue(config.activationAutoStickySteps) ?? DEFAULTS.activationAutoStickySteps,
681
+ activationToolBudgetChars:
682
+ liveValue(config.activationToolBudgetChars) ?? DEFAULTS.activationToolBudgetChars,
683
+ allowGlobalWrite: liveValue(config.allowGlobalWrite) ?? DEFAULTS.allowGlobalWrite,
684
+ }
685
+ }