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.
@@ -0,0 +1,211 @@
1
+ /**
2
+ * Filesystem discovery for `dsh-project-mcp`: project root, config documents,
3
+ * and the two credential sources behind `${...}` references — the global
4
+ * credentials file and the project's own dotenv documents.
5
+ *
6
+ * Which MCP documents are read is a setting, not a constant: the deployment
7
+ * lists its **local** documents (relative to a project root) and its **global**
8
+ * ones (relative to `$HOME`, or absolute) in `localFiles` / `globalFiles`, and
9
+ * one spec resolves through {@link expandConfigPath} to an absolute path.
10
+ *
11
+ * @module dsh-project-mcp/discovery
12
+ */
13
+
14
+ import { existsSync, readFileSync, readdirSync } from 'node:fs'
15
+ import { homedir } from 'node:os'
16
+ import { dirname, isAbsolute, join, resolve } from 'node:path'
17
+ import { parseCredentials, parseEnvFile } from './parse.ts'
18
+
19
+ /** Directory/marker names that terminate the upward project-root walk. */
20
+ export const DEFAULT_PROJECT_MARKERS = ['.git', '.dsh', '.kimi-code', 'package.json']
21
+
22
+ /** File-suffix markers that terminate the upward project-root walk. */
23
+ export const DEFAULT_FILE_MARKERS = ['.sln', '.slnx', '.csproj']
24
+
25
+ /**
26
+ * Project-relative documents read out of the box, in increasing priority: the
27
+ * native DSH file only. A deployment that also wants another agent's document
28
+ * names it in `localFiles`.
29
+ */
30
+ export const DEFAULT_LOCAL_FILES: readonly string[] = ['.dsh/mcp.json']
31
+
32
+ /**
33
+ * Global documents read out of the box, in increasing priority: none. A global
34
+ * document is read only when a deployment lists it in `globalFiles`, so a
35
+ * project never inherits a server it did not ask for.
36
+ */
37
+ export const DEFAULT_GLOBAL_FILES: readonly string[] = []
38
+
39
+ /** `$DSH_HOME`, falling back to `~/.dsh`. */
40
+ export function dshHome(env: Record<string, string | undefined> = process.env): string {
41
+ const configured = env.DSH_HOME
42
+ return configured !== undefined && configured !== '' ? configured : join(homedir(), '.dsh')
43
+ }
44
+
45
+ /** Environment-variable references a path spec may carry. */
46
+ const HOME_REFERENCE = '~'
47
+ const DSH_HOME_REFERENCE = '$DSH_HOME'
48
+ const DSH_HOME_BRACED_REFERENCE = '${DSH_HOME}'
49
+
50
+ /**
51
+ * Resolve one configured document spec to an absolute path.
52
+ *
53
+ * A spec is read the way a shell reads it, in this order:
54
+ *
55
+ * - `~/x` (and a bare `~`) → `$HOME/x`;
56
+ * - `$DSH_HOME/x` or `${DSH_HOME}/x` → the deployment's own home;
57
+ * - an absolute path → itself;
58
+ * - anything else → `base/x`, so a local document stays inside the project and
59
+ * a global one stays inside `$HOME`.
60
+ *
61
+ * @param spec - one entry of `localFiles` or `globalFiles`.
62
+ * @param base - directory a relative spec is read from.
63
+ * @param env - environment used to resolve `$DSH_HOME`.
64
+ * @returns the absolute document path.
65
+ */
66
+ export function expandConfigPath(
67
+ spec: string,
68
+ base: string,
69
+ env: Record<string, string | undefined> = process.env,
70
+ ): string {
71
+ if (spec === HOME_REFERENCE) return homedir()
72
+ if (spec.startsWith(`${HOME_REFERENCE}/`)) return resolve(homedir(), spec.slice(2))
73
+ if (spec === DSH_HOME_REFERENCE || spec === DSH_HOME_BRACED_REFERENCE) return dshHome(env)
74
+ if (spec.startsWith(`${DSH_HOME_REFERENCE}/`)) {
75
+ return resolve(dshHome(env), spec.slice(DSH_HOME_REFERENCE.length + 1))
76
+ }
77
+ if (spec.startsWith(`${DSH_HOME_BRACED_REFERENCE}/`)) {
78
+ return resolve(dshHome(env), spec.slice(DSH_HOME_BRACED_REFERENCE.length + 1))
79
+ }
80
+ if (isAbsolute(spec)) return resolve(spec)
81
+ return resolve(base, spec)
82
+ }
83
+
84
+ /**
85
+ * Project documents to read for one project root, in increasing priority — a
86
+ * later document overrides an earlier entry of the same `serverName`.
87
+ * @param projectRoot - absolute project root.
88
+ * @param files - configured project-relative specs, lowest priority first.
89
+ * @param env - environment used to resolve `$DSH_HOME`.
90
+ * @returns absolute paths, lowest priority first.
91
+ */
92
+ export function localConfigPaths(
93
+ projectRoot: string,
94
+ files: readonly string[] = DEFAULT_LOCAL_FILES,
95
+ env: Record<string, string | undefined> = process.env,
96
+ ): string[] {
97
+ return files.map((spec) => expandConfigPath(spec, projectRoot, env))
98
+ }
99
+
100
+ /**
101
+ * Global documents of one deployment, in increasing priority. They are read
102
+ * before a project's own documents, so a project declaration always wins.
103
+ * @param files - configured specs, lowest priority first.
104
+ * @param env - environment used to resolve `$DSH_HOME`.
105
+ * @returns absolute paths, lowest priority first.
106
+ */
107
+ export function globalConfigPaths(
108
+ files: readonly string[] = DEFAULT_GLOBAL_FILES,
109
+ env: Record<string, string | undefined> = process.env,
110
+ ): string[] {
111
+ const home = homedir()
112
+ return files.map((spec) => expandConfigPath(spec, home, env))
113
+ }
114
+
115
+ /** Default credentials document consulted for `${input:NAME}` values. */
116
+ export function defaultCredentialsPath(env: Record<string, string | undefined> = process.env): string {
117
+ return join(dshHome(env), '.credentials.yaml')
118
+ }
119
+
120
+ /** Project-relative dotenv documents read for `${...}` values, lowest priority first. */
121
+ export const PROJECT_ENV_RELATIVE = ['.env', '.dsh/.env'] as const
122
+
123
+ /**
124
+ * Dotenv documents of one project, lowest priority first: the plain `.env` at
125
+ * the project root, then the one in `.dsh` next to `mcp.json`. A value declared
126
+ * in both is taken from the `.dsh` file — the project-local declaration wins.
127
+ * @param projectRoot - absolute project root.
128
+ * @returns absolute paths, lowest priority first.
129
+ */
130
+ export function projectEnvPaths(projectRoot: string): string[] {
131
+ return PROJECT_ENV_RELATIVE.map((relative) => join(projectRoot, relative))
132
+ }
133
+
134
+ /**
135
+ * Walk upward from `cwd` to the first directory carrying a project marker.
136
+ * @param cwd - absolute session working directory.
137
+ * @param markers - directory/file marker names.
138
+ * @param fileMarkers - file suffixes that also mark a project root.
139
+ * @returns the absolute project root, or `undefined` when no marker is found.
140
+ */
141
+ export function findProjectRoot(
142
+ cwd: string,
143
+ markers: readonly string[] = DEFAULT_PROJECT_MARKERS,
144
+ fileMarkers: readonly string[] = DEFAULT_FILE_MARKERS,
145
+ ): string | undefined {
146
+ let current = resolve(cwd)
147
+ for (;;) {
148
+ if (isProjectRoot(current, markers, fileMarkers)) return current
149
+ const parent = dirname(current)
150
+ if (parent === current) return undefined
151
+ current = parent
152
+ }
153
+ }
154
+
155
+ function isProjectRoot(
156
+ dir: string,
157
+ markers: readonly string[],
158
+ fileMarkers: readonly string[],
159
+ ): boolean {
160
+ for (const marker of markers) {
161
+ if (existsSync(join(dir, marker))) return true
162
+ }
163
+ if (fileMarkers.length === 0) return false
164
+ try {
165
+ for (const entry of readdirSync(dir)) {
166
+ if (fileMarkers.some((suffix) => entry.endsWith(suffix))) return true
167
+ }
168
+ } catch {
169
+ return false
170
+ }
171
+ return false
172
+ }
173
+
174
+ /** Read the credentials document into a flat string map; missing file yields `{}`. */
175
+ export function readSecrets(path: string): Record<string, string> {
176
+ try {
177
+ return parseCredentials(readFileSync(path, 'utf8'))
178
+ } catch {
179
+ return {}
180
+ }
181
+ }
182
+
183
+ /** Read one dotenv document into a flat string map; missing file yields `{}`. */
184
+ export function readEnvFile(path: string): Record<string, string> {
185
+ try {
186
+ return parseEnvFile(readFileSync(path, 'utf8'))
187
+ } catch {
188
+ return {}
189
+ }
190
+ }
191
+
192
+ /**
193
+ * Directories that hold this project's MCP documents. Used by the flat-watch
194
+ * fallback when the runtime cannot watch a tree recursively.
195
+ * @param projectRoot - absolute project root.
196
+ * @param files - configured project-relative specs, lowest priority first.
197
+ * @param env - environment used to resolve `$DSH_HOME`.
198
+ * @returns existing directories, project root first, deduplicated.
199
+ */
200
+ export function configDirectories(
201
+ projectRoot: string,
202
+ files: readonly string[] = DEFAULT_LOCAL_FILES,
203
+ env: Record<string, string | undefined> = process.env,
204
+ ): string[] {
205
+ const directories = [projectRoot]
206
+ for (const path of localConfigPaths(projectRoot, files, env)) {
207
+ const directory = dirname(path)
208
+ if (!directories.includes(directory)) directories.push(directory)
209
+ }
210
+ return directories.filter((directory) => existsSync(directory))
211
+ }
@@ -0,0 +1,415 @@
1
+ /**
2
+ * Project-level MCP guidance for the session system prompt.
3
+ *
4
+ * A project can mount a large MCP surface, and with activation on (see
5
+ * `./activation.ts`) most of its tools are not listed in a request at all: they
6
+ * are offered on demand through `mcp_search_tools`. The per-server
7
+ * `mcp:<server>` sections mcp-client publishes say what a server *is*, but
8
+ * nothing tells the model that a tool it cannot see may still be asked for.
9
+ *
10
+ * This module contributes that one short section. {@link buildGuidance} is
11
+ * pure: it turns a plain input object into markdown — or `''` when there is
12
+ * nothing worth saying — with a hard length cap, a deterministic server order
13
+ * and a deterministic truncated tool sample. {@link installGuidance} is the
14
+ * thin scope wiring the runtime installs beside its mount and activation
15
+ * wiring: it registers the section through `ctx.inject(['systemPrompt'], …)`
16
+ * with a stable name whose code-unit order places it ahead of every per-server
17
+ * block, and reads the project's live state at each assembly, so a rescan that
18
+ * changes the mounted set changes the text without re-registering anything.
19
+ *
20
+ * The text never carries an absolute path, an endpoint or any other local
21
+ * machine identifier: the project is named by its `~`-collapsed label
22
+ * ({@link projectLabel}) and the input holds server names, states and tool
23
+ * names only.
24
+ *
25
+ * Like `./activation.ts`, the module describes the prompt surface structurally
26
+ * instead of importing `@deepseek-ai/dsh-system-prompt`: that peer is not
27
+ * installed in every deployment, so the section and the injected scope are
28
+ * declared by the minimal types below.
29
+ *
30
+ * @module dsh-project-mcp/guidance
31
+ */
32
+
33
+ import { DEFAULT_ACTIVATION_ENABLED, SEARCH_TOOL_NAME } from './activation.ts'
34
+ import type { ServerStatus } from './types.ts'
35
+
36
+ /** `true` unless a deployment turns the guidance section off. */
37
+ export const DEFAULT_GUIDANCE_ENABLED = true
38
+
39
+ /**
40
+ * Section name. At equal orders sections sort by code-unit name, and `-`
41
+ * (0x2D) precedes `:` (0x3A), so this name — exactly like mcp-resources'
42
+ * `mcp-resource-servers` — sorts ahead of every `mcp:<server>` instruction
43
+ * block mcp-client publishes at the same order.
44
+ */
45
+ export const GUIDANCE_SECTION_NAME = 'mcp-project-guidance'
46
+
47
+ /** Hard cap on the section text; {@link buildGuidance} never returns more. */
48
+ export const MAX_GUIDANCE_CHARS = 1200
49
+
50
+ /** Server bullets rendered at most, before the rest is summarized. */
51
+ export const MAX_GUIDANCE_SERVERS = 8
52
+
53
+ /** Deferred tool names the on-demand inventory line shows before `+N more`. */
54
+ export const MAX_GUIDANCE_HIDDEN_NAMES = 12
55
+
56
+ /** Baseline names the most-used line shows before `+N more`. */
57
+ export const MAX_GUIDANCE_MOST_USED = 4
58
+
59
+ /** Longest purpose text kept in one server bullet. */
60
+ export const MAX_GUIDANCE_PURPOSE = 80
61
+
62
+ /** One mounted server, as far as the guidance section describes it. */
63
+ export interface GuidanceServer {
64
+ /** `serverName` of the mount. */
65
+ readonly name: string
66
+ /** Transport, when the mount has one. */
67
+ readonly transport?: 'stdio' | 'streamable-http'
68
+ /** Live mount state. */
69
+ readonly status: ServerStatus
70
+ /** Tool names the server currently publishes, in any order. */
71
+ readonly tools?: readonly string[]
72
+ /** Optional one-line purpose, shown after the server name. */
73
+ readonly purpose?: string
74
+ }
75
+
76
+ /**
77
+ * Plain input of {@link buildGuidance}. Every field is optional so a caller
78
+ * that predates this feature (or a test) can pass a bare object; the defaults
79
+ * describe "no project, no servers".
80
+ */
81
+ export interface GuidanceInput {
82
+ /** `~`-collapsed project label; defaults to `this project`. */
83
+ readonly project?: string
84
+ /** Mounted servers, in any order. */
85
+ readonly servers?: readonly GuidanceServer[]
86
+ /** Tool names offered directly in the request right now. */
87
+ readonly offered?: readonly string[]
88
+ /** Tool names reachable only through `mcp_search_tools` right now. */
89
+ readonly deferred?: readonly string[]
90
+ /**
91
+ * The counter-seeded hot tools, most-called first. They are offered directly
92
+ * from the first step on; naming them keeps the model from searching for
93
+ * what it already has.
94
+ */
95
+ readonly mostUsed?: readonly string[]
96
+ /** Whether the on-demand search surface is on; defaults to the activation default. */
97
+ readonly activationEnabled?: boolean
98
+ }
99
+
100
+ /**
101
+ * Build the project-MCP guidance section.
102
+ *
103
+ * Deterministic and total: server bullets follow code-unit name order, the
104
+ * deferred surface is listed as one flat, sorted, deduped names line, and the
105
+ * result never exceeds {@link MAX_GUIDANCE_CHARS} — when it would, trailing
106
+ * server bullets are replaced by an `and N more server(s)` line, the on-demand
107
+ * paragraph and the names line are reserved their room first, and a final cut
108
+ * falls back to the last complete line. Equal input always yields equal
109
+ * output, and `''` means there is nothing worth saying.
110
+ *
111
+ * @param input - project label, mounted servers and the offered/deferred split.
112
+ * @returns markdown for one prompt section, or `''`.
113
+ */
114
+ export function buildGuidance(input: GuidanceInput): string {
115
+ const servers = normalizeServers(input.servers ?? [])
116
+ if (servers.length === 0) return ''
117
+ const activationEnabled = input.activationEnabled ?? DEFAULT_ACTIVATION_ENABLED
118
+ const offered = new Set(input.offered ?? [])
119
+ // A tool that is already offered is never presented as on-demand, and with
120
+ // activation off nothing is on demand at all.
121
+ const deferred = new Set(
122
+ activationEnabled ? (input.deferred ?? []).filter((name) => !offered.has(name)) : [],
123
+ )
124
+ const header = [
125
+ '## Project MCP servers',
126
+ '',
127
+ `Project \`${label(input.project)}\` mounts ${servers.length} MCP server(s) in this session.`,
128
+ '',
129
+ ]
130
+ const tail: string[] = []
131
+ // The counter-seeded hot tools are offered from the first step on; naming
132
+ // them here keeps the model from searching for what it already has.
133
+ const hot = mostUsedLine(input.mostUsed ?? [])
134
+ if (activationEnabled && hot !== '') tail.push('', hot)
135
+ if (deferred.size > 0) {
136
+ tail.push('', onDemandParagraph(offered.size, deferred.size))
137
+ tail.push('', hiddenNamesLine(deferred))
138
+ }
139
+ const bullets: string[] = []
140
+ let hidden = 0
141
+ for (const [index, server] of servers.entries()) {
142
+ const remaining = servers.length - index
143
+ const bullet = serverBullet(server)
144
+ const overflow = remaining > 1 ? [`- … and ${remaining - 1} more server(s)`] : []
145
+ const candidate = [...header, ...bullets, bullet, ...overflow, ...tail].join('\n')
146
+ if (index >= MAX_GUIDANCE_SERVERS || candidate.length > MAX_GUIDANCE_CHARS) {
147
+ hidden = remaining
148
+ break
149
+ }
150
+ bullets.push(bullet)
151
+ }
152
+ if (hidden > 0) bullets.push(`- … and ${hidden} more server(s)`)
153
+ return applyCap([...header, ...bullets, ...tail].join('\n'))
154
+ }
155
+
156
+ /**
157
+ * `~`-collapsed display label for a project root.
158
+ *
159
+ * The session prompt must never carry an absolute path or a local machine
160
+ * identifier, so the label is the home-relative form when the root lives under
161
+ * `home` and the directory name otherwise. `home` is passed in rather than read
162
+ * from the environment, which keeps the helper pure and testable.
163
+ *
164
+ * @param projectRoot - absolute project root, or any path-shaped string.
165
+ * @param home - home directory to collapse to `~`, when known.
166
+ * @returns a relative `~/…` label, the directory name, or `this project`.
167
+ */
168
+ export function projectLabel(projectRoot: string, home?: string): string {
169
+ const root = stripSeparators(projectRoot)
170
+ if (root === '') return 'this project'
171
+ if (home !== undefined) {
172
+ const base = stripSeparators(home)
173
+ if (base !== '') {
174
+ if (root === base) return '~'
175
+ if (root.startsWith(`${base}/`) || root.startsWith(`${base}\\`)) {
176
+ return `~${root.slice(base.length)}`
177
+ }
178
+ }
179
+ }
180
+ const index = Math.max(root.lastIndexOf('/'), root.lastIndexOf('\\'))
181
+ return index === -1 ? root : root.slice(index + 1)
182
+ }
183
+
184
+ /** The prompt-section fields this module registers (structural view). */
185
+ export interface GuidanceSectionLike {
186
+ /** Unique section name. */
187
+ readonly name: string
188
+ /** Numeric sort order. */
189
+ readonly order: number
190
+ /** `false` preserves literal text; this section carries no variables. */
191
+ readonly interpolate?: boolean
192
+ /** Text, or a provider evaluated at each assembly. */
193
+ readonly text: string | (() => string)
194
+ }
195
+
196
+ /** The `systemPrompt` slice the wiring reads (structural view). */
197
+ export interface GuidancePromptLike {
198
+ /**
199
+ * Register one ordered section in the calling scope.
200
+ * @param section - the section to register.
201
+ * @returns the registration's effect disposer.
202
+ */
203
+ section(section: GuidanceSectionLike): unknown
204
+ /**
205
+ * Resolve a centrally owned placement.
206
+ * @param name - stable placement name.
207
+ * @returns the numeric sort order.
208
+ */
209
+ getSectionOrder(name: 'MCP_SERVERS'): number
210
+ }
211
+
212
+ /** The injected scope carrying `systemPrompt`. */
213
+ export interface GuidancePromptScopeLike {
214
+ /** The prompt registry. */
215
+ readonly systemPrompt: GuidancePromptLike
216
+ }
217
+
218
+ /**
219
+ * The agent-scoped context slice the guidance wiring touches. Described
220
+ * structurally so the wiring is testable without a live harness.
221
+ */
222
+ export interface GuidanceContextLike {
223
+ /**
224
+ * Start a callback once the injected services exist; the injected scope owns
225
+ * what the callback registers.
226
+ * @param deps - service names the callback requires.
227
+ * @param callback - receives the injected scope.
228
+ * @returns a disposer for the callback's own fiber, when the runtime gives one.
229
+ */
230
+ inject(deps: readonly string[], callback: (inner: GuidancePromptScopeLike) => unknown): unknown
231
+ }
232
+
233
+ /** Wiring options for {@link installGuidance}. */
234
+ export interface GuidanceWiringOptions {
235
+ /** Agent-scoped context; the section lives here. */
236
+ readonly ctx: GuidanceContextLike
237
+ /** Live section text; called at every assembly, so it may read changing state. */
238
+ readonly text: () => string
239
+ /** Section name override; defaults to {@link GUIDANCE_SECTION_NAME}. */
240
+ readonly name?: string
241
+ /** Sink for a contained failure of this plugin's own work. */
242
+ readonly onError?: (error: unknown) => void
243
+ }
244
+
245
+ /**
246
+ * Register the guidance section on one agent scope.
247
+ *
248
+ * The section goes in through `ctx.inject(['systemPrompt'], …)`, so the scope
249
+ * fiber owns it and a scope disposal unregisters it with the real registry.
250
+ * The returned disposer is the explicit path for a host that publishes a plain
251
+ * `systemPrompt` stub — the runtime keeps it and releases it exactly when it
252
+ * releases the scope (idle release and agent disposal), so no section outlives
253
+ * its mounts. It is idempotent.
254
+ *
255
+ * @param options - scope, live text provider and an optional failure sink.
256
+ * @returns the disposer that unregisters everything installed here.
257
+ */
258
+ export function installGuidance(options: GuidanceWiringOptions): () => void {
259
+ const disposers: (() => void)[] = []
260
+ const contain = (error: unknown): void => {
261
+ options.onError?.(error)
262
+ }
263
+ try {
264
+ const registered = options.ctx.inject(['systemPrompt'], (inner) => {
265
+ const dispose = inner.systemPrompt.section({
266
+ name: options.name ?? GUIDANCE_SECTION_NAME,
267
+ order: inner.systemPrompt.getSectionOrder('MCP_SERVERS'),
268
+ interpolate: false,
269
+ text: options.text,
270
+ })
271
+ const release = disposerOf(dispose)
272
+ if (release !== undefined) disposers.push(release)
273
+ return dispose
274
+ })
275
+ const release = disposerOf(registered)
276
+ if (release !== undefined) disposers.push(release)
277
+ } catch (error) {
278
+ contain(error)
279
+ }
280
+ return () => {
281
+ // Newest first: the section registration is released before the injected
282
+ // fiber that owns it. `splice` makes a second call a no-op.
283
+ for (const dispose of disposers.splice(0).reverse()) {
284
+ try {
285
+ dispose()
286
+ } catch (error) {
287
+ contain(error)
288
+ }
289
+ }
290
+ }
291
+ }
292
+
293
+ /** Dedupe by name, drop blank names and put the rest in code-unit name order. */
294
+ function normalizeServers(servers: readonly GuidanceServer[]): GuidanceServer[] {
295
+ const byName = new Map<string, GuidanceServer>()
296
+ for (const server of servers) {
297
+ const name = server.name.trim()
298
+ if (name === '' || byName.has(name)) continue
299
+ byName.set(name, { ...server, name })
300
+ }
301
+ return [...byName.values()].sort((left, right) => compareNames(left.name, right.name))
302
+ }
303
+
304
+ /** One server bullet: state and the optional purpose. */
305
+ function serverBullet(server: GuidanceServer): string {
306
+ const state =
307
+ server.transport === undefined ? server.status : `${server.transport}, ${server.status}`
308
+ const purpose = shorten(server.purpose, MAX_GUIDANCE_PURPOSE)
309
+ return `- ${server.name} (${state})${purpose === '' ? '' : ` — ${purpose}`}`
310
+ }
311
+
312
+ /**
313
+ * The flat inventory of the deferred surface: bare names only, sorted and
314
+ * deduped, truncated to {@link MAX_GUIDANCE_HIDDEN_NAMES} with a `+N more`.
315
+ * Descriptions and schemas are the expensive part, so the line carries names
316
+ * only — the model picks the one it needs and runs a single targeted search
317
+ * instead of rephrasing blind guesses. The sentence also states the
318
+ * direct-call contract: deferral trims the assembled request list, it never
319
+ * unregisters the tool, so a call by the exact full name still executes;
320
+ * searching the name first is how the model sees the description and
321
+ * parameters, not a gate.
322
+ */
323
+ function hiddenNamesLine(deferred: ReadonlySet<string>): string {
324
+ const names = [...deferred].sort(compareNames)
325
+ const shown = names.slice(0, MAX_GUIDANCE_HIDDEN_NAMES)
326
+ const hidden = names.length - shown.length
327
+ const list = hidden === 0 ? shown.join(', ') : `${shown.join(', ')} +${hidden} more`
328
+ return (
329
+ `On demand right now: ${list} — every one of them runs when called by its exact full ` +
330
+ `name \`mcp__<server>__<tool>\`; search a name with \`${SEARCH_TOOL_NAME}\` first to see ` +
331
+ 'its description and parameters.'
332
+ )
333
+ }
334
+
335
+ /** The paragraph that turns "a tool is missing" into "ask for it". */
336
+ function onDemandParagraph(offered: number, deferred: number): string {
337
+ return (
338
+ `${offered} of ${offered + deferred} MCP tool(s) are offered directly; the other ${deferred} ` +
339
+ `are offered on demand — call \`${SEARCH_TOOL_NAME}\` with a keyword or a tool name (several ` +
340
+ 'words are matched one by one), and a tool it activates becomes callable from the next ' +
341
+ 'step. Search once with the best keywords you have; when the search reports no match, this ' +
342
+ 'project mounts no such ' +
343
+ 'tool — report the gap instead of rephrasing the search or guessing a name.'
344
+ )
345
+ }
346
+
347
+ /**
348
+ * The session-start "most used" line. The input arrives most-called first
349
+ * (the seeded baseline's insertion order is the rank order), so the line
350
+ * keeps that order and samples the top names before `+N more`.
351
+ */
352
+ function mostUsedLine(mostUsed: readonly string[]): string {
353
+ const unique: string[] = []
354
+ const seen = new Set<string>()
355
+ for (const name of mostUsed) {
356
+ const trimmed = name.trim()
357
+ if (trimmed === '' || seen.has(trimmed)) continue
358
+ seen.add(trimmed)
359
+ unique.push(trimmed)
360
+ }
361
+ if (unique.length === 0) return ''
362
+ const shown = unique.slice(0, MAX_GUIDANCE_MOST_USED)
363
+ const hidden = unique.length - shown.length
364
+ const list = hidden === 0 ? shown.join(', ') : `${shown.join(', ')} +${hidden} more`
365
+ return (
366
+ `Most used in this project's sessions, offered from the first step on: ${list} — ` +
367
+ 'call them directly, no search needed.'
368
+ )
369
+ }
370
+
371
+ /** Project label, or a neutral fallback for a blank/missing one. */
372
+ function label(project: string | undefined): string {
373
+ const value = project?.trim() ?? ''
374
+ return value === '' ? 'this project' : value
375
+ }
376
+
377
+ /** Trim a purpose and bound it, so one server cannot crowd the section. */
378
+ function shorten(text: string | undefined, max: number): string {
379
+ const value = text?.trim() ?? ''
380
+ if (value.length <= max) return value
381
+ return `${value.slice(0, max - 1).replace(/\s+$/, '')}…`
382
+ }
383
+
384
+ /** Final guard: cut at the last complete line and add an ellipsis. */
385
+ function applyCap(text: string): string {
386
+ if (text.length <= MAX_GUIDANCE_CHARS) return text
387
+ const head = text.slice(0, MAX_GUIDANCE_CHARS - 1)
388
+ const cut = head.lastIndexOf('\n')
389
+ const body = (cut === -1 ? head : head.slice(0, cut)).replace(/\s+$/, '')
390
+ return `${body}…`
391
+ }
392
+
393
+ /** Remove trailing path separators; a bare root collapses to an empty string. */
394
+ function stripSeparators(path: string): string {
395
+ return path.replace(/[\\/]+$/, '')
396
+ }
397
+
398
+ function compareNames(left: string, right: string): number {
399
+ return left < right ? -1 : left > right ? 1 : 0
400
+ }
401
+
402
+ /** Read a disposer from either a function or an object with `dispose()`. */
403
+ function disposerOf(value: unknown): (() => void) | undefined {
404
+ if (typeof value === 'function') return value as () => void
405
+ if (typeof value === 'object' && value !== null) {
406
+ const target = value as { dispose?: unknown }
407
+ if (typeof target.dispose === 'function') {
408
+ const dispose = target.dispose as () => void
409
+ return () => {
410
+ dispose.call(target)
411
+ }
412
+ }
413
+ }
414
+ return undefined
415
+ }