@kirkchinese/harness-forge 0.4.0 → 0.5.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.
Files changed (125) hide show
  1. package/README.md +4 -0
  2. package/docs/DETAIL.zh.md +47 -0
  3. package/lib/agents/presets.d.ts +7 -0
  4. package/lib/agents/presets.js +11 -1
  5. package/lib/agents/profiles.js +3 -2
  6. package/lib/agents/row.js +3 -1
  7. package/lib/client/paths.d.ts +12 -0
  8. package/lib/client/paths.js +68 -0
  9. package/lib/client/typert.d.ts +12 -1
  10. package/lib/client/typert.js +54 -6
  11. package/lib/client.js +1593 -270
  12. package/lib/commands/row.js +1 -1
  13. package/lib/context/instructions.js +5 -5
  14. package/lib/dsh/host.d.ts +3 -0
  15. package/lib/dsh/host.js +3 -0
  16. package/lib/forge/contract.d.ts +42 -2
  17. package/lib/forge/contract.js +3 -1
  18. package/lib/forge/follow.d.ts +30 -0
  19. package/lib/forge/follow.js +73 -0
  20. package/lib/forge/ledger.d.ts +70 -7
  21. package/lib/forge/ledger.js +314 -42
  22. package/lib/forge/projects.d.ts +5 -2
  23. package/lib/forge/projects.js +23 -16
  24. package/lib/forge/remote/archive.d.ts +65 -0
  25. package/lib/forge/remote/archive.js +565 -0
  26. package/lib/forge/remote/code-parts.d.ts +18 -0
  27. package/lib/forge/remote/code-parts.js +76 -0
  28. package/lib/forge/remote/fetch.d.ts +265 -0
  29. package/lib/forge/remote/fetch.js +1133 -0
  30. package/lib/forge/remote/service.d.ts +256 -0
  31. package/lib/forge/remote/service.js +868 -0
  32. package/lib/forge/service.d.ts +19 -9
  33. package/lib/forge/service.js +47 -31
  34. package/lib/forge/settings.d.ts +5 -3
  35. package/lib/forge/settings.js +11 -4
  36. package/lib/forge/state.d.ts +60 -0
  37. package/lib/forge/state.js +174 -58
  38. package/lib/hooks/broker/engine.js +2 -8
  39. package/lib/hooks/broker/session-events.d.ts +5 -0
  40. package/lib/hooks/broker/session-events.js +12 -3
  41. package/lib/hooks/broker/types.d.ts +7 -5
  42. package/lib/hooks/condition.d.ts +78 -2
  43. package/lib/hooks/condition.js +494 -73
  44. package/lib/hooks/config.d.ts +1 -1
  45. package/lib/hooks/config.js +4 -0
  46. package/lib/hooks/glob.d.ts +41 -0
  47. package/lib/hooks/glob.js +114 -0
  48. package/lib/hooks/permissions.d.ts +8 -3
  49. package/lib/hooks/permissions.js +119 -26
  50. package/lib/hooks/powershell-aliases.d.ts +19 -0
  51. package/lib/hooks/powershell-aliases.js +58 -0
  52. package/lib/hooks/process.d.ts +17 -0
  53. package/lib/hooks/process.js +156 -1
  54. package/lib/hooks/row.js +2 -0
  55. package/lib/hooks/runner.d.ts +17 -4
  56. package/lib/hooks/runner.js +42 -13
  57. package/lib/hooks/shell-commands.d.ts +10 -1
  58. package/lib/hooks/shell-commands.js +74 -10
  59. package/lib/hooks/shell.d.ts +3 -2
  60. package/lib/hooks/shell.js +5 -2
  61. package/lib/hooks/vocabulary.js +3 -1
  62. package/lib/mcp/catalog.d.ts +5 -2
  63. package/lib/mcp/catalog.js +18 -10
  64. package/lib/mcp/mount.d.ts +40 -2
  65. package/lib/mcp/mount.js +131 -31
  66. package/lib/mcp/policy.d.ts +42 -0
  67. package/lib/mcp/policy.js +43 -0
  68. package/lib/mcp/remote.js +5 -15
  69. package/lib/mcp/row.js +111 -17
  70. package/lib/mods/loader.js +4 -0
  71. package/lib/mods/service/turns.d.ts +8 -7
  72. package/lib/mods/service/turns.js +10 -35
  73. package/lib/opencode/bun.js +14 -2
  74. package/lib/opencode/row.d.ts +14 -1
  75. package/lib/opencode/row.js +38 -20
  76. package/lib/opencode/runtime/server.js +2 -1
  77. package/lib/porting/adapter-paths.d.ts +13 -0
  78. package/lib/porting/adapter-paths.js +120 -0
  79. package/lib/porting/port-gap.d.ts +10 -4
  80. package/lib/porting/port-gap.js +43 -7
  81. package/lib/porting/prompt.js +9 -7
  82. package/lib/porting/row.js +7 -5
  83. package/lib/porting/verify-port.d.ts +3 -10
  84. package/lib/porting/verify-port.js +12 -34
  85. package/lib/sessions/chat-import.d.ts +48 -0
  86. package/lib/sessions/chat-import.js +44 -0
  87. package/lib/sessions/claude.d.ts +16 -10
  88. package/lib/sessions/claude.js +76 -55
  89. package/lib/sessions/codex-discover.d.ts +34 -0
  90. package/lib/sessions/codex-discover.js +205 -0
  91. package/lib/sessions/codex-meta.d.ts +63 -0
  92. package/lib/sessions/codex-meta.js +148 -0
  93. package/lib/sessions/codex-text.d.ts +9 -0
  94. package/lib/sessions/codex-text.js +44 -0
  95. package/lib/sessions/codex.d.ts +34 -22
  96. package/lib/sessions/codex.js +150 -183
  97. package/lib/sessions/opencode.d.ts +15 -9
  98. package/lib/sessions/opencode.js +77 -58
  99. package/lib/sessions/persist.d.ts +162 -0
  100. package/lib/sessions/persist.js +377 -0
  101. package/lib/sessions/row.d.ts +2 -1
  102. package/lib/sessions/row.js +75 -9
  103. package/lib/sessions/turns.d.ts +31 -0
  104. package/lib/sessions/turns.js +63 -0
  105. package/lib/sessions/zstd.d.ts +15 -0
  106. package/lib/sessions/zstd.js +152 -0
  107. package/lib/shared/render.d.ts +30 -1
  108. package/lib/shared/render.js +813 -48
  109. package/lib/skills/provider.d.ts +2 -0
  110. package/lib/skills/provider.js +8 -2
  111. package/lib/skills/row.js +1 -1
  112. package/lib/workbench/adapter-coverage.d.ts +20 -2
  113. package/lib/workbench/adapter-coverage.js +46 -7
  114. package/lib/workbench/overview.d.ts +77 -27
  115. package/lib/workbench/overview.js +99 -12
  116. package/lib/workbench/remote.d.ts +64 -21
  117. package/lib/workbench/remote.js +181 -42
  118. package/lib/workbench/settings.d.ts +5 -1
  119. package/lib/workbench/settings.js +6 -2
  120. package/lib/workbench/workbench.d.ts +34 -4
  121. package/lib/workbench/workbench.js +147 -46
  122. package/locale/zh.json +2 -1
  123. package/package.json +3 -2
  124. package/lib/forge/marketplace-install.d.ts +0 -3
  125. package/lib/forge/marketplace-install.js +0 -64
@@ -25,7 +25,22 @@ export interface McpVariables {
25
25
  readonly dataDir: string;
26
26
  /** The `env` of imported harness settings: servers inherit it, `${VAR}` reads it. */
27
27
  readonly env?: Readonly<Record<string, string>>;
28
+ /**
29
+ * Variables the foreign harness itself sets for its servers, read by
30
+ * `${VAR}` when neither the settings nor the environment set them; see
31
+ * {@link harnessVariables}.
32
+ */
33
+ readonly provided?: Readonly<Record<string, string>>;
28
34
  }
35
+ /**
36
+ * The variables a harness provides to its plugins' MCP servers. Codex sets
37
+ * `CODEX_HOME` (its configuration directory) and, for plugin servers,
38
+ * `CODEX_MCP_NODE_PATH`, the Node.js it bundles (the openai-bundled plugins
39
+ * start their servers as `exec "$CODEX_MCP_NODE_PATH" ./server.mjs`). DSH
40
+ * provides the Node.js running it instead. They reach a server only through
41
+ * its configuration (`env_vars`, `env`, `${VAR}` in its command or arguments).
42
+ */
43
+ export declare function harnessVariables(plugin: Pick<ForeignPlugin, 'source'>): Readonly<Record<string, string>>;
29
44
  /**
30
45
  * The server name the foreign harness would use, before DSH length limits:
31
46
  * Claude Code scopes a plugin's servers as `plugin_<plugin>_<server>` and
@@ -49,7 +64,13 @@ export declare function projectRootOf(plugin: {
49
64
  /**
50
65
  * Expand `${CLAUDE_PLUGIN_ROOT}`, `${CLAUDE_PLUGIN_DATA}`, `${PLUGIN_ROOT}`,
51
66
  * `${PLUGIN_DATA}`, `${VAR}` and `${VAR:-default}` the way Claude Code expands
52
- * `.mcp.json`. Unknown variables without a default expand to empty text.
67
+ * `.mcp.json`; then what the harness provides ({@link McpVariables.provided}).
68
+ * Unknown variables without a default expand to empty text; a stdio server
69
+ * whose command or arguments need one does not start (`missingVariables`).
70
+ * The value goes in as plain text, as in Claude Code: expanded into an
71
+ * explicit `sh -c '… ${VAR} …'` argument it becomes part of that script. The
72
+ * values are the plugin author's and the user's own environment, so this
73
+ * keeps the original harness's meaning instead of quoting them.
53
74
  */
54
75
  export declare function expandVariables(value: string, vars: McpVariables, env?: NodeJS.ProcessEnv): string;
55
76
  /** Build the official mcp-client config for one component. */
@@ -59,6 +80,16 @@ export interface RemoteMcpHost {
59
80
  readonly auth: McpAuthStore;
60
81
  onState(server: RemoteMcp, state: RemoteMcpState): void;
61
82
  }
83
+ /**
84
+ * Whether `mountMcp` serves a server through the capability catalog: with the
85
+ * catalog composed, a stdio server is listed in its compact index and started
86
+ * on demand instead of putting every tool schema in every request. Remote
87
+ * servers keep the direct path, which adds OAuth; `options.catalog: false`
88
+ * (a session's own server) keeps it direct too.
89
+ */
90
+ export declare function servedByCatalog(ctx: object, component: McpComponent, options?: {
91
+ readonly catalog?: boolean;
92
+ }): boolean;
62
93
  /**
63
94
  * Mount one MCP server and wait until it is connected and its tools are
64
95
  * registered, so the first model request already sees them. A stdio server
@@ -69,7 +100,14 @@ export interface RemoteMcpHost {
69
100
  export declare function mountMcp(ctx: Context, component: McpComponent, serverName: string, vars: McpVariables, remoteHost: RemoteMcpHost, options?: {
70
101
  readonly catalog?: boolean;
71
102
  }): Promise<McpMount>;
72
- /** A DSH-safe server name (`[A-Za-z0-9_-]{1,32}`), stable for the same input. */
103
+ /**
104
+ * A DSH-safe server name (`[A-Za-z0-9_-]{1,32}`), stable for the same input.
105
+ * It never holds `__` nor starts or ends with `_`: a model-facing tool name
106
+ * `mcp__<server>__<tool>` then names one server only (with servers `app` and
107
+ * `app__reports`, `mcp__app__reports__x` would name either). A name that had
108
+ * `__` is collapsed to single `_` and keeps a hash of the original, so it
109
+ * stays apart from a server that was named that way to begin with.
110
+ */
73
111
  export declare function mcpServerName(name: string): string;
74
112
  /** The per-plugin data directory under a profile-local root. */
75
113
  export declare function pluginDataDir(dataRoot: string, pluginId: string): string;
package/lib/mcp/mount.js CHANGED
@@ -9,17 +9,22 @@
9
9
  * @module @kirkchinese/harness-forge
10
10
  */
11
11
  import { existsSync, statSync } from 'node:fs';
12
- import { delimiter, isAbsolute, join, resolve } from 'node:path';
13
- import { shortHash } from '@kirkchinese/harness-forge-core';
12
+ import { delimiter, join, resolve } from 'node:path';
13
+ import { codexHome, contentPath, LEADS_TO_SHARE, shortHash, stripAround } from '@kirkchinese/harness-forge-core';
14
14
  import { RemoteMcp } from './remote.js';
15
15
  import { composedCatalog, mountInCatalog } from './catalog.js';
16
+ import { DEFAULT_TOOL_CALL_TIMEOUT_MS } from './policy.js';
16
17
  /** Resolve a program the way a spawned process would find it. */
17
18
  export function findProgram(program, cwd, env = process.env) {
18
19
  const extensions = process.platform === 'win32'
19
20
  ? ['', ...(env['PATHEXT'] ?? '.COM;.EXE;.BAT;.CMD').split(';').filter(extension => extension.length > 0)]
20
21
  : [''];
21
- const candidates = /[\\/]/u.test(program)
22
- ? [isAbsolute(program) ? program : resolve(cwd, program)]
22
+ // A program path the configuration names is checked against the folder it runs in (see `contentPath`).
23
+ const named = /[\\/]/u.test(program) ? contentPath(program, cwd) : undefined;
24
+ if (/[\\/]/u.test(program) && named === undefined)
25
+ return undefined;
26
+ const candidates = named !== undefined
27
+ ? [named]
23
28
  : (env['PATH'] ?? env['Path'] ?? '').split(delimiter).filter(entry => entry.length > 0).map(entry => join(entry, program));
24
29
  for (const candidate of candidates) {
25
30
  for (const extension of extensions) {
@@ -40,8 +45,19 @@ export class UnsupportedMcpTransportError extends Error {
40
45
  this.name = 'UnsupportedMcpTransportError';
41
46
  }
42
47
  }
43
- /** How long a server may take to connect and list its tools. */
48
+ /** How long a server may take to connect and list its tools when its configuration does not say. */
44
49
  const READY_TIMEOUT_MS = 120_000;
50
+ /**
51
+ * The variables a harness provides to its plugins' MCP servers. Codex sets
52
+ * `CODEX_HOME` (its configuration directory) and, for plugin servers,
53
+ * `CODEX_MCP_NODE_PATH`, the Node.js it bundles (the openai-bundled plugins
54
+ * start their servers as `exec "$CODEX_MCP_NODE_PATH" ./server.mjs`). DSH
55
+ * provides the Node.js running it instead. They reach a server only through
56
+ * its configuration (`env_vars`, `env`, `${VAR}` in its command or arguments).
57
+ */
58
+ export function harnessVariables(plugin) {
59
+ return plugin.source === 'codex' ? { CODEX_HOME: codexHome(), CODEX_MCP_NODE_PATH: process.execPath } : {};
60
+ }
45
61
  /**
46
62
  * The server name the foreign harness would use, before DSH length limits:
47
63
  * Claude Code scopes a plugin's servers as `plugin_<plugin>_<server>` and
@@ -70,17 +86,42 @@ export function projectRootOf(plugin) {
70
86
  /**
71
87
  * Expand `${CLAUDE_PLUGIN_ROOT}`, `${CLAUDE_PLUGIN_DATA}`, `${PLUGIN_ROOT}`,
72
88
  * `${PLUGIN_DATA}`, `${VAR}` and `${VAR:-default}` the way Claude Code expands
73
- * `.mcp.json`. Unknown variables without a default expand to empty text.
89
+ * `.mcp.json`; then what the harness provides ({@link McpVariables.provided}).
90
+ * Unknown variables without a default expand to empty text; a stdio server
91
+ * whose command or arguments need one does not start (`missingVariables`).
92
+ * The value goes in as plain text, as in Claude Code: expanded into an
93
+ * explicit `sh -c '… ${VAR} …'` argument it becomes part of that script. The
94
+ * values are the plugin author's and the user's own environment, so this
95
+ * keeps the original harness's meaning instead of quoting them.
74
96
  */
75
97
  export function expandVariables(value, vars, env = process.env) {
76
- return value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}/gu, (_match, name, fallback) => {
98
+ const expand = (name, fallback) => {
77
99
  if (name === 'CLAUDE_PLUGIN_ROOT' || name === 'PLUGIN_ROOT')
78
100
  return vars.pluginRoot;
79
101
  if (name === 'CLAUDE_PLUGIN_DATA' || name === 'PLUGIN_DATA')
80
102
  return vars.dataDir;
81
- const resolved = vars.env?.[name] ?? env[name];
82
- return resolved !== undefined && resolved.length > 0 ? resolved : fallback ?? '';
83
- });
103
+ const resolved = [vars.env?.[name], env[name], vars.provided?.[name]].find(value => value !== undefined && value.length > 0);
104
+ return resolved ?? fallback ?? '';
105
+ };
106
+ // A scan: `/\$\{(NAME)(?::-([^}]*))?\}/g` reads to the end from every unclosed `${NAME:-`, quadratic.
107
+ let out = '';
108
+ let index = 0;
109
+ let close = -1;
110
+ for (;;) {
111
+ const start = value.indexOf('${', index);
112
+ if (close < start + 2)
113
+ close = value.indexOf('}', start + 2);
114
+ if (start === -1 || close === -1)
115
+ return out + value.slice(index);
116
+ const match = /^([A-Za-z_][A-Za-z0-9_]*)(?::-(.*))?$/su.exec(value.slice(start + 2, close));
117
+ if (match === null) {
118
+ out += value.slice(index, start + 2);
119
+ index = start + 2;
120
+ continue;
121
+ }
122
+ out += value.slice(index, start) + expand(match[1] ?? '', match[2]);
123
+ index = close + 1;
124
+ }
84
125
  }
85
126
  /** Build the official mcp-client config for one component. */
86
127
  export function mcpClientConfig(component, serverName, vars) {
@@ -89,6 +130,11 @@ export function mcpClientConfig(component, serverName, vars) {
89
130
  if (component.transport === 'stdio') {
90
131
  if (component.command === undefined)
91
132
  throw new Error(`MCP server "${component.name}" has no command`);
133
+ const env = expandRecord(component.env);
134
+ const missing = missingVariables(component, env, vars);
135
+ if (missing.length > 0) {
136
+ throw new Error(`MCP server "${component.name}" needs ${missing.join(', ')}, which DSH does not provide; set ${missing.length > 1 ? 'them' : 'it'} in the environment DSH starts in`);
137
+ }
92
138
  const command = resolveCommand(expand(component.command), vars.pluginRoot);
93
139
  return {
94
140
  serverName,
@@ -97,15 +143,16 @@ export function mcpClientConfig(component, serverName, vars) {
97
143
  args: (component.args ?? []).map(expand),
98
144
  env: {
99
145
  ...vars.env,
100
- ...expandRecord(component.env),
146
+ ...env,
101
147
  CLAUDE_PLUGIN_ROOT: vars.pluginRoot,
102
148
  CLAUDE_PLUGIN_DATA: vars.dataDir,
103
149
  PLUGIN_ROOT: vars.pluginRoot,
104
150
  PLUGIN_DATA: vars.dataDir,
105
151
  },
106
- cwd: component.cwd === undefined ? vars.pluginRoot : resolvePath(expand(component.cwd), vars.pluginRoot),
152
+ cwd: component.cwd === undefined ? vars.pluginRoot : workingDirectory(component, expand(component.cwd), vars.pluginRoot),
107
153
  failOnStartupError: true,
108
- toolCallTimeoutMs: 600_000,
154
+ toolCallTimeoutMs: component.toolTimeoutMs ?? DEFAULT_TOOL_CALL_TIMEOUT_MS,
155
+ ...(component.startupTimeoutMs !== undefined ? { startupTimeoutMs: component.startupTimeoutMs } : {}),
109
156
  };
110
157
  }
111
158
  if (component.transport === 'streamable-http') {
@@ -117,11 +164,49 @@ export function mcpClientConfig(component, serverName, vars) {
117
164
  url: expand(component.url),
118
165
  headers: expandRecord(component.headers),
119
166
  failOnStartupError: true,
120
- toolCallTimeoutMs: 600_000,
167
+ toolCallTimeoutMs: component.toolTimeoutMs ?? DEFAULT_TOOL_CALL_TIMEOUT_MS,
168
+ ...(component.startupTimeoutMs !== undefined ? { startupTimeoutMs: component.startupTimeoutMs } : {}),
121
169
  };
122
170
  }
123
171
  throw new UnsupportedMcpTransportError(component.transport);
124
172
  }
173
+ /**
174
+ * The variables a stdio server's command or arguments reference that would
175
+ * be empty: a `${VAR}` without a default that nothing sets, and a shell
176
+ * `$VAR` the server's `env` passes through (`env_vars`) but nothing sets.
177
+ * Started anyway, such a server runs an empty program
178
+ * (`exec "$CODEX_MCP_NODE_PATH"` fails with `exec: : Permission denied`).
179
+ * A shell variable the server does not declare may be the script's own, so
180
+ * it is left alone.
181
+ */
182
+ function missingVariables(component, env, vars) {
183
+ const missing = new Set();
184
+ const declared = component.env ?? {};
185
+ for (const text of [component.command ?? '', ...(component.args ?? [])]) {
186
+ for (const match of text.matchAll(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/gu)) {
187
+ const name = match[1] ?? '';
188
+ if (expandVariables(match[0], vars) === '')
189
+ missing.add(name);
190
+ }
191
+ for (const match of text.matchAll(/\$([A-Za-z_][A-Za-z0-9_]*)/gu)) {
192
+ const name = match[1] ?? '';
193
+ const passed = declared[name];
194
+ if (passed !== undefined && /^\$\{[A-Za-z_][A-Za-z0-9_]*\}$/u.test(passed) && env[name] === '')
195
+ missing.add(name);
196
+ }
197
+ }
198
+ return [...missing];
199
+ }
200
+ /**
201
+ * Whether `mountMcp` serves a server through the capability catalog: with the
202
+ * catalog composed, a stdio server is listed in its compact index and started
203
+ * on demand instead of putting every tool schema in every request. Remote
204
+ * servers keep the direct path, which adds OAuth; `options.catalog: false`
205
+ * (a session's own server) keeps it direct too.
206
+ */
207
+ export function servedByCatalog(ctx, component, options = {}) {
208
+ return options.catalog !== false && component.transport === 'stdio' && composedCatalog(ctx) !== undefined;
209
+ }
125
210
  /**
126
211
  * Mount one MCP server and wait until it is connected and its tools are
127
212
  * registered, so the first model request already sees them. A stdio server
@@ -130,18 +215,15 @@ export function mcpClientConfig(component, serverName, vars) {
130
215
  * that state.
131
216
  */
132
217
  export async function mountMcp(ctx, component, serverName, vars, remoteHost, options = {}) {
133
- // With the capability catalog composed, a stdio server is listed in its
134
- // compact index and started on demand instead of putting every tool schema
135
- // in every request. Remote servers keep the direct path, which adds OAuth.
136
- const catalog = options.catalog === false ? undefined : composedCatalog(ctx);
137
- if (catalog !== undefined && component.transport === 'stdio') {
218
+ const catalog = servedByCatalog(ctx, component, options) ? composedCatalog(ctx) : undefined;
219
+ if (catalog !== undefined) {
138
220
  const config = mcpClientConfig(component, serverName, vars);
139
221
  const program = String(config['command']);
140
222
  const resolved = findProgram(program, String(config['cwd']));
141
223
  if (resolved === undefined) {
142
224
  throw new Error(`MCP server "${component.name}" needs the program "${program}", which is not installed or not on PATH`);
143
225
  }
144
- return { serverName, catalog: true, dispose: await mountInCatalog(ctx, catalog, component, serverName, config, program, resolved, READY_TIMEOUT_MS) };
226
+ return { serverName, catalog: true, dispose: await mountInCatalog(ctx, catalog, component, serverName, config, program, resolved, component.startupTimeoutMs ?? READY_TIMEOUT_MS) };
145
227
  }
146
228
  if (component.transport === 'streamable-http' || component.transport === 'sse') {
147
229
  if (component.url === undefined)
@@ -167,7 +249,8 @@ export async function mountMcp(ctx, component, serverName, vars, remoteHost, opt
167
249
  const module = await import('@deepseek-ai/dsh-mcp-client');
168
250
  const fiber = ctx.plugin(module, config);
169
251
  try {
170
- await withTimeout(fiber, `MCP server "${component.name}" did not become ready within ${READY_TIMEOUT_MS / 1000}s`);
252
+ const readyMs = component.startupTimeoutMs ?? READY_TIMEOUT_MS;
253
+ await withTimeout(fiber, readyMs, `MCP server "${component.name}" did not become ready within ${readyMs / 1000}s`);
171
254
  }
172
255
  catch (error) {
173
256
  await fiber.dispose();
@@ -175,14 +258,27 @@ export async function mountMcp(ctx, component, serverName, vars, remoteHost, opt
175
258
  }
176
259
  return { serverName, dispose: async () => { await fiber.dispose(); } };
177
260
  }
178
- /** A DSH-safe server name (`[A-Za-z0-9_-]{1,32}`), stable for the same input. */
261
+ /** The longest server name DSH's MCP client accepts. */
262
+ const MAX_SERVER_NAME_LENGTH = 32;
263
+ /** Hex characters of the hash that keeps a shortened or collapsed server name apart from the others. */
264
+ const SERVER_NAME_HASH_LENGTH = 8;
265
+ /** Characters kept before that hash: the name, `_` and the hash fit {@link MAX_SERVER_NAME_LENGTH}. */
266
+ const SERVER_NAME_KEPT_LENGTH = MAX_SERVER_NAME_LENGTH - SERVER_NAME_HASH_LENGTH - 1;
267
+ /**
268
+ * A DSH-safe server name (`[A-Za-z0-9_-]{1,32}`), stable for the same input.
269
+ * It never holds `__` nor starts or ends with `_`: a model-facing tool name
270
+ * `mcp__<server>__<tool>` then names one server only (with servers `app` and
271
+ * `app__reports`, `mcp__app__reports__x` would name either). A name that had
272
+ * `__` is collapsed to single `_` and keeps a hash of the original, so it
273
+ * stays apart from a server that was named that way to begin with.
274
+ */
179
275
  export function mcpServerName(name) {
180
- const base = name.replace(/[^A-Za-z0-9_-]+/gu, '_').replace(/^_+|_+$/gu, '');
181
- if (base.length > 0 && base.length <= 32)
276
+ const base = stripAround(name.replace(/[^A-Za-z0-9_-]+/gu, '_'), '_');
277
+ const collapsed = base.replace(/_{2,}/gu, '_');
278
+ if (collapsed === base && base.length > 0 && base.length <= MAX_SERVER_NAME_LENGTH)
182
279
  return base;
183
- if (base.length > 32)
184
- return `${base.slice(0, 23).replace(/[_-]+$/u, '')}_${shortHash(base, 8)}`;
185
- return `mcp_${shortHash(name, 8)}`;
280
+ const kept = collapsed.slice(0, SERVER_NAME_KEPT_LENGTH).replace(/[_-]+$/u, '');
281
+ return `${kept.length > 0 ? kept : 'mcp'}_${shortHash(base.length > 0 ? base : name, SERVER_NAME_HASH_LENGTH)}`;
186
282
  }
187
283
  /** The per-plugin data directory under a profile-local root. */
188
284
  export function pluginDataDir(dataRoot, pluginId) {
@@ -193,8 +289,12 @@ function resolveCommand(command, root) {
193
289
  return resolve(root, command);
194
290
  return command;
195
291
  }
196
- function resolvePath(path, root) {
197
- return isAbsolute(path) ? path : resolve(root, path);
292
+ /** A server's configured working directory, resolved against its plugin; one on a network share the plugin is not on is refused. */
293
+ function workingDirectory(component, path, root) {
294
+ const resolved = contentPath(path, root);
295
+ if (resolved === undefined)
296
+ throw new Error(`MCP server "${component.name}" would run in ${path}, which ${LEADS_TO_SHARE}; Harness Forge does not start servers there`);
297
+ return resolved;
198
298
  }
199
299
  function rootCause(error) {
200
300
  let current = error;
@@ -206,11 +306,11 @@ function rootCause(error) {
206
306
  }
207
307
  return message;
208
308
  }
209
- function withTimeout(promise, message) {
309
+ function withTimeout(promise, ms, message) {
210
310
  return Promise.race([
211
311
  promise,
212
312
  new Promise((_resolve, reject) => {
213
- const timer = setTimeout(() => reject(new Error(message)), READY_TIMEOUT_MS);
313
+ const timer = setTimeout(() => reject(new Error(message)), ms);
214
314
  timer.unref?.();
215
315
  }),
216
316
  ]);
@@ -0,0 +1,42 @@
1
+ /**
2
+ * A server's own tool policy, from its configuration (Codex's
3
+ * `enabled_tools`, `disabled_tools`, `default_tools_approval_mode` and
4
+ * `tools.<tool>.approval_mode`): which of its tools may run and which ask the
5
+ * user first. `@deepseek-ai/dsh-mcp-client` registers every tool a server
6
+ * lists, so the MCP row enforces this when a call is made; the capability
7
+ * catalog and remote servers also leave filtered tools out of the list.
8
+ * @module @kirkchinese/harness-forge
9
+ */
10
+ import type { McpComponent } from '@kirkchinese/harness-forge-core';
11
+ /**
12
+ * How long one MCP tool call may run when the server's configuration does not
13
+ * say (Codex `tool_timeout_sec`): long-running tools (builds, test runs) are
14
+ * common, and the call can be cancelled like any other. Direct, catalog and
15
+ * remote mounts all use it.
16
+ */
17
+ export declare const DEFAULT_TOOL_CALL_TIMEOUT_MS = 600000;
18
+ /** Same public naming contract as dsh-mcp-client: `mcp__<server>__<tool>`, normalized with a hash when needed. */
19
+ export declare function publicToolName(serverName: string, rawName: string): string;
20
+ /** A mounted server's tool policy. */
21
+ export interface McpToolPolicy {
22
+ /** Whether the raw tool may run at all. */
23
+ runs(rawName: string): boolean;
24
+ /**
25
+ * The raw name of a configured tool of this server, from the public name
26
+ * `dsh-mcp-client` registers it under ({@link publicToolName}); undefined
27
+ * for a tool the configuration does not name.
28
+ */
29
+ rawName(publicName: string): string | undefined;
30
+ /**
31
+ * The decision for a call to one of this server's tools by its raw name
32
+ * (undefined for a tool the configuration does not name): `deny` for a
33
+ * filtered tool, `ask` for one that asks first, else undefined.
34
+ * @param shownName - the tool as the reason names it.
35
+ */
36
+ decide(rawName: string | undefined, shownName: string): {
37
+ readonly kind: 'deny' | 'ask';
38
+ readonly reason: string;
39
+ } | undefined;
40
+ }
41
+ /** The policy of one server, or undefined when its configuration sets none. */
42
+ export declare function mcpToolPolicy(component: McpComponent, serverName: string): McpToolPolicy | undefined;
@@ -0,0 +1,43 @@
1
+ import { createHash } from 'node:crypto';
2
+ /** The longest public tool name, as `dsh-mcp-client` names tools. */
3
+ const MAX_PUBLIC_NAME_LENGTH = 64;
4
+ /** Hex characters of the hash a normalized public tool name ends with, as `dsh-mcp-client` names tools. */
5
+ const HASH_LENGTH = 12;
6
+ /**
7
+ * How long one MCP tool call may run when the server's configuration does not
8
+ * say (Codex `tool_timeout_sec`): long-running tools (builds, test runs) are
9
+ * common, and the call can be cancelled like any other. Direct, catalog and
10
+ * remote mounts all use it.
11
+ */
12
+ export const DEFAULT_TOOL_CALL_TIMEOUT_MS = 600_000;
13
+ /** Same public naming contract as dsh-mcp-client: `mcp__<server>__<tool>`, normalized with a hash when needed. */
14
+ export function publicToolName(serverName, rawName) {
15
+ const joined = `mcp__${serverName}__${rawName}`;
16
+ const normalized = joined.replace(/[^A-Za-z0-9_-]/gu, '_');
17
+ if (normalized === joined && normalized.length <= MAX_PUBLIC_NAME_LENGTH)
18
+ return normalized;
19
+ const hash = createHash('sha256').update(`${serverName}\0${rawName}`).digest('hex').slice(0, HASH_LENGTH);
20
+ return `${normalized.slice(0, MAX_PUBLIC_NAME_LENGTH - HASH_LENGTH - 1)}_${hash}`;
21
+ }
22
+ /** The policy of one server, or undefined when its configuration sets none. */
23
+ export function mcpToolPolicy(component, serverName) {
24
+ const { enabledTools, disabledTools = [], toolApproval } = component;
25
+ if (enabledTools === undefined && disabledTools.length === 0 && toolApproval === undefined)
26
+ return undefined;
27
+ const runs = (rawName) => (enabledTools === undefined || enabledTools.includes(rawName)) && !disabledTools.includes(rawName);
28
+ const configured = new Set([...enabledTools ?? [], ...disabledTools, ...Object.keys(toolApproval?.tools ?? {})]);
29
+ const byPublicName = new Map([...configured].map(tool => [publicToolName(serverName, tool), tool]));
30
+ return {
31
+ runs,
32
+ rawName: publicName => byPublicName.get(publicName),
33
+ decide(raw, toolName) {
34
+ // A tool the configuration does not name is some other tool of the server: an allowlist refuses it.
35
+ if (raw === undefined ? enabledTools !== undefined : !runs(raw)) {
36
+ return { kind: 'deny', reason: `${toolName} is switched off by the configuration of MCP server "${component.name}" (enabled_tools / disabled_tools).` };
37
+ }
38
+ const own = raw !== undefined && toolApproval !== undefined && Object.hasOwn(toolApproval.tools, raw) ? toolApproval.tools[raw] : undefined;
39
+ const asks = own ?? toolApproval?.askByDefault === true;
40
+ return asks ? { kind: 'ask', reason: `MCP server "${component.name}" asks before running ${toolName} (approval_mode = "prompt").` } : undefined;
41
+ },
42
+ };
43
+ }
package/lib/mcp/remote.js CHANGED
@@ -9,15 +9,12 @@
9
9
  * `ctx.tools` accessor in a context that declared the dependency.
10
10
  * @module @kirkchinese/harness-forge
11
11
  */
12
- import { createHash } from 'node:crypto';
13
12
  import { createRequire } from 'node:module';
14
13
  import { Client, SSEClientTransport, StreamableHTTPClientTransport, UnauthorizedError } from '@modelcontextprotocol/client';
15
14
  import { createMcpToolDefinition } from '@deepseek-ai/dsh-mcp-client';
15
+ import { DEFAULT_TOOL_CALL_TIMEOUT_MS, mcpToolPolicy, publicToolName } from './policy.js';
16
16
  /** This package's version, as the MCP client names itself to a server. */
17
17
  const PACKAGE_VERSION = createRequire(import.meta.url)('../../package.json').version;
18
- const MAX_PUBLIC_NAME_LENGTH = 64;
19
- const HASH_LENGTH = 12;
20
- const CALL_TIMEOUT_MS = 600_000;
21
18
  /** One live remote server. */
22
19
  export class RemoteMcp {
23
20
  ctx;
@@ -86,7 +83,9 @@ export class RemoteMcp {
86
83
  try {
87
84
  await client.connect(transport);
88
85
  const response = await client.listTools(undefined, { cacheMode: 'refresh' });
89
- const tools = response.tools.map(tool => this.register(client, tool));
86
+ // Tools the server's configuration switches off are never registered.
87
+ const policy = mcpToolPolicy(this.component, this.serverName);
88
+ const tools = response.tools.filter(tool => policy?.runs(tool.name) ?? true).map(tool => this.register(client, tool));
90
89
  return this.settle({ kind: 'connected', tools });
91
90
  }
92
91
  catch (error) {
@@ -107,7 +106,7 @@ export class RemoteMcp {
107
106
  inputSchema: tool.inputSchema,
108
107
  outputSchema: tool.outputSchema,
109
108
  taskRequired: tool.execution?.taskSupport === 'required',
110
- call: (args, execution) => client.callTool({ name: tool.name, arguments: args }, { signal: execution.signal, timeout: CALL_TIMEOUT_MS, toolDefinition: tool }),
109
+ call: (args, execution) => client.callTool({ name: tool.name, arguments: args }, { signal: execution.signal, timeout: this.component.toolTimeoutMs ?? DEFAULT_TOOL_CALL_TIMEOUT_MS, toolDefinition: tool }),
111
110
  });
112
111
  this.registrations.push(toolCtx.tools.register(definition));
113
112
  return name;
@@ -122,15 +121,6 @@ export class RemoteMcp {
122
121
  return state;
123
122
  }
124
123
  }
125
- /** Same public naming contract as dsh-mcp-client. */
126
- function publicToolName(serverName, rawName) {
127
- const joined = `mcp__${serverName}__${rawName}`;
128
- const normalized = joined.replace(/[^A-Za-z0-9_-]/gu, '_');
129
- if (normalized === joined && normalized.length <= MAX_PUBLIC_NAME_LENGTH)
130
- return normalized;
131
- const hash = createHash('sha256').update(`${serverName}\0${rawName}`).digest('hex').slice(0, HASH_LENGTH);
132
- return `${normalized.slice(0, MAX_PUBLIC_NAME_LENGTH - HASH_LENGTH - 1)}_${hash}`;
133
- }
134
124
  function rootCause(error) {
135
125
  let current = error;
136
126
  let message = error instanceof Error ? error.message : String(error);