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/usage.ts ADDED
@@ -0,0 +1,442 @@
1
+ /**
2
+ * Durable per-project MCP usage counters for `dsh-project-mcp`.
3
+ *
4
+ * The host half counts the `tools/result` events whose tool belongs to a server
5
+ * it mounted itself, keyed by project root and `serverName`. The numbers are
6
+ * remembered across sessions and restarts in one versioned document under
7
+ * `$DSH_HOME`, written atomically on a debounce so a tool call never waits for
8
+ * the filesystem, and a failed write is logged and dropped rather than allowed
9
+ * to disturb the call.
10
+ *
11
+ * Counting itself is pure ({@link recordUsage}) and the document only sits
12
+ * behind {@link UsageStore}, so the model is testable without a filesystem.
13
+ *
14
+ * @module dsh-project-mcp/usage
15
+ */
16
+
17
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
18
+ import { dirname, join } from 'node:path'
19
+ import { dshHome } from './discovery.ts'
20
+ import type { ServerUsage, SessionUsage } from './types.ts'
21
+
22
+ /** Current on-disk document version; another version is ignored, not migrated. */
23
+ export const USAGE_VERSION = 1
24
+
25
+ /** Counter document name under `$DSH_HOME`. */
26
+ export const USAGE_FILE_NAME = 'dsh-project-mcp-usage.json'
27
+
28
+ /** Counters keyed by project root, then by `serverName`. */
29
+ export type UsageState = Record<string, Record<string, ServerUsage>>
30
+
31
+ /** The durable counter document as written to disk. */
32
+ export interface UsageDocument {
33
+ /** Document version; a reader that does not know it starts clean. */
34
+ version: typeof USAGE_VERSION
35
+ /** Counters of every project ever seen. */
36
+ projects: UsageState
37
+ }
38
+
39
+ /** One registry call, before it is attributed to a mounted server. */
40
+ export interface UsageCall {
41
+ /** Project root the calling agent resolved to. */
42
+ projectRoot: string
43
+ /** Server names this plugin currently mounts for that project. */
44
+ servers: ReadonlySet<string>
45
+ /**
46
+ * Public tool name delivered by `tools/result`, ie `mcp__<serverName>__<name>`.
47
+ * A name the registry had to truncate to the function-name budget keeps this
48
+ * prefix, so the server is still identifiable.
49
+ */
50
+ toolName: string
51
+ /** `true` when the settled result carried an error. */
52
+ isError: boolean
53
+ /** Epoch milliseconds of the call. */
54
+ at: number
55
+ /**
56
+ * Session the call belongs to: the id of the agent that made it.
57
+ *
58
+ * The host resolves an agent from the call's own event, and every other
59
+ * surface of this plugin already calls that id the session id (a `LogEvent`,
60
+ * a `SessionSnapshot`). Counting is therefore attributable without a second
61
+ * lookup, which is what lets the panel answer "and how much of this is mine?"
62
+ * (F-34).
63
+ */
64
+ sessionId: string
65
+ }
66
+
67
+ /** One counted call, attributed to a project and a server this plugin mounted. */
68
+ export interface UsageEvent {
69
+ /** Project root the calling agent resolved to. */
70
+ projectRoot: string
71
+ /** `serverName` this plugin mounted for that project. */
72
+ serverName: string
73
+ /**
74
+ * Tool name as declared by the server, ie without the `mcp__<serverName>__`
75
+ * prefix. A name the registry truncated to its function-name budget cannot be
76
+ * reversed, so its key is the public suffix the registry published.
77
+ */
78
+ tool: string
79
+ /** `true` when the settled result carried an error. */
80
+ isError: boolean
81
+ /** Epoch milliseconds of the call. */
82
+ at: number
83
+ /** Session (agent) id this call is counted under, besides the project total. */
84
+ sessionId: string
85
+ }
86
+
87
+ /** The `tools/result` execution view this module reads. */
88
+ export interface ToolResultEventLike {
89
+ /** Public tool name, `mcp__<serverName>__<name>`. */
90
+ readonly name: string
91
+ /** Agent the call ran for; absent on a host-level call, which is not counted. */
92
+ readonly agent?: { readonly id: string } | undefined
93
+ }
94
+
95
+ /** The settled `tools/result` outcome view this module reads. */
96
+ export interface ToolResultLike {
97
+ /** `true` when the call settled as an error. */
98
+ readonly isError: boolean
99
+ }
100
+
101
+ /** Everything {@link observeToolResults} needs, injected so it is testable. */
102
+ export interface ToolResultObserverOptions {
103
+ /** Register the `tools/result` listener; returns its disposer. */
104
+ on(
105
+ name: 'tools/result',
106
+ handler: (exec: ToolResultEventLike, result: ToolResultLike) => undefined,
107
+ ): (() => void) | undefined
108
+ /** Resolve the project and the mounted servers of the agent that made a call. */
109
+ mountsFor(agentId: string): { projectRoot: string; servers: ReadonlySet<string> } | undefined
110
+ /** Durable store the attributed calls are recorded in. */
111
+ store: Pick<UsageStore, 'record'>
112
+ /** Clock override; defaults to `Date.now`. */
113
+ now?: () => number
114
+ }
115
+
116
+ /** The logger surface the store uses; a Cordis logger satisfies it. */
117
+ export interface UsageLogger {
118
+ /** Non-fatal report; the store never throws at its caller. */
119
+ warn(message: string): void
120
+ }
121
+
122
+ /** Construction options for {@link UsageStore}; production uses the defaults. */
123
+ export interface UsageStoreOptions {
124
+ /** Absolute document path; defaults to `$DSH_HOME/dsh-project-mcp-usage.json`. */
125
+ file?: string
126
+ /** Debounce before a recorded call reaches disk. */
127
+ flushMs?: number
128
+ /** Sink for a corrupt document or a failed write. */
129
+ logger?: UsageLogger
130
+ }
131
+
132
+ /** Debounce that keeps a tool call off the filesystem. */
133
+ const DEFAULT_FLUSH_MS = 1_000
134
+
135
+ /**
136
+ * Attribute one registry tool name to a server this plugin mounted.
137
+ *
138
+ * The prefix is never parsed blindly: only mounted names are candidates, and
139
+ * the longest match wins, so a mounted `alpha_` is never shadowed by a mounted
140
+ * `alpha` when both publish tools into one scope.
141
+ *
142
+ * @param toolName - public registry name, `mcp__<serverName>__<name>`.
143
+ * @param servers - names this plugin mounted for the calling agent's project.
144
+ * @returns the matched `serverName`, or `undefined` for a foreign tool.
145
+ */
146
+ export function matchServer(toolName: string, servers: ReadonlySet<string>): string | undefined {
147
+ let match: string | undefined
148
+ for (const server of servers) {
149
+ if (!toolName.startsWith(`mcp__${server}__`)) continue
150
+ if (match === undefined || server.length > match.length) match = server
151
+ }
152
+ return match
153
+ }
154
+
155
+ /**
156
+ * Attribute one registry call, or `undefined` when no server this plugin
157
+ * mounted for the project claims the name.
158
+ * @param call - the raw `tools/result` view plus the caller's mounts.
159
+ * @returns the counted event, ready for {@link recordUsage}.
160
+ */
161
+ export function usageEventFor(call: UsageCall): UsageEvent | undefined {
162
+ const serverName = matchServer(call.toolName, call.servers)
163
+ if (serverName === undefined) return undefined
164
+ return {
165
+ projectRoot: call.projectRoot,
166
+ serverName,
167
+ tool: call.toolName.slice(`mcp__${serverName}__`.length),
168
+ isError: call.isError,
169
+ at: call.at,
170
+ sessionId: call.sessionId,
171
+ }
172
+ }
173
+
174
+ /**
175
+ * Count one call into the state.
176
+ *
177
+ * Pure: it reads and returns counters only, touching no filesystem, clock or
178
+ * logger, so the model is testable on its own.
179
+ *
180
+ * @param state - counters before the call.
181
+ * @param event - one attributed call.
182
+ * @returns a new state carrying the increment; `lastUsedAt` moves and is set
183
+ * only on a success, while a failure keeps the previous stamp.
184
+ */
185
+ export function recordUsage(state: UsageState, event: UsageEvent): UsageState {
186
+ const project = state[event.projectRoot] ?? {}
187
+ const previous = project[event.serverName]
188
+ const tools: Record<string, number> = { ...previous?.tools }
189
+ tools[event.tool] = (tools[event.tool] ?? 0) + 1
190
+ const lastUsedAt = event.isError ? previous?.lastUsedAt : new Date(event.at).toISOString()
191
+ const sessions: Record<string, SessionUsage> = { ...previous?.sessions }
192
+ const previousSession = sessions[event.sessionId]
193
+ const sessionTools: Record<string, number> = { ...previousSession?.tools }
194
+ sessionTools[event.tool] = (sessionTools[event.tool] ?? 0) + 1
195
+ const sessionLastUsedAt = event.isError
196
+ ? previousSession?.lastUsedAt
197
+ : new Date(event.at).toISOString()
198
+ sessions[event.sessionId] = {
199
+ calls: (previousSession?.calls ?? 0) + 1,
200
+ errors: (previousSession?.errors ?? 0) + (event.isError ? 1 : 0),
201
+ tools: sessionTools,
202
+ ...(sessionLastUsedAt === undefined ? {} : { lastUsedAt: sessionLastUsedAt }),
203
+ }
204
+ const usage: ServerUsage = {
205
+ calls: (previous?.calls ?? 0) + 1,
206
+ errors: (previous?.errors ?? 0) + (event.isError ? 1 : 0),
207
+ tools,
208
+ sessions,
209
+ ...(lastUsedAt === undefined ? {} : { lastUsedAt }),
210
+ }
211
+ return {
212
+ ...state,
213
+ [event.projectRoot]: { ...project, [event.serverName]: usage },
214
+ }
215
+ }
216
+
217
+ /**
218
+ * Subscribe the durable counters to `tools/result`.
219
+ *
220
+ * Counting is per event, never deduplicated against a parent: a programmatic
221
+ * sub-dispatch is its own call with its own result, while the enclosing
222
+ * `run_code` carries a name no server claims, so each MCP call is counted
223
+ * exactly once on either path.
224
+ *
225
+ * @param options - registry subscription, agent resolver, store and clock.
226
+ * @returns the disposer that unregisters the listener.
227
+ */
228
+ export function observeToolResults(options: ToolResultObserverOptions): () => void {
229
+ const now = options.now ?? Date.now
230
+ const listener = (exec: ToolResultEventLike, result: ToolResultLike): undefined => {
231
+ const agentId = exec.agent?.id
232
+ if (agentId === undefined) return undefined
233
+ const mounts = options.mountsFor(agentId)
234
+ if (mounts === undefined) return undefined
235
+ const event = usageEventFor({
236
+ projectRoot: mounts.projectRoot,
237
+ servers: mounts.servers,
238
+ toolName: exec.name,
239
+ isError: result.isError,
240
+ at: now(),
241
+ sessionId: agentId,
242
+ })
243
+ if (event === undefined) return undefined
244
+ options.store.record(event)
245
+ return undefined
246
+ }
247
+ const dispose = options.on('tools/result', listener)
248
+ return () => {
249
+ dispose?.()
250
+ }
251
+ }
252
+
253
+ /**
254
+ * The durable counters: one versioned document under `$DSH_HOME`, loaded once
255
+ * when the plugin applies and written atomically on a debounce.
256
+ *
257
+ * Every failure mode is non-fatal by design. A missing, unreadable, foreign or
258
+ * older-version document starts clean, and a write that fails is logged and
259
+ * forgotten, because a tool call must never fail on a counter that could not
260
+ * be stored.
261
+ */
262
+ export class UsageStore {
263
+ private state: UsageState
264
+ private timer: ReturnType<typeof setTimeout> | undefined
265
+ private dirty = false
266
+ private disposed = false
267
+ private readonly file: string
268
+ private readonly flushMs: number
269
+ private readonly logger: UsageLogger | undefined
270
+
271
+ /** @param options - document path, debounce and log sink. */
272
+ constructor(options: UsageStoreOptions = {}) {
273
+ this.file = options.file ?? join(dshHome(), USAGE_FILE_NAME)
274
+ this.flushMs = options.flushMs ?? DEFAULT_FLUSH_MS
275
+ this.logger = options.logger
276
+ this.state = this.load()
277
+ }
278
+
279
+ /** Counters of one project root, or `undefined` when it has none yet. */
280
+ forProject(projectRoot: string): Record<string, ServerUsage> | undefined {
281
+ return this.state[projectRoot]
282
+ }
283
+
284
+ /** Count one attributed call and schedule the debounced write. */
285
+ record(event: UsageEvent): void {
286
+ if (this.disposed) return
287
+ this.state = recordUsage(this.state, event)
288
+ this.dirty = true
289
+ if (this.timer !== undefined) return
290
+ this.timer = setTimeout(() => {
291
+ this.timer = undefined
292
+ this.flush()
293
+ }, this.flushMs)
294
+ this.timer.unref?.()
295
+ }
296
+
297
+ /** Write the counters atomically now. Best effort: it never throws. */
298
+ flush(): void {
299
+ if (!this.dirty) return
300
+ const document: UsageDocument = { version: USAGE_VERSION, projects: this.state }
301
+ const temporary = `${this.file}.${process.pid}.tmp`
302
+ try {
303
+ mkdirSync(dirname(this.file), { recursive: true })
304
+ writeFileSync(temporary, `${JSON.stringify(document, undefined, 2)}\n`, 'utf8')
305
+ renameSync(temporary, this.file)
306
+ this.dirty = false
307
+ } catch (error) {
308
+ this.logger?.warn(
309
+ `project-mcp: writing usage counters to ${this.file} failed: ${errorText(error)}`,
310
+ )
311
+ }
312
+ }
313
+
314
+ /**
315
+ * Cancel the pending write, flush what is dirty, and stop counting. Safe to
316
+ * call more than once; the plugin fiber calls it on disposal.
317
+ */
318
+ dispose(): void {
319
+ if (this.timer !== undefined) {
320
+ clearTimeout(this.timer)
321
+ this.timer = undefined
322
+ }
323
+ if (this.disposed) return
324
+ this.disposed = true
325
+ this.flush()
326
+ }
327
+
328
+ private load(): UsageState {
329
+ let text: string
330
+ try {
331
+ text = readFileSync(this.file, 'utf8')
332
+ } catch {
333
+ return {}
334
+ }
335
+ const state = parseUsageDocument(text)
336
+ if (state === undefined) {
337
+ this.logger?.warn(
338
+ `project-mcp: ignoring usage counters in ${this.file} (unreadable or unsupported version); starting clean`,
339
+ )
340
+ return {}
341
+ }
342
+ return state
343
+ }
344
+ }
345
+
346
+ /**
347
+ * Parse one durable counter document.
348
+ *
349
+ * Anything this version cannot trust — malformed JSON, a foreign shape, or
350
+ * another version — yields `undefined` so the caller starts clean instead of
351
+ * throwing, and each counter is validated so a hand-edited document cannot
352
+ * poison later arithmetic.
353
+ *
354
+ * @param text - raw document contents.
355
+ * @returns the counters, or `undefined` when the document is not usable.
356
+ */
357
+ export function parseUsageDocument(text: string): UsageState | undefined {
358
+ let value: unknown
359
+ try {
360
+ value = JSON.parse(text)
361
+ } catch {
362
+ return undefined
363
+ }
364
+ if (!isRecord(value)) return undefined
365
+ if (value.version !== USAGE_VERSION) return undefined
366
+ if (!isRecord(value.projects)) return undefined
367
+ return sanitizeProjects(value.projects)
368
+ }
369
+
370
+ function sanitizeProjects(raw: Record<string, unknown>): UsageState {
371
+ const projects: UsageState = {}
372
+ for (const [root, servers] of Object.entries(raw)) {
373
+ if (!isRecord(servers)) continue
374
+ const rows: Record<string, ServerUsage> = {}
375
+ for (const [server, usage] of Object.entries(servers)) {
376
+ const parsed = sanitizeUsage(usage)
377
+ if (parsed !== undefined) rows[server] = parsed
378
+ }
379
+ if (Object.keys(rows).length > 0) projects[root] = rows
380
+ }
381
+ return projects
382
+ }
383
+
384
+ function sanitizeUsage(value: unknown): ServerUsage | undefined {
385
+ if (!isRecord(value)) return undefined
386
+ if (!isCount(value.calls) || !isCount(value.errors)) return undefined
387
+ return {
388
+ calls: value.calls,
389
+ errors: value.errors,
390
+ tools: countMap(value.tools),
391
+ // The per-session split is carried through, not rebuilt: a reader that
392
+ // dropped it would lose every session figure on the first restart, while
393
+ // the project totals it kept looked perfectly healthy.
394
+ ...sanitizeSessions(value.sessions),
395
+ ...(typeof value.lastUsedAt === 'string' ? { lastUsedAt: value.lastUsedAt } : {}),
396
+ }
397
+ }
398
+
399
+ /** A record of non-negative integer counts, with every other entry dropped. */
400
+ function countMap(value: unknown): Record<string, number> {
401
+ const counts: Record<string, number> = {}
402
+ if (isRecord(value)) {
403
+ for (const [name, count] of Object.entries(value)) {
404
+ if (isCount(count)) counts[name] = count
405
+ }
406
+ }
407
+ return counts
408
+ }
409
+
410
+ /** The `sessions` half of a stored record, as the `...` spread a caller wants. */
411
+ function sanitizeSessions(value: unknown): { sessions?: Record<string, SessionUsage> } {
412
+ if (!isRecord(value)) return {}
413
+ const sessions: Record<string, SessionUsage> = {}
414
+ for (const [id, usage] of Object.entries(value)) {
415
+ const parsed = sanitizeSessionUsage(usage)
416
+ if (parsed !== undefined) sessions[id] = parsed
417
+ }
418
+ return Object.keys(sessions).length === 0 ? {} : { sessions }
419
+ }
420
+
421
+ function sanitizeSessionUsage(value: unknown): SessionUsage | undefined {
422
+ if (!isRecord(value)) return undefined
423
+ if (!isCount(value.calls) || !isCount(value.errors)) return undefined
424
+ return {
425
+ calls: value.calls,
426
+ errors: value.errors,
427
+ tools: countMap(value.tools),
428
+ ...(typeof value.lastUsedAt === 'string' ? { lastUsedAt: value.lastUsedAt } : {}),
429
+ }
430
+ }
431
+
432
+ function isRecord(value: unknown): value is Record<string, unknown> {
433
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
434
+ }
435
+
436
+ function isCount(value: unknown): value is number {
437
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0
438
+ }
439
+
440
+ function errorText(error: unknown): string {
441
+ return error instanceof Error ? error.message : String(error)
442
+ }