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/policy.ts ADDED
@@ -0,0 +1,425 @@
1
+ /**
2
+ * Durable per-project tool policy for `dsh-project-mcp`.
3
+ *
4
+ * The panel lets a user decide how one project's MCP tools are offered — never
5
+ * defer (`direct`), do not offer them at all (`off`), or keep the shipped
6
+ * on-demand presentation (`disclosure`) — and which tool names are pinned. That
7
+ * decision is the same kind of state as the usage counters: remembered across
8
+ * sessions and restarts in one versioned document under `$DSH_HOME`, written
9
+ * atomically on a debounce, and never able to break a model request.
10
+ *
11
+ * The decision logic is pure ({@link policyFor}, {@link withMode},
12
+ * {@link withPin}) and the document only sits behind {@link PolicyStore}, so the
13
+ * model is testable without a filesystem. Absent file, absent project and absent
14
+ * field all mean {@link DEFAULT_TOOL_POLICY}, so a broken or hand-edited
15
+ * document can only ever fall back to the shipped behaviour.
16
+ *
17
+ * @module dsh-project-mcp/policy
18
+ */
19
+
20
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
21
+ import { dirname, join } from 'node:path'
22
+ import { dshHome } from './discovery.ts'
23
+ import { DEFAULT_TOOL_POLICY } from './types.ts'
24
+ import type { ConflictChoice, ToolMode, ToolPolicy } from './types.ts'
25
+
26
+ /** Current on-disk document version; another version is ignored, not migrated. */
27
+ export const POLICY_VERSION = 1
28
+
29
+ /** Policy document name under `$DSH_HOME`, next to the usage counters. */
30
+ export const POLICY_FILE_NAME = 'dsh-project-mcp-policy.json'
31
+
32
+ /** Every mode a request may store, in the order the type declares them. */
33
+ export const TOOL_MODES: readonly ToolMode[] = ['disclosure', 'direct', 'off']
34
+
35
+ /** Policy of every project ever configured, keyed by project root. */
36
+ export type PolicyState = Record<string, ToolPolicy>
37
+
38
+ /** The durable policy document as written to disk. */
39
+ export interface PolicyDocument {
40
+ /** Document version; a reader that does not know it starts clean. */
41
+ version: typeof POLICY_VERSION
42
+ /** Policy of every project the user configured. */
43
+ projects: PolicyState
44
+ }
45
+
46
+ /** The logger surface the store uses; a Cordis logger satisfies it. */
47
+ export interface PolicyLogger {
48
+ /** Non-fatal report; the store never throws at its caller. */
49
+ warn(message: string): void
50
+ }
51
+
52
+ /** Construction options for {@link PolicyStore}; production uses the defaults. */
53
+ export interface PolicyStoreOptions {
54
+ /** Absolute document path; defaults to `$DSH_HOME/dsh-project-mcp-policy.json`. */
55
+ file?: string
56
+ /** Debounce before a policy change reaches disk. */
57
+ flushMs?: number
58
+ /** Sink for a corrupt document or a failed write. */
59
+ logger?: PolicyLogger
60
+ }
61
+
62
+ /** Debounce that keeps a panel click off the filesystem. */
63
+ const DEFAULT_FLUSH_MS = 1_000
64
+
65
+ /**
66
+ * The shape `@deepseek-ai/dsh-mcp-client` accepts for a reserved `serverName`,
67
+ * narrowed to a name that may open a stored conflict key: a key that fails it is
68
+ * a hand-edit or an array index, and never a server this host could mount.
69
+ */
70
+ const SERVER_NAME_SHAPE = /^[A-Za-z_][A-Za-z0-9_-]*$/
71
+
72
+ /**
73
+ * Whether a value is one of the modes this plugin stores.
74
+ *
75
+ * The routes read an untrusted JSON body, so the check belongs here rather than
76
+ * in the type system: a body that names an unknown mode is refused instead of
77
+ * being stored as a mode no assembly would know what to do with.
78
+ *
79
+ * @param value - parsed request or document value.
80
+ * @returns `true` when the value is a {@link ToolMode}.
81
+ */
82
+ export function isToolMode(value: unknown): value is ToolMode {
83
+ return typeof value === 'string' && (TOOL_MODES as readonly string[]).includes(value)
84
+ }
85
+
86
+ /**
87
+ * The policy in force for one project.
88
+ *
89
+ * Pure: it reads the state only. An absent project is the shipped default rather
90
+ * than an error, which is what makes a fresh install behave exactly like the
91
+ * plugin before this document existed.
92
+ *
93
+ * @param state - policies before the read.
94
+ * @param projectRoot - project root the policy belongs to.
95
+ * @returns the stored policy, or {@link DEFAULT_TOOL_POLICY} when there is none.
96
+ */
97
+ export function policyFor(state: PolicyState, projectRoot: string): ToolPolicy {
98
+ return state[projectRoot] ?? DEFAULT_TOOL_POLICY
99
+ }
100
+
101
+ /**
102
+ * Whether a value is one of the conflict answers this plugin stores.
103
+ *
104
+ * Read from an untrusted route body and from a hand-edited document, so the
105
+ * check lives here: a body that names an answer no build knows is refused
106
+ * instead of stored.
107
+ *
108
+ * @param value - parsed request or document value.
109
+ * @returns `true` when the value is a {@link ConflictChoice}.
110
+ */
111
+ export function isConflictChoice(value: unknown): value is ConflictChoice {
112
+ return value === 'profile' || value === 'local' || value === 'native'
113
+ }
114
+
115
+ /**
116
+ * What the user chose for one contested `serverName`.
117
+ *
118
+ * Pure: the absence of a choice is the shipped answer — the profile's instance
119
+ * keeps the name — so a project that never saw the toggle behaves exactly like
120
+ * the plugin before the choice existed.
121
+ *
122
+ * @param state - policies before the read.
123
+ * @param projectRoot - project root the name belongs to.
124
+ * @param server - contested `serverName` as declared.
125
+ * @returns the stored answer, or `'profile'` when there is none.
126
+ */
127
+ export function choiceFor(state: PolicyState, projectRoot: string, server: string): ConflictChoice {
128
+ return aliasesOf(state[projectRoot])[server] ?? 'profile'
129
+ }
130
+
131
+ /** The choices of one policy, treating an absent map and an empty one alike. */
132
+ export function aliasesOf(policy: ToolPolicy | undefined): Readonly<Record<string, ConflictChoice>> {
133
+ return policy?.aliases ?? {}
134
+ }
135
+
136
+ /**
137
+ * Store one contested name's answer, keeping the mode, the pins and the other
138
+ * names.
139
+ *
140
+ * Pure and idempotent. Choosing the profile again *removes* the entry rather
141
+ * than storing `'profile'`, because the absence already says exactly that: a
142
+ * document that kept both spellings of one answer would grow with every click
143
+ * and hand-edit its way into disagreeing with itself.
144
+ *
145
+ * @param state - policies before the change.
146
+ * @param projectRoot - project root the name belongs to.
147
+ * @param server - contested `serverName` as declared.
148
+ * @param choice - the answer to store.
149
+ * @returns a new state, or the input when the answer did not change.
150
+ */
151
+ export function withConflictChoice(
152
+ state: PolicyState,
153
+ projectRoot: string,
154
+ server: string,
155
+ choice: ConflictChoice,
156
+ ): PolicyState {
157
+ const current = policyFor(state, projectRoot)
158
+ if (choiceFor(state, projectRoot, server) === choice) return state
159
+ const aliases: Record<string, ConflictChoice> = { ...aliasesOf(current) }
160
+ if (choice === 'profile') delete aliases[server]
161
+ else aliases[server] = choice
162
+ return { ...state, [projectRoot]: normalizePolicy(current.mode, current.pins, aliases) }
163
+ }
164
+
165
+ /**
166
+ * Store one project's mode, keeping its pins.
167
+ *
168
+ * Pure and idempotent: storing the mode already in force returns the input state
169
+ * unchanged, so a panel that resubmits a switch does not schedule a write.
170
+ *
171
+ * @param state - policies before the change.
172
+ * @param projectRoot - project root the mode applies to.
173
+ * @param mode - the mode to store.
174
+ * @returns a new state, or the input when the mode did not change.
175
+ */
176
+ export function withMode(state: PolicyState, projectRoot: string, mode: ToolMode): PolicyState {
177
+ const current = policyFor(state, projectRoot)
178
+ if (current.mode === mode) return state
179
+ return { ...state, [projectRoot]: normalizePolicy(mode, current.pins, aliasesOf(current)) }
180
+ }
181
+
182
+ /**
183
+ * Pin or unpin one name of one project.
184
+ *
185
+ * Pins keep the order the user pinned them in — a pin is appended, an unpin
186
+ * removes exactly that name — because the panel lists them in that order and a
187
+ * re-pin after an unpin must not silently jump to the front. A name is never
188
+ * validated against the project's mounts here: a pin of a tool the project does
189
+ * not mount yet is kept, so a declaration that comes back finds its pin again.
190
+ *
191
+ * @param state - policies before the change.
192
+ * @param projectRoot - project root the pin belongs to.
193
+ * @param tool - public registry name, eg `mcp__tglider__workspace`.
194
+ * @param pinned - `true` pins it, `false` unpins it.
195
+ * @returns a new state, or the input when the list did not change.
196
+ */
197
+ export function withPin(
198
+ state: PolicyState,
199
+ projectRoot: string,
200
+ tool: string,
201
+ pinned: boolean,
202
+ ): PolicyState {
203
+ const current = policyFor(state, projectRoot)
204
+ const has = current.pins.includes(tool)
205
+ if (pinned === has) return state
206
+ const pins = pinned ? [...current.pins, tool] : current.pins.filter((name) => name !== tool)
207
+ return { ...state, [projectRoot]: normalizePolicy(current.mode, pins, aliasesOf(current)) }
208
+ }
209
+
210
+ /**
211
+ * One policy entry as the store keeps it: the mode and the pins always, the
212
+ * choices only when there are any.
213
+ *
214
+ * Written through here rather than assembled field by field at each call site,
215
+ * so the state the panel changes and the document that is flushed have one
216
+ * shape — an entry that carries an empty map in memory but not on disk would be
217
+ * a difference nothing could explain from the file.
218
+ *
219
+ * @param mode - mode in force.
220
+ * @param pins - pinned names, in order.
221
+ * @param aliases - choices per contested name.
222
+ * @returns the entry to store.
223
+ */
224
+ function normalizePolicy(
225
+ mode: ToolMode,
226
+ pins: readonly string[],
227
+ aliases: Readonly<Record<string, ConflictChoice>>,
228
+ ): ToolPolicy {
229
+ return Object.keys(aliases).length === 0 ? { mode, pins } : { mode, pins, aliases }
230
+ }
231
+
232
+ /**
233
+ * Parse one durable policy document.
234
+ *
235
+ * Anything this version cannot trust — malformed JSON, a foreign shape, or
236
+ * another version — yields `undefined` so the caller starts from the shipped
237
+ * default instead of throwing. A project entry is sanitized field by field: an
238
+ * unknown mode falls back to `disclosure` and a pin list keeps only non-empty
239
+ * deduplicated strings, so a hand-edited document cannot poison a request.
240
+ *
241
+ * @param text - raw document contents.
242
+ * @returns the policies, or `undefined` when the document is not usable.
243
+ */
244
+ export function parsePolicyDocument(text: string): PolicyState | undefined {
245
+ let value: unknown
246
+ try {
247
+ value = JSON.parse(text)
248
+ } catch {
249
+ return undefined
250
+ }
251
+ if (!isRecord(value)) return undefined
252
+ if (value.version !== POLICY_VERSION) return undefined
253
+ if (!isRecord(value.projects)) return undefined
254
+ const projects: PolicyState = {}
255
+ for (const [root, raw] of Object.entries(value.projects)) {
256
+ const policy = sanitizePolicy(raw)
257
+ if (policy === undefined) continue
258
+ // An entry that carries no mode, no pin and no choice says nothing the
259
+ // default would not say, so it is dropped rather than written back.
260
+ if (
261
+ policy.mode === DEFAULT_TOOL_POLICY.mode &&
262
+ policy.pins.length === 0 &&
263
+ Object.keys(aliasesOf(policy)).length === 0
264
+ ) {
265
+ continue
266
+ }
267
+ projects[root] = policy
268
+ }
269
+ return projects
270
+ }
271
+
272
+ /**
273
+ * The durable policy: one versioned document under `$DSH_HOME`, loaded once when
274
+ * the plugin applies and written atomically on a debounce.
275
+ *
276
+ * Every failure mode is non-fatal by design, exactly like the counters. A
277
+ * missing, unreadable, foreign or older-version document starts from the shipped
278
+ * default, and a write that fails is logged and forgotten, because a panel click
279
+ * must never fail on a policy that could not be stored.
280
+ */
281
+ export class PolicyStore {
282
+ private state: PolicyState
283
+ private timer: ReturnType<typeof setTimeout> | undefined
284
+ private dirty = false
285
+ private disposed = false
286
+ private readonly file: string
287
+ private readonly flushMs: number
288
+ private readonly logger: PolicyLogger | undefined
289
+
290
+ /** @param options - document path, debounce and log sink. */
291
+ constructor(options: PolicyStoreOptions = {}) {
292
+ this.file = options.file ?? join(dshHome(), POLICY_FILE_NAME)
293
+ this.flushMs = options.flushMs ?? DEFAULT_FLUSH_MS
294
+ this.logger = options.logger
295
+ this.state = this.load()
296
+ }
297
+
298
+ /** Policy of one project root; the shipped default when it has none. */
299
+ forProject(projectRoot: string): ToolPolicy {
300
+ return policyFor(this.state, projectRoot)
301
+ }
302
+
303
+ /** Store one project's mode and schedule the debounced write. */
304
+ setMode(projectRoot: string, mode: ToolMode): ToolPolicy {
305
+ this.commit(withMode(this.state, projectRoot, mode))
306
+ return policyFor(this.state, projectRoot)
307
+ }
308
+
309
+ /** Pin or unpin one name of one project and schedule the debounced write. */
310
+ setPin(projectRoot: string, tool: string, pinned: boolean): ToolPolicy {
311
+ this.commit(withPin(this.state, projectRoot, tool, pinned))
312
+ return policyFor(this.state, projectRoot)
313
+ }
314
+
315
+ /**
316
+ * Store which of two conflicting declarations one name shows and schedule the
317
+ * debounced write.
318
+ *
319
+ * Durable on purpose: the answer is what the user decided about their project,
320
+ * not what one session happened to mount, so it survives the restart that
321
+ * would otherwise bring the profile's instance back unopposed.
322
+ */
323
+ setConflictChoice(
324
+ projectRoot: string,
325
+ server: string,
326
+ choice: ConflictChoice,
327
+ ): ToolPolicy {
328
+ this.commit(withConflictChoice(this.state, projectRoot, server, choice))
329
+ return policyFor(this.state, projectRoot)
330
+ }
331
+
332
+ /** Write the policy atomically now. Best effort: it never throws. */
333
+ flush(): void {
334
+ if (!this.dirty) return
335
+ const document: PolicyDocument = { version: POLICY_VERSION, projects: this.state }
336
+ const temporary = `${this.file}.${process.pid}.tmp`
337
+ try {
338
+ mkdirSync(dirname(this.file), { recursive: true })
339
+ writeFileSync(temporary, `${JSON.stringify(document, undefined, 2)}\n`, 'utf8')
340
+ renameSync(temporary, this.file)
341
+ this.dirty = false
342
+ } catch (error) {
343
+ this.logger?.warn(
344
+ `project-mcp: writing the tool policy to ${this.file} failed: ${errorText(error)}`,
345
+ )
346
+ }
347
+ }
348
+
349
+ /**
350
+ * Cancel the pending write, flush what is dirty, and stop storing. Safe to
351
+ * call more than once; the plugin fiber calls it on disposal.
352
+ */
353
+ dispose(): void {
354
+ if (this.timer !== undefined) {
355
+ clearTimeout(this.timer)
356
+ this.timer = undefined
357
+ }
358
+ if (this.disposed) return
359
+ this.disposed = true
360
+ this.flush()
361
+ }
362
+
363
+ /** Adopt a state a pure change produced, and schedule the write when it moved. */
364
+ private commit(next: PolicyState): void {
365
+ if (this.disposed || next === this.state) return
366
+ this.state = next
367
+ this.dirty = true
368
+ if (this.timer !== undefined) return
369
+ this.timer = setTimeout(() => {
370
+ this.timer = undefined
371
+ this.flush()
372
+ }, this.flushMs)
373
+ this.timer.unref?.()
374
+ }
375
+
376
+ private load(): PolicyState {
377
+ let text: string
378
+ try {
379
+ text = readFileSync(this.file, 'utf8')
380
+ } catch {
381
+ return {}
382
+ }
383
+ const state = parsePolicyDocument(text)
384
+ if (state === undefined) {
385
+ this.logger?.warn(
386
+ `project-mcp: ignoring the tool policy in ${this.file} (unreadable or unsupported version); starting from the default`,
387
+ )
388
+ return {}
389
+ }
390
+ return state
391
+ }
392
+ }
393
+
394
+ /** Sanitize one project entry; `undefined` when it is not even a record. */
395
+ function sanitizePolicy(value: unknown): ToolPolicy | undefined {
396
+ if (!isRecord(value)) return undefined
397
+ const pins: string[] = []
398
+ if (Array.isArray(value.pins)) {
399
+ for (const pin of value.pins) {
400
+ if (typeof pin !== 'string' || pin === '' || pins.includes(pin)) continue
401
+ pins.push(pin)
402
+ }
403
+ }
404
+ const aliases: Record<string, ConflictChoice> = {}
405
+ if (isRecord(value.aliases)) {
406
+ for (const [server, choice] of Object.entries(value.aliases)) {
407
+ // The profile is what an absent entry means, so storing it would only
408
+ // duplicate the default; an answer this build does not know is dropped.
409
+ // A key that is no `serverName` at all — empty, or a bare index — is a
410
+ // hand-edit or an array that JSON turned into an object, and is dropped
411
+ // with the answer it carried.
412
+ if (!SERVER_NAME_SHAPE.test(server) || !isConflictChoice(choice) || choice === 'profile') continue
413
+ aliases[server] = choice
414
+ }
415
+ }
416
+ return normalizePolicy(isToolMode(value.mode) ? value.mode : DEFAULT_TOOL_POLICY.mode, pins, aliases)
417
+ }
418
+
419
+ function isRecord(value: unknown): value is Record<string, unknown> {
420
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
421
+ }
422
+
423
+ function errorText(error: unknown): string {
424
+ return error instanceof Error ? error.message : String(error)
425
+ }