@kirkchinese/harness-forge 0.0.0-stage → 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.
Files changed (246) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +42 -2
  3. package/assets/icon.svg +12 -0
  4. package/cordis.patch.yml +28 -0
  5. package/lib/agents/presets.d.ts +91 -0
  6. package/lib/agents/presets.js +282 -0
  7. package/lib/agents/profiles.d.ts +58 -0
  8. package/lib/agents/profiles.js +278 -0
  9. package/lib/agents/row.d.ts +17 -0
  10. package/lib/agents/row.js +146 -0
  11. package/lib/client/styles.d.ts +8 -0
  12. package/lib/client/styles.js +89 -0
  13. package/lib/client/typert.d.ts +14 -0
  14. package/lib/client/typert.js +110 -0
  15. package/lib/client.js +22500 -0
  16. package/lib/commands/definition.d.ts +40 -0
  17. package/lib/commands/definition.js +113 -0
  18. package/lib/commands/output-styles.d.ts +42 -0
  19. package/lib/commands/output-styles.js +152 -0
  20. package/lib/commands/row.d.ts +9 -0
  21. package/lib/commands/row.js +157 -0
  22. package/lib/context/instructions.d.ts +32 -0
  23. package/lib/context/instructions.js +88 -0
  24. package/lib/context/row.d.ts +16 -0
  25. package/lib/context/row.js +17 -0
  26. package/lib/dsh/commands.d.ts +30 -0
  27. package/lib/dsh/commands.js +61 -0
  28. package/lib/dsh/host.d.ts +107 -0
  29. package/lib/dsh/host.js +214 -0
  30. package/lib/dsh/model-route.d.ts +21 -0
  31. package/lib/dsh/model-route.js +37 -0
  32. package/lib/dsh/session-records.d.ts +78 -0
  33. package/lib/dsh/session-records.js +36 -0
  34. package/lib/dsh/subagents.d.ts +46 -0
  35. package/lib/dsh/subagents.js +14 -0
  36. package/lib/forge/contract.d.ts +231 -0
  37. package/lib/forge/contract.js +43 -0
  38. package/lib/forge/ledger.d.ts +143 -0
  39. package/lib/forge/ledger.js +733 -0
  40. package/lib/forge/live-mounts.d.ts +45 -0
  41. package/lib/forge/live-mounts.js +78 -0
  42. package/lib/forge/marketplace-install.d.ts +3 -0
  43. package/lib/forge/marketplace-install.js +64 -0
  44. package/lib/forge/npm.d.ts +31 -0
  45. package/lib/forge/npm.js +60 -0
  46. package/lib/forge/projects.d.ts +94 -0
  47. package/lib/forge/projects.js +336 -0
  48. package/lib/forge/receipts.d.ts +5 -0
  49. package/lib/forge/receipts.js +31 -0
  50. package/lib/forge/row.d.ts +32 -0
  51. package/lib/forge/row.js +59 -0
  52. package/lib/forge/service.d.ts +105 -0
  53. package/lib/forge/service.js +274 -0
  54. package/lib/forge/settings.d.ts +41 -0
  55. package/lib/forge/settings.js +115 -0
  56. package/lib/forge/state.d.ts +69 -0
  57. package/lib/forge/state.js +150 -0
  58. package/lib/forge/trust.d.ts +48 -0
  59. package/lib/forge/trust.js +107 -0
  60. package/lib/forge/turns.d.ts +13 -0
  61. package/lib/forge/turns.js +56 -0
  62. package/lib/hooks/broker/engine.d.ts +112 -0
  63. package/lib/hooks/broker/engine.js +728 -0
  64. package/lib/hooks/broker/helpers.d.ts +10 -0
  65. package/lib/hooks/broker/helpers.js +22 -0
  66. package/lib/hooks/broker/lifecycle.d.ts +65 -0
  67. package/lib/hooks/broker/lifecycle.js +342 -0
  68. package/lib/hooks/broker/session-events.d.ts +22 -0
  69. package/lib/hooks/broker/session-events.js +196 -0
  70. package/lib/hooks/broker/tools.d.ts +52 -0
  71. package/lib/hooks/broker/tools.js +424 -0
  72. package/lib/hooks/broker/types.d.ts +262 -0
  73. package/lib/hooks/broker/types.js +1 -0
  74. package/lib/hooks/broker.d.ts +80 -0
  75. package/lib/hooks/broker.js +95 -0
  76. package/lib/hooks/codex-user.d.ts +5 -0
  77. package/lib/hooks/codex-user.js +109 -0
  78. package/lib/hooks/condition.d.ts +11 -0
  79. package/lib/hooks/condition.js +181 -0
  80. package/lib/hooks/config.d.ts +85 -0
  81. package/lib/hooks/config.js +150 -0
  82. package/lib/hooks/matcher.d.ts +20 -0
  83. package/lib/hooks/matcher.js +39 -0
  84. package/lib/hooks/notice.d.ts +17 -0
  85. package/lib/hooks/notice.js +39 -0
  86. package/lib/hooks/output.d.ts +56 -0
  87. package/lib/hooks/output.js +214 -0
  88. package/lib/hooks/permissions.d.ts +14 -0
  89. package/lib/hooks/permissions.js +109 -0
  90. package/lib/hooks/process.d.ts +47 -0
  91. package/lib/hooks/process.js +134 -0
  92. package/lib/hooks/row.d.ts +17 -0
  93. package/lib/hooks/row.js +94 -0
  94. package/lib/hooks/runner.d.ts +85 -0
  95. package/lib/hooks/runner.js +293 -0
  96. package/lib/hooks/shell-commands.d.ts +19 -0
  97. package/lib/hooks/shell-commands.js +177 -0
  98. package/lib/hooks/shell.d.ts +43 -0
  99. package/lib/hooks/shell.js +126 -0
  100. package/lib/hooks/transcript.d.ts +28 -0
  101. package/lib/hooks/transcript.js +141 -0
  102. package/lib/hooks/vocabulary.d.ts +57 -0
  103. package/lib/hooks/vocabulary.js +364 -0
  104. package/lib/index.d.ts +31 -0
  105. package/lib/index.js +287 -0
  106. package/lib/mcp/auth.d.ts +35 -0
  107. package/lib/mcp/auth.js +178 -0
  108. package/lib/mcp/catalog.d.ts +36 -0
  109. package/lib/mcp/catalog.js +61 -0
  110. package/lib/mcp/mount.d.ts +75 -0
  111. package/lib/mcp/mount.js +217 -0
  112. package/lib/mcp/remote.d.ts +45 -0
  113. package/lib/mcp/remote.js +143 -0
  114. package/lib/mcp/row.d.ts +9 -0
  115. package/lib/mcp/row.js +131 -0
  116. package/lib/mods/bundler.d.ts +38 -0
  117. package/lib/mods/bundler.js +157 -0
  118. package/lib/mods/chain.d.ts +103 -0
  119. package/lib/mods/chain.js +436 -0
  120. package/lib/mods/claude.d.ts +27 -0
  121. package/lib/mods/claude.js +56 -0
  122. package/lib/mods/engine.d.ts +160 -0
  123. package/lib/mods/engine.js +701 -0
  124. package/lib/mods/expect.d.ts +8 -0
  125. package/lib/mods/expect.js +248 -0
  126. package/lib/mods/host.d.ts +105 -0
  127. package/lib/mods/host.js +462 -0
  128. package/lib/mods/loader.d.ts +53 -0
  129. package/lib/mods/loader.js +227 -0
  130. package/lib/mods/ops.d.ts +13 -0
  131. package/lib/mods/ops.js +117 -0
  132. package/lib/mods/row.d.ts +9 -0
  133. package/lib/mods/row.js +77 -0
  134. package/lib/mods/runtime.d.ts +60 -0
  135. package/lib/mods/runtime.js +133 -0
  136. package/lib/mods/service/commands.d.ts +17 -0
  137. package/lib/mods/service/commands.js +121 -0
  138. package/lib/mods/service/drawings.d.ts +36 -0
  139. package/lib/mods/service/drawings.js +64 -0
  140. package/lib/mods/service/sessions.d.ts +63 -0
  141. package/lib/mods/service/sessions.js +345 -0
  142. package/lib/mods/service/tools.d.ts +32 -0
  143. package/lib/mods/service/tools.js +253 -0
  144. package/lib/mods/service/turns.d.ts +32 -0
  145. package/lib/mods/service/turns.js +161 -0
  146. package/lib/mods/service/types.d.ts +151 -0
  147. package/lib/mods/service/types.js +1 -0
  148. package/lib/mods/service.d.ts +72 -0
  149. package/lib/mods/service.js +104 -0
  150. package/lib/mods/surfaces.d.ts +93 -0
  151. package/lib/mods/surfaces.js +309 -0
  152. package/lib/mods/values.d.ts +30 -0
  153. package/lib/mods/values.js +95 -0
  154. package/lib/opencode/bun.d.ts +40 -0
  155. package/lib/opencode/bun.js +156 -0
  156. package/lib/opencode/convert.d.ts +53 -0
  157. package/lib/opencode/convert.js +255 -0
  158. package/lib/opencode/row.d.ts +9 -0
  159. package/lib/opencode/row.js +86 -0
  160. package/lib/opencode/runtime/core.d.ts +74 -0
  161. package/lib/opencode/runtime/core.js +249 -0
  162. package/lib/opencode/runtime/events.d.ts +80 -0
  163. package/lib/opencode/runtime/events.js +281 -0
  164. package/lib/opencode/runtime/mount.d.ts +27 -0
  165. package/lib/opencode/runtime/mount.js +283 -0
  166. package/lib/opencode/runtime/server.d.ts +27 -0
  167. package/lib/opencode/runtime/server.js +353 -0
  168. package/lib/opencode/runtime/types.d.ts +109 -0
  169. package/lib/opencode/runtime/types.js +1 -0
  170. package/lib/opencode/runtime.d.ts +55 -0
  171. package/lib/opencode/runtime.js +79 -0
  172. package/lib/porting/port-gap.d.ts +30 -0
  173. package/lib/porting/port-gap.js +122 -0
  174. package/lib/porting/port-sessions.d.ts +41 -0
  175. package/lib/porting/port-sessions.js +98 -0
  176. package/lib/porting/prompt.d.ts +23 -0
  177. package/lib/porting/prompt.js +49 -0
  178. package/lib/porting/row.d.ts +16 -0
  179. package/lib/porting/row.js +25 -0
  180. package/lib/porting/verify-port.d.ts +53 -0
  181. package/lib/porting/verify-port.js +104 -0
  182. package/lib/presets/fs-search.d.ts +25 -0
  183. package/lib/presets/fs-search.js +17 -0
  184. package/lib/presets/tool-filter.d.ts +35 -0
  185. package/lib/presets/tool-filter.js +91 -0
  186. package/lib/sessions/claude.d.ts +29 -0
  187. package/lib/sessions/claude.js +83 -0
  188. package/lib/sessions/codex.d.ts +30 -0
  189. package/lib/sessions/codex.js +303 -0
  190. package/lib/sessions/opencode.d.ts +32 -0
  191. package/lib/sessions/opencode.js +320 -0
  192. package/lib/sessions/row.d.ts +14 -0
  193. package/lib/sessions/row.js +35 -0
  194. package/lib/shared/invocation.d.ts +169 -0
  195. package/lib/shared/invocation.js +325 -0
  196. package/lib/shared/render.d.ts +72 -0
  197. package/lib/shared/render.js +588 -0
  198. package/lib/shared/util.d.ts +21 -0
  199. package/lib/shared/util.js +32 -0
  200. package/lib/skills/bundled.d.ts +3 -0
  201. package/lib/skills/bundled.js +42 -0
  202. package/lib/skills/provider.d.ts +72 -0
  203. package/lib/skills/provider.js +340 -0
  204. package/lib/skills/row.d.ts +22 -0
  205. package/lib/skills/row.js +204 -0
  206. package/lib/workbench/adapter-coverage.d.ts +47 -0
  207. package/lib/workbench/adapter-coverage.js +102 -0
  208. package/lib/workbench/model-tools.d.ts +10 -0
  209. package/lib/workbench/model-tools.js +122 -0
  210. package/lib/workbench/overview.d.ts +103 -0
  211. package/lib/workbench/overview.js +159 -0
  212. package/lib/workbench/remote.d.ts +118 -0
  213. package/lib/workbench/remote.js +422 -0
  214. package/lib/workbench/row.d.ts +15 -0
  215. package/lib/workbench/row.js +16 -0
  216. package/lib/workbench/settings.d.ts +15 -0
  217. package/lib/workbench/settings.js +56 -0
  218. package/lib/workbench/workbench.d.ts +100 -0
  219. package/lib/workbench/workbench.js +260 -0
  220. package/locale/agents/en.json +6 -0
  221. package/locale/agents/zh.json +6 -0
  222. package/locale/commands/en.json +6 -0
  223. package/locale/commands/zh.json +6 -0
  224. package/locale/context/en.json +6 -0
  225. package/locale/context/zh.json +6 -0
  226. package/locale/en.json +6 -0
  227. package/locale/hooks/en.json +6 -0
  228. package/locale/hooks/zh.json +6 -0
  229. package/locale/mcp/en.json +6 -0
  230. package/locale/mcp/zh.json +6 -0
  231. package/locale/mods/en.json +6 -0
  232. package/locale/mods/zh.json +6 -0
  233. package/locale/opencode/en.json +6 -0
  234. package/locale/opencode/zh.json +6 -0
  235. package/locale/porter/en.json +6 -0
  236. package/locale/porter/zh.json +6 -0
  237. package/locale/sessions/en.json +6 -0
  238. package/locale/sessions/zh.json +6 -0
  239. package/locale/skills/en.json +6 -0
  240. package/locale/skills/zh.json +6 -0
  241. package/locale/workbench/en.json +6 -0
  242. package/locale/workbench/zh.json +6 -0
  243. package/locale/zh.json +6 -0
  244. package/package.json +246 -3
  245. package/runtime/opencode-host.mjs +270 -0
  246. package/skills/harness-forge/SKILL.md +47 -0
@@ -0,0 +1,75 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import type { ForeignPlugin, McpComponent } from '@kirkchinese/harness-forge-core';
3
+ import type { McpAuthStore } from './auth.js';
4
+ import { RemoteMcp, type RemoteMcpState } from './remote.js';
5
+ /** One mounted MCP server. */
6
+ export interface McpMount {
7
+ readonly serverName: string;
8
+ /** Present for Streamable HTTP and SSE servers, which may need sign-in. */
9
+ readonly remote?: RemoteMcp;
10
+ /** True when the server is served through the capability catalog (`capability_call`, id `mcp:<server>/<tool>`). */
11
+ readonly catalog?: boolean;
12
+ readonly dispose: () => Promise<void>;
13
+ }
14
+ /** Resolve a program the way a spawned process would find it. */
15
+ export declare function findProgram(program: string, cwd: string, env?: NodeJS.ProcessEnv): string | undefined;
16
+ /** Raised when a foreign MCP transport has no implementation. */
17
+ export declare class UnsupportedMcpTransportError extends Error {
18
+ readonly transport: string;
19
+ readonly code = "unsupported-transport";
20
+ constructor(transport: string);
21
+ }
22
+ /** Variables a plugin's MCP configuration may reference. */
23
+ export interface McpVariables {
24
+ readonly pluginRoot: string;
25
+ readonly dataDir: string;
26
+ /** The `env` of imported harness settings: servers inherit it, `${VAR}` reads it. */
27
+ readonly env?: Readonly<Record<string, string>>;
28
+ }
29
+ /**
30
+ * The server name the foreign harness would use, before DSH length limits:
31
+ * Claude Code scopes a plugin's servers as `plugin_<plugin>_<server>` and
32
+ * keeps user, project and local servers under their own names.
33
+ */
34
+ export declare function foreignServerName(plugin: Pick<ForeignPlugin, 'source' | 'name'> & {
35
+ readonly manifest?: Readonly<Record<string, unknown>>;
36
+ }, server: string): string;
37
+ /** A user's or project's own assets rather than a plugin. */
38
+ export declare function isOwnAssets(plugin: {
39
+ readonly manifest?: Readonly<Record<string, unknown>>;
40
+ }): boolean;
41
+ /** Whose templates a plugin's commands and skills are: the person's own, a project's, or an installed plugin's. */
42
+ export declare function templateScope(plugin: {
43
+ readonly manifest?: Readonly<Record<string, unknown>>;
44
+ }): 'user' | 'project' | 'plugin';
45
+ /** The project directory of a project's assets, else undefined. */
46
+ export declare function projectRootOf(plugin: {
47
+ readonly manifest?: Readonly<Record<string, unknown>>;
48
+ }): string | undefined;
49
+ /**
50
+ * Expand `${CLAUDE_PLUGIN_ROOT}`, `${CLAUDE_PLUGIN_DATA}`, `${PLUGIN_ROOT}`,
51
+ * `${PLUGIN_DATA}`, `${VAR}` and `${VAR:-default}` the way Claude Code expands
52
+ * `.mcp.json`. Unknown variables without a default expand to empty text.
53
+ */
54
+ export declare function expandVariables(value: string, vars: McpVariables, env?: NodeJS.ProcessEnv): string;
55
+ /** Build the official mcp-client config for one component. */
56
+ export declare function mcpClientConfig(component: McpComponent, serverName: string, vars: McpVariables): Record<string, unknown>;
57
+ /** What a remote mount needs beyond the component. */
58
+ export interface RemoteMcpHost {
59
+ readonly auth: McpAuthStore;
60
+ onState(server: RemoteMcp, state: RemoteMcpState): void;
61
+ }
62
+ /**
63
+ * Mount one MCP server and wait until it is connected and its tools are
64
+ * registered, so the first model request already sees them. A stdio server
65
+ * whose program is missing, or a server that cannot connect, fails the mount
66
+ * with that reason. A remote server that requires sign-in stays mounted in
67
+ * that state.
68
+ */
69
+ export declare function mountMcp(ctx: Context, component: McpComponent, serverName: string, vars: McpVariables, remoteHost: RemoteMcpHost, options?: {
70
+ readonly catalog?: boolean;
71
+ }): Promise<McpMount>;
72
+ /** A DSH-safe server name (`[A-Za-z0-9_-]{1,32}`), stable for the same input. */
73
+ export declare function mcpServerName(name: string): string;
74
+ /** The per-plugin data directory under a profile-local root. */
75
+ export declare function pluginDataDir(dataRoot: string, pluginId: string): string;
@@ -0,0 +1,217 @@
1
+ /**
2
+ * Dynamic MCP bridge. A stdio server mounts one official `mcp-client`
3
+ * instance; Streamable HTTP and SSE servers connect through `remote.ts`,
4
+ * which adds OAuth sign-in. Server names follow the foreign harness so the model-facing
5
+ * tool names are the ones the plugin's hooks, agents and prompts already use:
6
+ * Claude Code plugin servers are `plugin_<plugin>_<server>`
7
+ * (`mcp__plugin_<plugin>_<server>__<tool>`), Codex and portable servers keep
8
+ * their own name.
9
+ * @module @kirkchinese/harness-forge
10
+ */
11
+ import { existsSync, statSync } from 'node:fs';
12
+ import { delimiter, isAbsolute, join, resolve } from 'node:path';
13
+ import { shortHash } from '@kirkchinese/harness-forge-core';
14
+ import { RemoteMcp } from './remote.js';
15
+ import { composedCatalog, mountInCatalog } from './catalog.js';
16
+ /** Resolve a program the way a spawned process would find it. */
17
+ export function findProgram(program, cwd, env = process.env) {
18
+ const extensions = process.platform === 'win32'
19
+ ? ['', ...(env['PATHEXT'] ?? '.COM;.EXE;.BAT;.CMD').split(';').filter(extension => extension.length > 0)]
20
+ : [''];
21
+ const candidates = /[\\/]/u.test(program)
22
+ ? [isAbsolute(program) ? program : resolve(cwd, program)]
23
+ : (env['PATH'] ?? env['Path'] ?? '').split(delimiter).filter(entry => entry.length > 0).map(entry => join(entry, program));
24
+ for (const candidate of candidates) {
25
+ for (const extension of extensions) {
26
+ const path = `${candidate}${extension}`;
27
+ if (existsSync(path) && statSync(path).isFile())
28
+ return path;
29
+ }
30
+ }
31
+ return undefined;
32
+ }
33
+ /** Raised when a foreign MCP transport has no implementation. */
34
+ export class UnsupportedMcpTransportError extends Error {
35
+ transport;
36
+ code = 'unsupported-transport';
37
+ constructor(transport) {
38
+ super(`MCP transport "${transport}" is not supported`);
39
+ this.transport = transport;
40
+ this.name = 'UnsupportedMcpTransportError';
41
+ }
42
+ }
43
+ /** How long a server may take to connect and list its tools. */
44
+ const READY_TIMEOUT_MS = 120_000;
45
+ /**
46
+ * The server name the foreign harness would use, before DSH length limits:
47
+ * Claude Code scopes a plugin's servers as `plugin_<plugin>_<server>` and
48
+ * keeps user, project and local servers under their own names.
49
+ */
50
+ export function foreignServerName(plugin, server) {
51
+ if (plugin.source !== 'claude-code' || isOwnAssets(plugin))
52
+ return server;
53
+ return `plugin_${plugin.name}_${server}`;
54
+ }
55
+ /** A user's or project's own assets rather than a plugin. */
56
+ export function isOwnAssets(plugin) {
57
+ const scope = plugin.manifest?.['scope'];
58
+ return scope === 'user' || scope === 'project';
59
+ }
60
+ /** Whose templates a plugin's commands and skills are: the person's own, a project's, or an installed plugin's. */
61
+ export function templateScope(plugin) {
62
+ const scope = plugin.manifest?.['scope'];
63
+ return scope === 'user' || scope === 'project' ? scope : 'plugin';
64
+ }
65
+ /** The project directory of a project's assets, else undefined. */
66
+ export function projectRootOf(plugin) {
67
+ const root = plugin.manifest?.['projectRoot'];
68
+ return plugin.manifest?.['scope'] === 'project' && typeof root === 'string' ? root : undefined;
69
+ }
70
+ /**
71
+ * Expand `${CLAUDE_PLUGIN_ROOT}`, `${CLAUDE_PLUGIN_DATA}`, `${PLUGIN_ROOT}`,
72
+ * `${PLUGIN_DATA}`, `${VAR}` and `${VAR:-default}` the way Claude Code expands
73
+ * `.mcp.json`. Unknown variables without a default expand to empty text.
74
+ */
75
+ export function expandVariables(value, vars, env = process.env) {
76
+ return value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}/gu, (_match, name, fallback) => {
77
+ if (name === 'CLAUDE_PLUGIN_ROOT' || name === 'PLUGIN_ROOT')
78
+ return vars.pluginRoot;
79
+ if (name === 'CLAUDE_PLUGIN_DATA' || name === 'PLUGIN_DATA')
80
+ return vars.dataDir;
81
+ const resolved = vars.env?.[name] ?? env[name];
82
+ return resolved !== undefined && resolved.length > 0 ? resolved : fallback ?? '';
83
+ });
84
+ }
85
+ /** Build the official mcp-client config for one component. */
86
+ export function mcpClientConfig(component, serverName, vars) {
87
+ const expand = (value) => expandVariables(value, vars);
88
+ const expandRecord = (record) => Object.fromEntries(Object.entries(record ?? {}).map(([key, value]) => [key, expand(value)]));
89
+ if (component.transport === 'stdio') {
90
+ if (component.command === undefined)
91
+ throw new Error(`MCP server "${component.name}" has no command`);
92
+ const command = resolveCommand(expand(component.command), vars.pluginRoot);
93
+ return {
94
+ serverName,
95
+ transport: 'stdio',
96
+ command,
97
+ args: (component.args ?? []).map(expand),
98
+ env: {
99
+ ...vars.env,
100
+ ...expandRecord(component.env),
101
+ CLAUDE_PLUGIN_ROOT: vars.pluginRoot,
102
+ CLAUDE_PLUGIN_DATA: vars.dataDir,
103
+ PLUGIN_ROOT: vars.pluginRoot,
104
+ PLUGIN_DATA: vars.dataDir,
105
+ },
106
+ cwd: component.cwd === undefined ? vars.pluginRoot : resolvePath(expand(component.cwd), vars.pluginRoot),
107
+ failOnStartupError: true,
108
+ toolCallTimeoutMs: 600_000,
109
+ };
110
+ }
111
+ if (component.transport === 'streamable-http') {
112
+ if (component.url === undefined)
113
+ throw new Error(`MCP server "${component.name}" has no url`);
114
+ return {
115
+ serverName,
116
+ transport: 'streamable-http',
117
+ url: expand(component.url),
118
+ headers: expandRecord(component.headers),
119
+ failOnStartupError: true,
120
+ toolCallTimeoutMs: 600_000,
121
+ };
122
+ }
123
+ throw new UnsupportedMcpTransportError(component.transport);
124
+ }
125
+ /**
126
+ * Mount one MCP server and wait until it is connected and its tools are
127
+ * registered, so the first model request already sees them. A stdio server
128
+ * whose program is missing, or a server that cannot connect, fails the mount
129
+ * with that reason. A remote server that requires sign-in stays mounted in
130
+ * that state.
131
+ */
132
+ 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') {
138
+ const config = mcpClientConfig(component, serverName, vars);
139
+ const program = String(config['command']);
140
+ const resolved = findProgram(program, String(config['cwd']));
141
+ if (resolved === undefined) {
142
+ throw new Error(`MCP server "${component.name}" needs the program "${program}", which is not installed or not on PATH`);
143
+ }
144
+ return { serverName, catalog: true, dispose: await mountInCatalog(ctx, catalog, component, serverName, config, program, resolved, READY_TIMEOUT_MS) };
145
+ }
146
+ if (component.transport === 'streamable-http' || component.transport === 'sse') {
147
+ if (component.url === undefined)
148
+ throw new Error(`MCP server "${component.name}" has no url`);
149
+ const expand = (value) => expandVariables(value, vars);
150
+ const server = new RemoteMcp(ctx, {
151
+ ...component,
152
+ url: expand(component.url),
153
+ headers: Object.fromEntries(Object.entries(component.headers ?? {}).map(([key, value]) => [key, expand(value)])),
154
+ }, serverName, remoteHost.auth, state => remoteHost.onState(server, state));
155
+ const state = await server.start();
156
+ if (state.kind === 'failed') {
157
+ await server.dispose();
158
+ throw new Error(`MCP server "${component.name}" failed to connect: ${state.error}`);
159
+ }
160
+ return { serverName, remote: server, dispose: () => server.dispose() };
161
+ }
162
+ const config = mcpClientConfig(component, serverName, vars);
163
+ const program = String(config['command']);
164
+ if (findProgram(program, String(config['cwd'])) === undefined) {
165
+ throw new Error(`MCP server "${component.name}" needs the program "${program}", which is not installed or not on PATH`);
166
+ }
167
+ const module = await import('@deepseek-ai/dsh-mcp-client');
168
+ const fiber = ctx.plugin(module, config);
169
+ try {
170
+ await withTimeout(fiber, `MCP server "${component.name}" did not become ready within ${READY_TIMEOUT_MS / 1000}s`);
171
+ }
172
+ catch (error) {
173
+ await fiber.dispose();
174
+ throw new Error(`MCP server "${component.name}" failed to start: ${rootCause(error)}`);
175
+ }
176
+ return { serverName, dispose: async () => { await fiber.dispose(); } };
177
+ }
178
+ /** A DSH-safe server name (`[A-Za-z0-9_-]{1,32}`), stable for the same input. */
179
+ export function mcpServerName(name) {
180
+ const base = name.replace(/[^A-Za-z0-9_-]+/gu, '_').replace(/^_+|_+$/gu, '');
181
+ if (base.length > 0 && base.length <= 32)
182
+ return base;
183
+ if (base.length > 32)
184
+ return `${base.slice(0, 23).replace(/[_-]+$/u, '')}_${shortHash(base, 8)}`;
185
+ return `mcp_${shortHash(name, 8)}`;
186
+ }
187
+ /** The per-plugin data directory under a profile-local root. */
188
+ export function pluginDataDir(dataRoot, pluginId) {
189
+ return join(dataRoot, pluginId.replace(/[^A-Za-z0-9._-]+/gu, '-'));
190
+ }
191
+ function resolveCommand(command, root) {
192
+ if (command.startsWith('./') || command.startsWith('.\\'))
193
+ return resolve(root, command);
194
+ return command;
195
+ }
196
+ function resolvePath(path, root) {
197
+ return isAbsolute(path) ? path : resolve(root, path);
198
+ }
199
+ function rootCause(error) {
200
+ let current = error;
201
+ let message = error instanceof Error ? error.message : String(error);
202
+ while (current instanceof Error && current.cause !== undefined) {
203
+ current = current.cause;
204
+ if (current instanceof Error)
205
+ message = current.message;
206
+ }
207
+ return message;
208
+ }
209
+ function withTimeout(promise, message) {
210
+ return Promise.race([
211
+ promise,
212
+ new Promise((_resolve, reject) => {
213
+ const timer = setTimeout(() => reject(new Error(message)), READY_TIMEOUT_MS);
214
+ timer.unref?.();
215
+ }),
216
+ ]);
217
+ }
@@ -0,0 +1,45 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import type { McpComponent } from '@kirkchinese/harness-forge-core';
3
+ import type { McpAuthStore } from './auth.js';
4
+ /** Connection state reported to the service. */
5
+ export type RemoteMcpState = {
6
+ readonly kind: 'connected';
7
+ readonly tools: readonly string[];
8
+ } | {
9
+ readonly kind: 'sign-in-required';
10
+ readonly url: string;
11
+ } | {
12
+ readonly kind: 'failed';
13
+ readonly error: string;
14
+ };
15
+ /** One live remote server. */
16
+ export declare class RemoteMcp {
17
+ private readonly ctx;
18
+ private readonly component;
19
+ readonly serverName: string;
20
+ private readonly auth;
21
+ private readonly onState;
22
+ private client;
23
+ private transport;
24
+ private toolCtx;
25
+ private fiber;
26
+ private registrations;
27
+ private authorizationUrl;
28
+ private state;
29
+ private closed;
30
+ constructor(ctx: Context, component: McpComponent & {
31
+ readonly url: string;
32
+ }, serverName: string, auth: McpAuthStore, onState: (state: RemoteMcpState) => void);
33
+ /** Connect and register tools; resolves with the resulting state. */
34
+ start(): Promise<RemoteMcpState>;
35
+ /** Open the sign-in page, finish the OAuth exchange, then connect. */
36
+ signIn(): Promise<RemoteMcpState>;
37
+ get current(): RemoteMcpState;
38
+ /** Whether the server was disposed: it waits for nothing any more. */
39
+ get disposed(): boolean;
40
+ dispose(): Promise<void>;
41
+ private connect;
42
+ private register;
43
+ private unregister;
44
+ private settle;
45
+ }
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Remote MCP servers (Streamable HTTP and legacy SSE) with OAuth sign-in.
3
+ * The MCP SDK client connects; tools register through the official
4
+ * `createMcpToolDefinition`, so naming, schemas, task rejection and result
5
+ * projection match DSH's native MCP client. A server that requires sign-in
6
+ * stays mounted in the `sign-in required` state until the user signs in.
7
+ *
8
+ * The bridge runs inside `ctx.inject(['tools'])`: Cordis only permits the
9
+ * `ctx.tools` accessor in a context that declared the dependency.
10
+ * @module @kirkchinese/harness-forge
11
+ */
12
+ import { createHash } from 'node:crypto';
13
+ import { createRequire } from 'node:module';
14
+ import { Client, SSEClientTransport, StreamableHTTPClientTransport, UnauthorizedError } from '@modelcontextprotocol/client';
15
+ import { createMcpToolDefinition } from '@deepseek-ai/dsh-mcp-client';
16
+ /** This package's version, as the MCP client names itself to a server. */
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
+ /** One live remote server. */
22
+ export class RemoteMcp {
23
+ ctx;
24
+ component;
25
+ serverName;
26
+ auth;
27
+ onState;
28
+ client;
29
+ transport;
30
+ toolCtx;
31
+ fiber;
32
+ registrations = [];
33
+ authorizationUrl;
34
+ state = { kind: 'failed', error: 'not connected' };
35
+ closed = false;
36
+ constructor(ctx, component, serverName, auth, onState) {
37
+ this.ctx = ctx;
38
+ this.component = component;
39
+ this.serverName = serverName;
40
+ this.auth = auth;
41
+ this.onState = onState;
42
+ }
43
+ /** Connect and register tools; resolves with the resulting state. */
44
+ async start() {
45
+ this.toolCtx ??= await new Promise((resolve) => {
46
+ this.fiber = this.ctx.inject(['tools'], (toolCtx) => { resolve(toolCtx); });
47
+ });
48
+ await this.auth.prepare(this.component.url);
49
+ return this.connect();
50
+ }
51
+ /** Open the sign-in page, finish the OAuth exchange, then connect. */
52
+ async signIn() {
53
+ if (this.state.kind !== 'sign-in-required' || this.authorizationUrl === undefined || this.transport === undefined)
54
+ return this.state;
55
+ const params = await this.auth.signIn(this.component.url, this.authorizationUrl);
56
+ await this.transport.finishAuth(params);
57
+ return this.connect();
58
+ }
59
+ get current() {
60
+ return this.state;
61
+ }
62
+ /** Whether the server was disposed: it waits for nothing any more. */
63
+ get disposed() {
64
+ return this.closed;
65
+ }
66
+ async dispose() {
67
+ this.closed = true;
68
+ this.unregister();
69
+ await this.client?.close().catch(() => undefined);
70
+ await this.fiber?.dispose();
71
+ }
72
+ async connect() {
73
+ this.unregister();
74
+ await this.client?.close().catch(() => undefined);
75
+ const url = new URL(this.component.url);
76
+ const options = {
77
+ requestInit: { headers: { ...this.component.headers } },
78
+ authProvider: this.auth.provider(this.component.url, (authorizationUrl) => { this.authorizationUrl = authorizationUrl; }),
79
+ };
80
+ const transport = this.component.transport === 'sse'
81
+ ? new SSEClientTransport(url, options)
82
+ : new StreamableHTTPClientTransport(url, options);
83
+ const client = new Client({ name: 'harness-forge', version: PACKAGE_VERSION }, { capabilities: {}, versionNegotiation: { mode: 'auto' } });
84
+ this.transport = transport;
85
+ this.client = client;
86
+ try {
87
+ await client.connect(transport);
88
+ const response = await client.listTools(undefined, { cacheMode: 'refresh' });
89
+ const tools = response.tools.map(tool => this.register(client, tool));
90
+ return this.settle({ kind: 'connected', tools });
91
+ }
92
+ catch (error) {
93
+ if (error instanceof UnauthorizedError && this.authorizationUrl !== undefined) {
94
+ return this.settle({ kind: 'sign-in-required', url: this.authorizationUrl.href });
95
+ }
96
+ await client.close().catch(() => undefined);
97
+ return this.settle({ kind: 'failed', error: rootCause(error) });
98
+ }
99
+ }
100
+ register(client, tool) {
101
+ const toolCtx = this.toolCtx;
102
+ const name = publicToolName(this.serverName, tool.name);
103
+ const definition = createMcpToolDefinition(toolCtx, {
104
+ name,
105
+ rawName: tool.name,
106
+ description: tool.description ?? '',
107
+ inputSchema: tool.inputSchema,
108
+ outputSchema: tool.outputSchema,
109
+ 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 }),
111
+ });
112
+ this.registrations.push(toolCtx.tools.register(definition));
113
+ return name;
114
+ }
115
+ unregister() {
116
+ for (const dispose of this.registrations.splice(0))
117
+ dispose();
118
+ }
119
+ settle(state) {
120
+ this.state = state;
121
+ this.onState(state);
122
+ return state;
123
+ }
124
+ }
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
+ function rootCause(error) {
135
+ let current = error;
136
+ let message = error instanceof Error ? error.message : String(error);
137
+ while (current instanceof Error && current.cause !== undefined) {
138
+ current = current.cause;
139
+ if (current instanceof Error)
140
+ message = current.message;
141
+ }
142
+ return message;
143
+ }
@@ -0,0 +1,9 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import type { Disposer } from '../forge/contract.js';
3
+ import { type HarnessForge } from '../forge/service.js';
4
+ export declare const name = "harness-forge-mcp";
5
+ export declare const inject: string[];
6
+ /** The MCP row. */
7
+ export declare function apply(ctx: Context): void;
8
+ /** Start the MCP row on the shared service. Returns its teardown. */
9
+ export declare function startMcp(ctx: Context, forge: HarnessForge): Disposer;
package/lib/mcp/row.js ADDED
@@ -0,0 +1,131 @@
1
+ /**
2
+ * The MCP row: imported MCP servers, stdio through DSH's own MCP client (or
3
+ * the capability catalog when the profile composes it), Streamable HTTP and
4
+ * SSE with OAuth sign-in. Their tool calls are the components' evidence.
5
+ * @module @kirkchinese/harness-forge/mcp
6
+ */
7
+ import { join } from 'node:path';
8
+ import { HarnessError } from '@kirkchinese/harness-forge-core';
9
+ import { onDsh } from '../dsh/host.js';
10
+ import { FORGE_SERVICE } from '../forge/service.js';
11
+ import { McpAuthStore } from './auth.js';
12
+ import { CATALOG_SERVICES, calledTool } from './catalog.js';
13
+ import { foreignServerName, mcpServerName, mountMcp } from './mount.js';
14
+ import { messageOf } from '../shared/util.js';
15
+ import { mounted, Parts, rowEffect } from '../forge/row.js';
16
+ export const name = 'harness-forge-mcp';
17
+ export const inject = [FORGE_SERVICE];
18
+ /** The MCP row. */
19
+ export function apply(ctx) {
20
+ rowEffect(ctx, 'mcp', forge => startMcp(ctx, forge));
21
+ }
22
+ /** Start the MCP row on the shared service. Returns its teardown. */
23
+ export function startMcp(ctx, forge) {
24
+ const auth = new McpAuthStore(join(forge.dataRoot, 'mcp-auth'));
25
+ /**
26
+ * Remote servers that reported a state, by server object: the same name may
27
+ * be mounted process-wide and in several sessions' projects at once, each
28
+ * with its own sign-in state and component.
29
+ */
30
+ const remotes = new Map();
31
+ /** Each mounted server's tool-name prefix, with its component and session. */
32
+ const prefixes = new Set();
33
+ const remoteHost = (componentId, scope = {}) => ({
34
+ auth,
35
+ onState: (server, state) => {
36
+ remotes.set(server, { componentId, server, ...(scope.sessionId !== undefined ? { sessionId: scope.sessionId } : {}) });
37
+ if (state.kind === 'sign-in-required')
38
+ forge.observe(componentId, 'sign-in', false, `sign-in required: run /harness login ${server.serverName}`);
39
+ else
40
+ forge.clearObservation(componentId, 'sign-in');
41
+ },
42
+ });
43
+ /** Servers waiting for sign-in that a session sees (its own and process-wide ones); every one without a session. */
44
+ const waiting = (sessionId) => {
45
+ for (const server of [...remotes.keys()])
46
+ if (server.disposed)
47
+ remotes.delete(server);
48
+ return [...remotes.values()].filter(entry => entry.server.current.kind === 'sign-in-required'
49
+ && (sessionId === undefined || entry.sessionId === undefined || entry.sessionId === sessionId));
50
+ };
51
+ const api = {
52
+ pendingSignIns: sessionId => [...new Set(waiting(sessionId).map(entry => entry.server.serverName))],
53
+ startSignIn: (serverName, sessionId) => {
54
+ const named = waiting(sessionId).filter(entry => entry.server.serverName === serverName);
55
+ // The session's own server first, then the process-wide one.
56
+ const remote = named.find(entry => sessionId !== undefined && entry.sessionId === sessionId)
57
+ ?? named.find(entry => entry.sessionId === undefined)
58
+ ?? named[0];
59
+ const state = remote?.server.current;
60
+ if (remote === undefined || state?.kind !== 'sign-in-required')
61
+ throw new Error(`MCP server "${serverName}" is not waiting for sign-in`);
62
+ void remote.server.signIn().then((next) => {
63
+ if (next.kind === 'failed')
64
+ forge.observe(remote.componentId, 'sign-in', false, `sign-in failed: ${next.error}`);
65
+ }, (error) => {
66
+ forge.observe(remote.componentId, 'sign-in', false, `sign-in failed: ${messageOf(error)}`);
67
+ });
68
+ return state.url;
69
+ },
70
+ remoteHost,
71
+ };
72
+ const mounter = {
73
+ mount: async ({ component, plugin, dataDir, scope }) => {
74
+ if (component.kind !== 'mcp')
75
+ throw new HarnessError('component-failed', `action expects MCP: ${component.id}`);
76
+ const serverName = mcpServerName(foreignServerName(plugin, component.name));
77
+ // A session's project servers stay in its own context; the catalog is process-wide.
78
+ const mount = await mountMcp(scope.ctx ?? ctx, component, serverName, { pluginRoot: plugin.root, dataDir, env: forge.settings.env() }, remoteHost(component.id, scope), { catalog: scope.sessionId === undefined });
79
+ const prefix = { prefix: `mcp__${serverName}__`, componentId: component.id, ...(scope.sessionId !== undefined ? { sessionId: scope.sessionId } : {}) };
80
+ prefixes.add(prefix);
81
+ return {
82
+ outcome: mounted(component, 'L1b', mount.catalog === true ? `${serverName} (capability catalog)` : serverName),
83
+ disposer: async () => {
84
+ prefixes.delete(prefix);
85
+ if (mount.remote !== undefined)
86
+ remotes.delete(mount.remote);
87
+ await mount.dispose();
88
+ },
89
+ };
90
+ },
91
+ };
92
+ const parts = new Parts(ctx, forge, 'mcp');
93
+ parts.add('tool evidence', () => onDsh(ctx, 'tools/post-execute', ((exec, result, next) => {
94
+ const toolName = calledTool(exec.name, exec.arguments);
95
+ const sessionId = exec.agent?.session?.header?.id;
96
+ const matching = [...prefixes].filter(entry => toolName.startsWith(entry.prefix));
97
+ // The calling session's own server first, then the process-wide one of that name.
98
+ const entry = matching.find(candidate => sessionId !== undefined && candidate.sessionId === sessionId)
99
+ ?? matching.find(candidate => candidate.sessionId === undefined);
100
+ if (entry !== undefined) {
101
+ forge.observe(entry.componentId, `tool:${toolName}`, !result.isError, result.isError ? result.error?.message ?? 'tool call failed' : `tool call returned${toolName !== exec.name ? ' through the capability catalog' : ''}`);
102
+ }
103
+ return next();
104
+ }), { owner: 'mcp' }));
105
+ let unregister = () => { };
106
+ let stopping = false;
107
+ parts.add('mcp mounter', () => {
108
+ unregister = forge.registerMounter('mcp', mounter);
109
+ return () => unregister();
110
+ });
111
+ // The capability catalog is optional and may come and go: its stdio servers move into it when it starts and
112
+ // mount directly again when it stops. Nothing waits for it.
113
+ parts.add('capability catalog', () => {
114
+ const fiber = ctx.inject([...CATALOG_SERVICES], (catalogCtx) => {
115
+ const remount = () => {
116
+ if (stopping)
117
+ return;
118
+ unregister();
119
+ unregister = forge.registerMounter('mcp', mounter);
120
+ };
121
+ remount();
122
+ catalogCtx.effect(() => remount, 'harness-forge.mcp-catalog');
123
+ });
124
+ return () => fiber.dispose();
125
+ });
126
+ parts.add('api', () => forge.provide('mcp', api));
127
+ parts.add('sign-in store', () => () => { auth.close(); });
128
+ // Torn down first: the catalog's going away with this row moves nothing.
129
+ parts.add('stopping', () => () => { stopping = true; });
130
+ return () => parts.dispose();
131
+ }
@@ -0,0 +1,38 @@
1
+ import type { Bundler } from './loader.js';
2
+ /** The rolldown version mods are bundled with. */
3
+ export declare const ROLLDOWN_VERSION = "1.3.2";
4
+ /** What decides which binding package fits this machine. */
5
+ export interface BundlerPlatform {
6
+ readonly os: NodeJS.Platform;
7
+ readonly arch: string;
8
+ /** Linux with musl libc (Alpine). */
9
+ readonly musl?: boolean;
10
+ }
11
+ /**
12
+ * The `@rolldown/binding-*` package rolldown loads on `platform`, as its
13
+ * binding loader picks it, among those rolldown publishes (its
14
+ * `optionalDependencies`). Undefined where rolldown has no native build.
15
+ */
16
+ export declare function rolldownBinding(platform: BundlerPlatform): string | undefined;
17
+ /** What {@link ensureBundler} does outside its own logic; tests replace it. */
18
+ export interface BundlerHost {
19
+ readonly platform: BundlerPlatform;
20
+ /** `npm install <specs>` into `prefix`. */
21
+ install(specs: readonly string[], prefix: string): Promise<void>;
22
+ /** Import the rolldown installed under `prefix`. */
23
+ load(prefix: string): Promise<Bundler>;
24
+ }
25
+ /** The packages to install: the pinned rolldown and its binding for `platform`. */
26
+ export declare function bundlerSpecs(platform: BundlerPlatform): string[];
27
+ /** Where the bundler is installed under a data root. */
28
+ export declare function bundlerPrefix(dataRoot: string): string;
29
+ /**
30
+ * The bundler, installing it under `dataRoot` on first use. One install runs
31
+ * at a time per data root; a failed one is forgotten, so the next mod tries
32
+ * again.
33
+ */
34
+ export declare function ensureBundler(dataRoot: string, host?: BundlerHost): Promise<Bundler>;
35
+ /** Whether {@link ensureBundler} would answer without installing anything. */
36
+ export declare function bundlerInstalled(dataRoot: string, host?: BundlerHost): boolean;
37
+ /** For tests: forget the bundlers loaded so far. */
38
+ export declare function resetBundlers(): void;