dsh-project-mcp 0.2.0 → 0.4.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 CHANGED
@@ -44,6 +44,7 @@ import type {
44
44
  RuntimeConfig,
45
45
  RuntimeOptions,
46
46
  SaveOutcome,
47
+ ToolFactsOutcome,
47
48
  } from './runtime.ts'
48
49
  import type { ConflictRequest, PinRequest, PolicyRequest, SaveRequest } from './shared.ts'
49
50
  import { UsageStore, observeToolResults } from './usage.ts'
@@ -64,6 +65,7 @@ export type {
64
65
  RuntimeConfig,
65
66
  RuntimeOptions,
66
67
  SaveOutcome,
68
+ ToolFactsOutcome,
67
69
  UsageSource,
68
70
  } from './runtime.ts'
69
71
  export {
@@ -486,6 +488,18 @@ export interface ProjectMcpService {
486
488
  subscribe(listener: (change: SnapshotChange) => void): () => void
487
489
  /** Give one session's servers back now, or every mounted session's when no id is given. */
488
490
  release(agentId?: string): Promise<void>
491
+ /**
492
+ * Read one tool's detail for a row a panel opened: its model-facing
493
+ * description, the fields its schema accepts, and the reason this session's
494
+ * request does not carry it. Answered on demand instead of riding the
495
+ * snapshot, because descriptions and schemas are the expensive part and this
496
+ * is read once per opened row.
497
+ * @param projectRoot - project root the panel read the row from.
498
+ * @param sessionId - live agent id the row belongs to.
499
+ * @param name - public registry name, as the panel drew it.
500
+ * @returns the tool's facts, or the coded refusal the route maps to a status.
501
+ */
502
+ toolFacts(projectRoot: string, sessionId: string, name: string): ToolFactsOutcome
489
503
  /**
490
504
  * Write one edited entry back to the document that declares it.
491
505
  * @param request - entry body, declaring document and the revision it was read at.
@@ -544,6 +558,7 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
544
558
  syncSoon: (projectRoot) => runtime.syncSoon(projectRoot),
545
559
  retry: (projectRoot) => runtime.retry(projectRoot),
546
560
  release: (agentId) => runtime.release(agentId),
561
+ toolFacts: (projectRoot, sessionId, name) => runtime.toolFactsOf(projectRoot, sessionId, name),
547
562
  save: (request) => runtime.saveEntry(request),
548
563
  setPin: (request) => runtime.setPin(request),
549
564
  setPolicy: (request) => runtime.setPolicy(request),
@@ -556,9 +571,9 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
556
571
  runtime.attach(scope as unknown as AgentScopeLike)
557
572
  scope.provide(SERVICE_NAME, service)
558
573
  })
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.
574
+ // The sidebar panel runs in the browser half, which can reach neither this
575
+ // service nor the host context that owns it: publish the same surface over HTTP
576
+ // when the composition has a web server.
562
577
  ctx.inject(['webServer'], (scope) => {
563
578
  const webServer = (scope as unknown as { webServer?: WebServerLike }).webServer
564
579
  if (webServer === undefined) return
package/src/runtime.ts CHANGED
@@ -39,6 +39,7 @@ import {
39
39
  noteUse,
40
40
  presentedNames,
41
41
  pruneIdle,
42
+ schemaChars,
42
43
  seedFromUsage,
43
44
  toolsFor,
44
45
  } from './activation.ts'
@@ -99,8 +100,11 @@ import type {
99
100
  SessionTools,
100
101
  SnapshotChange,
101
102
  SnapshotIssue,
103
+ ToolFacts,
104
+ ToolField,
102
105
  ToolMode,
103
106
  ToolPolicy,
107
+ ToolReason,
104
108
  WriteScope,
105
109
  } from './types.ts'
106
110
  import { matchServer } from './usage.ts'
@@ -285,6 +289,20 @@ export type PolicyOutcome =
285
289
  readonly messageParams?: Record<string, string>
286
290
  }
287
291
 
292
+ /**
293
+ * Outcome of {@link ProjectMcpRuntime.toolFactsOf}: one tool's on-demand detail,
294
+ * or the code the route maps to a status.
295
+ *
296
+ * A refusal is a `404`: the route only asks about a project root, a session id
297
+ * and a name a panel read from a snapshot, so one this host does not know is a
298
+ * stale read rather than a malformed request — the three parameters themselves
299
+ * are checked by the route. The prose stays plain English and uncoded, the way
300
+ * `GET logs` refuses.
301
+ */
302
+ export type ToolFactsOutcome =
303
+ | { readonly ok: true; readonly value: ToolFacts }
304
+ | { readonly ok: false; readonly code: SaveErrorCode; readonly message: string }
305
+
288
306
  /**
289
307
  * Identity of the Cordis scope one project's servers are mounted in. Every
290
308
  * session of that project is parented to it, so the registrations inside are
@@ -1123,6 +1141,95 @@ export class ProjectMcpRuntime {
1123
1141
  }
1124
1142
  }
1125
1143
 
1144
+ /**
1145
+ * One tool's on-demand detail, answered for a row a panel opened.
1146
+ *
1147
+ * A read, never a rescan: the definition comes from the same mount home the
1148
+ * snapshot's session row was measured from, so a **deferred** name answers
1149
+ * exactly like an offered one — the home's catalog carries the whole mounted
1150
+ * surface, and only the request's own deferral decision leaves a name out of
1151
+ * it. That is also what makes the reason honest: `budget` is reported exactly
1152
+ * when the session's own row lists the name in `deferred`, and every figure on
1153
+ * it is a host measurement — {@link schemaChars} of this definition, the
1154
+ * session's `budgetChars` and its `visibleChars`. A number the host does not
1155
+ * have is omitted rather than guessed.
1156
+ *
1157
+ * The published fields are the schema's top-level `parameters.properties`
1158
+ * only: a nested object or array is drawn as its type and never expanded, and
1159
+ * a property's `default` is never published — the schema a model reads is the
1160
+ * definition's, and this record is a *view* of it, not a second copy with
1161
+ * defaults baked in.
1162
+ *
1163
+ * @param projectRoot - project root the panel read the row from.
1164
+ * @param sessionId - live agent id the row belongs to.
1165
+ * @param name - public registry name, as the panel drew it.
1166
+ * @returns the tool's facts, or the `not-found` refusal the route maps to 404.
1167
+ */
1168
+ toolFactsOf(projectRoot: string, sessionId: string, name: string): ToolFactsOutcome {
1169
+ const state = this.states.get(sessionId)
1170
+ if (state === undefined || state.projectRoot !== projectRoot) {
1171
+ return {
1172
+ ok: false,
1173
+ code: 'not-found',
1174
+ message: `no live session ${sessionId} in ${projectRoot}`,
1175
+ }
1176
+ }
1177
+ const home = this.homeOf(state)
1178
+ if (home === undefined) {
1179
+ return {
1180
+ ok: false,
1181
+ code: 'not-found',
1182
+ message: `no live session ${sessionId} in ${projectRoot}`,
1183
+ }
1184
+ }
1185
+ const schema = this.schemasOf(home, state.agent.id).find(
1186
+ (candidate) => candidate.name === name,
1187
+ )
1188
+ if (schema === undefined) {
1189
+ return {
1190
+ ok: false,
1191
+ code: 'not-found',
1192
+ message: `${name} is not mounted in ${projectRoot}`,
1193
+ }
1194
+ }
1195
+ const fields = toolFieldsOf(schema.parameters)
1196
+ const description = schema.description === '' ? undefined : schema.description
1197
+ // Only a name the session's own row hides is unexplained by the request, so
1198
+ // only such a name carries a reason; an offered one has nothing to explain.
1199
+ const deferred = this.sessionTools(state)?.deferred ?? []
1200
+ const reason = deferred.includes(name) ? this.budgetReason(state, schema) : undefined
1201
+ return {
1202
+ ok: true,
1203
+ value: {
1204
+ name: schema.name,
1205
+ ...(description === undefined ? {} : { description }),
1206
+ fields,
1207
+ ...(reason === undefined ? {} : { reason }),
1208
+ },
1209
+ }
1210
+ }
1211
+
1212
+ /**
1213
+ * Why the budget left one definition out of this session's request: the host's
1214
+ * own numbers, each omitted when the row that carries it did not measure it.
1215
+ * @param state - the session whose row and budget are read.
1216
+ * @param schema - the definition the row does not offer.
1217
+ * @returns the `budget` reason, carrying only figures the host holds.
1218
+ */
1219
+ private budgetReason(state: AgentState, schema: ToolSchemaLike): ToolReason {
1220
+ const tools = this.sessionTools(state)
1221
+ return {
1222
+ kind: 'budget',
1223
+ chars: schemaChars(schema),
1224
+ ...(tools === undefined
1225
+ ? {}
1226
+ : {
1227
+ budget: tools.budgetChars,
1228
+ ...(tools.visibleChars === undefined ? {} : { used: tools.visibleChars }),
1229
+ }),
1230
+ }
1231
+ }
1232
+
1126
1233
  /**
1127
1234
  * What this plugin currently mounts for one live agent: the project root the
1128
1235
  * agent resolved to and the server names it mounted there. `undefined` when
@@ -2976,7 +3083,10 @@ export class ProjectMcpRuntime {
2976
3083
  for (const name of names) state.steps.set(name, step)
2977
3084
  },
2978
3085
  onCompaction: () => {
2979
- state.steps.clear()
3086
+ // A step record belongs to the activation it was made for, so the ones
3087
+ // a compaction just dropped go with them — while a tool the session
3088
+ // really used keeps the step its offer happened on.
3089
+ this.pruneStepRecords(state)
2980
3090
  },
2981
3091
  autoState: state.auto ?? createAutoOfferState(),
2982
3092
  setAutoState: (next) => {
@@ -3058,11 +3168,28 @@ export class ProjectMcpRuntime {
3058
3168
  // can never lag behind the catalog this probe returns. Unchanged names
3059
3169
  // short-circuit inside, so the cost is one name comparison.
3060
3170
  this.syncBridge(state)
3171
+ return this.schemasOf(home, state.agent.id)
3172
+ }
3173
+
3174
+ /**
3175
+ * The visible catalog of one mount home, read through the home's scope key.
3176
+ *
3177
+ * The single read both callers share: the activation probe asks for the whole
3178
+ * catalog, and the on-demand detail route asks it for one definition — reading
3179
+ * through the same key is what makes a deferred name answer exactly like an
3180
+ * offered one, because the home's catalog carries the whole mounted surface
3181
+ * and the deferral decision only lives in the request.
3182
+ *
3183
+ * @param home - the mount home whose registrations are read.
3184
+ * @param agentId - the session the read is attributed to, for the warning.
3185
+ * @returns the home's schemas, or none when the read fails.
3186
+ */
3187
+ private schemasOf(home: MountHome, agentId: string): ToolSchemaLike[] {
3061
3188
  try {
3062
3189
  return this.ctx.tools.schemas(home.key)
3063
3190
  } catch (error) {
3064
3191
  this.ctx.logger.warn(
3065
- `project-mcp: reading the tool catalog of session ${state.agent.id} failed: ${errorText(error)}`,
3192
+ `project-mcp: reading the tool catalog of session ${agentId} failed: ${errorText(error)}`,
3066
3193
  )
3067
3194
  return []
3068
3195
  }
@@ -3198,8 +3325,10 @@ export class ProjectMcpRuntime {
3198
3325
  }
3199
3326
 
3200
3327
  /**
3201
- * Refresh the freshness of a tool a session actually called. It rides the same
3202
- * `tools/result` subscription the counters use, so no second observer exists.
3328
+ * Record a call against the session's activation state: it refreshes the
3329
+ * freshness of a session-activated tool, and it is the evidence a later
3330
+ * compaction keeps that activation by. It rides the same `tools/result`
3331
+ * subscription the counters use, so no second observer exists.
3203
3332
  * @param agentId - calling agent, when the call was agent-scoped.
3204
3333
  * @param toolName - public registry name of the call.
3205
3334
  */
@@ -3218,10 +3347,21 @@ export class ProjectMcpRuntime {
3218
3347
  // A step record belongs to the activation it was made for, so a name that
3219
3348
  // fell out of the window takes its record with it; one that returns is
3220
3349
  // stamped again with the step it returns on.
3221
- if (state.activation !== current) {
3222
- for (const name of [...state.steps.keys()]) {
3223
- if (!state.activation.active.has(name)) state.steps.delete(name)
3224
- }
3350
+ if (state.activation !== current) this.pruneStepRecords(state)
3351
+ }
3352
+
3353
+ /**
3354
+ * Drop the step records whose activation the session no longer holds.
3355
+ *
3356
+ * Called wherever activations end — the idle sweep and a compaction — so a
3357
+ * record never outlives the offer it was made for, and a name the session
3358
+ * still offers keeps the step its offer happened on.
3359
+ * @param state - the session whose records are reconciled.
3360
+ */
3361
+ private pruneStepRecords(state: AgentState): void {
3362
+ const active = state.activation?.active
3363
+ for (const name of [...state.steps.keys()]) {
3364
+ if (active === undefined || !active.has(name)) state.steps.delete(name)
3225
3365
  }
3226
3366
  }
3227
3367
 
@@ -4198,6 +4338,43 @@ function errorText(error: unknown): string {
4198
4338
  return error instanceof Error ? error.message : String(error)
4199
4339
  }
4200
4340
 
4341
+ /**
4342
+ * The fields one tool definition accepts, read from its top-level
4343
+ * `parameters.properties` in schema order.
4344
+ *
4345
+ * A declared object or array is drawn as its own `type` and never expanded:
4346
+ * the record answers "what does this tool take", and a nested graph is what the
4347
+ * model-facing schema already carries. A property published without a `type` —
4348
+ * the JSON Schema case of `oneOf` or `$ref` — reads as `any`, the same word the
4349
+ * row vocabulary uses for "the schema names none". A property's `default` is
4350
+ * deliberately not part of the record: it is the host's own default for a call,
4351
+ * never a value the tool publishes.
4352
+ *
4353
+ * @param parameters - the definition's JSON Schema object arguments.
4354
+ * @returns one field per declared property; empty when the schema declares none.
4355
+ */
4356
+ function toolFieldsOf(parameters: Record<string, unknown>): ToolField[] {
4357
+ const properties = parameters.properties
4358
+ if (!isRecord(properties)) return []
4359
+ const required = new Set(stringArray(parameters.required))
4360
+ return Object.entries(properties).map(([name, declared]) => {
4361
+ const field = isRecord(declared) ? declared : {}
4362
+ const type = field.type
4363
+ const description = field.description
4364
+ return {
4365
+ name,
4366
+ type: typeof type === 'string' && type !== '' ? type : 'any',
4367
+ required: required.has(name),
4368
+ ...(typeof description === 'string' && description !== '' ? { description } : {}),
4369
+ }
4370
+ })
4371
+ }
4372
+
4373
+ /** The strings of one array value; empty for anything that is not one. */
4374
+ function stringArray(value: unknown): string[] {
4375
+ return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : []
4376
+ }
4377
+
4201
4378
  /**
4202
4379
  * One path the watcher stack covers and what kind it is.
4203
4380
  *
package/src/shared.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  /**
2
2
  * Contract shared by the host half and the browser half of the panel.
3
3
  *
4
- * Import-free on purpose: the client bundle must not pull host code in, and
5
- * `ctx.betterSidebar` exists only in the browser, so the two halves meet at
6
- * these routes over HTTP.
4
+ * Import-free on purpose: the client bundle must not pull host code in, and the
5
+ * right sidebar exists only in the browser half, so the two halves meet at these
6
+ * routes over HTTP.
7
7
  *
8
8
  * @module dsh-project-mcp/shared
9
9
  */
@@ -31,6 +31,12 @@ export const ROUTE_ACTIONS = {
31
31
  events: 'events',
32
32
  /** `GET`: one page of a project's log ring, oldest first, for "show older". */
33
33
  logs: 'logs',
34
+ /**
35
+ * `GET`: one tool's detail — its description, its accepted fields, its
36
+ * measured size and the reason it is not offered — read once per opened row
37
+ * so that neither the snapshot nor a change frame carries it.
38
+ */
39
+ tool: 'tool',
34
40
  /** `POST`: release this session's mounts. */
35
41
  release: 'release',
36
42
  /** `POST`: write one edited entry back to its declaring document. */
package/src/types.ts CHANGED
@@ -264,6 +264,71 @@ export interface OfferedTool {
264
264
  readonly step?: number
265
265
  }
266
266
 
267
+ /**
268
+ * One accepted field of a tool's `parameters` schema, as the panel lists it.
269
+ *
270
+ * A field is listed from the definition the host already holds, so its type and
271
+ * its `required` flag are the schema's own and neither is inferred from the
272
+ * tool's name. Nesting stops at the top level: an object or array field is drawn
273
+ * as its type, not expanded, because the panel lists what a call takes rather
274
+ * than mirroring a schema. Schema `default` values are deliberately not part of
275
+ * this shape — a default can carry a value the tool did not mean to publish.
276
+ */
277
+ export interface ToolField {
278
+ /** Property name, as the schema declares it. */
279
+ readonly name: string
280
+ /** JSON Schema `type` of the field, or `any` when the schema names none. */
281
+ readonly type: string
282
+ /** `true` when the schema's own `required` array names this property. */
283
+ readonly required: boolean
284
+ /** The property's own `description`, when the schema publishes one. */
285
+ readonly description?: string
286
+ }
287
+
288
+ /**
289
+ * Why one name is not in this session's request, in the host's own terms.
290
+ *
291
+ * The decision belongs to the host and the panel does not recompute it, so the
292
+ * reason travels as data and its copy lives in the client's dictionaries. Every
293
+ * figure here is a host measurement — the definition's own serialized size, the
294
+ * session's budget, what the offered set already carries — so a reason line
295
+ * invents no number. That is the same discipline as contract C2's step tag.
296
+ */
297
+ export interface ToolReason {
298
+ /**
299
+ * Which decision left the name out. `budget` is the disclosure mode pushing it
300
+ * past {@link ToolReason.budget}: the whole mounted surface is registered, and
301
+ * this definition did not fit the request.
302
+ */
303
+ readonly kind: 'budget'
304
+ /** Serialized size of this definition, in characters — the host's own figure. */
305
+ readonly chars?: number
306
+ /** The session's tool budget in characters, when the host budgeted one. */
307
+ readonly budget?: number
308
+ /** Characters the offered set already carries, when the host measured them. */
309
+ readonly used?: number
310
+ }
311
+
312
+ /**
313
+ * One tool's detail, answered on demand for a row the reader opened.
314
+ *
315
+ * The panel fetches this instead of carrying it in the snapshot: the snapshot
316
+ * travels on every change frame and every poll, while a description and a schema
317
+ * are read once per opened row. The text is model-facing and arrives as data —
318
+ * it is never copied into a dictionary, is not translated, and is drawn as the
319
+ * host published it.
320
+ */
321
+ export interface ToolFacts {
322
+ /** Public registry name this record answers about. */
323
+ readonly name: string
324
+ /** The definition's model-facing description, when the host holds one. */
325
+ readonly description?: string
326
+ /** Accepted fields, in schema order; empty when the tool declares none. */
327
+ readonly fields: readonly ToolField[]
328
+ /** Why the name is not offered, when it is not. Absent for an offered name. */
329
+ readonly reason?: ToolReason
330
+ }
331
+
267
332
  /**
268
333
  * Another loaded plugin that owns the assembled tool list.
269
334
  *
package/src/ui.ts CHANGED
@@ -1,10 +1,10 @@
1
1
  /**
2
2
  * Host HTTP surface for the sidebar panel.
3
3
  *
4
- * `ctx.betterSidebar` exists only in the browser half of a DSH composition, so
4
+ * The browser half of a DSH composition is a different process from this one, so
5
5
  * the panel cannot call the `projectMcp` service in process: it fetches these
6
- * routes, the same way `dsh-better-sidebar` serves its own `/sidebar/api/*`
7
- * surface. Every response is `{ ok: true, value }` or `{ ok: false, error }`.
6
+ * routes, which is how every browser-facing service in DSH reaches its host.
7
+ * Every response is `{ ok: true, value }` or `{ ok: false, error }`.
8
8
  *
9
9
  * @module dsh-project-mcp/ui
10
10
  */
@@ -168,6 +168,21 @@ const SAVE_STATUS: Record<SaveErrorCode, number> = {
168
168
  failed: 500,
169
169
  }
170
170
 
171
+ /**
172
+ * HTTP status a `GET tool` refusal answers with: the same vocabulary, one
173
+ * different reading.
174
+ *
175
+ * A save or a policy change names something the panel is looking at *and
176
+ * edits*, so a name this host does not know is a malformed request there —
177
+ * `400`. A tool read is a *fetch* of a row the panel already drew, so an
178
+ * unknown project, session or name means the picture moved under it, which is
179
+ * exactly what `404` says: `GET logs` answers the same question the same way.
180
+ */
181
+ const TOOL_STATUS: Record<SaveErrorCode, number> = {
182
+ ...SAVE_STATUS,
183
+ 'not-found': 404,
184
+ }
185
+
171
186
  /**
172
187
  * Read one numeric query parameter.
173
188
  *
@@ -302,6 +317,49 @@ export function createRouteHandler(
302
317
  })
303
318
  return
304
319
  }
320
+ // One tool's detail, for a row the panel opened. On demand rather than in
321
+ // the snapshot — descriptions and schemas are the expensive part, and every
322
+ // change frame and poll carries the whole snapshot — so nothing grows on the
323
+ // wire and the answer is fetched once per opened row. The same precedent as
324
+ // `logs`: the route checks that it was given three names at all and refuses
325
+ // a request missing one, while "this host does not know that project,
326
+ // session or tool" is the service's `404` rather than the route's `400`.
327
+ if (method === 'GET' && action === 'tool') {
328
+ const projectRoot = url.searchParams.get('projectRoot')
329
+ const sessionId = url.searchParams.get('sessionId')
330
+ const name = url.searchParams.get('name')
331
+ if (projectRoot === null || projectRoot === '') {
332
+ send(res, 400, {
333
+ ok: false,
334
+ error: { code: 'bad-request', message: 'GET tool needs a projectRoot' },
335
+ })
336
+ return
337
+ }
338
+ if (sessionId === null || sessionId === '') {
339
+ send(res, 400, {
340
+ ok: false,
341
+ error: { code: 'bad-request', message: 'GET tool needs a sessionId' },
342
+ })
343
+ return
344
+ }
345
+ if (name === null || name === '') {
346
+ send(res, 400, {
347
+ ok: false,
348
+ error: { code: 'bad-request', message: 'GET tool needs a name' },
349
+ })
350
+ return
351
+ }
352
+ const outcome = service.toolFacts(projectRoot, sessionId, name)
353
+ if (!outcome.ok) {
354
+ send(res, TOOL_STATUS[outcome.code], {
355
+ ok: false,
356
+ error: { code: outcome.code, message: outcome.message },
357
+ })
358
+ return
359
+ }
360
+ send(res, 200, { ok: true, value: outcome.value })
361
+ return
362
+ }
305
363
  if (method === 'POST' && action === 'retry') {
306
364
  const request = operatorRequestOf(await readJson(req))
307
365
  await reply(res, () => service.retry(request.projectRoot), request)