orchajs 0.23.11 → 0.24.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 (41) hide show
  1. package/README.md +94 -30
  2. package/dist/bin.js +11 -84
  3. package/dist/cli-agents-template.d.ts +1 -1
  4. package/dist/cli-agents-template.js +57 -19
  5. package/dist/cli.js +11 -11
  6. package/dist/compiler/build-project.js +23 -1
  7. package/dist/compiler/compile.js +131 -10
  8. package/dist/initialize-project.js +1 -1
  9. package/dist/orcha.js +11 -5
  10. package/dist/package-manager.d.ts +10 -0
  11. package/dist/package-manager.js +78 -0
  12. package/dist/project-loader.js +4 -1
  13. package/dist/providers/dependencies.d.ts +4 -0
  14. package/dist/providers/dependencies.js +125 -0
  15. package/dist/runtime/agent.d.ts +2 -0
  16. package/dist/runtime/agent.js +159 -7
  17. package/dist/runtime/create-orcha.js +6 -0
  18. package/dist/runtime/mcp/client.d.ts +31 -0
  19. package/dist/runtime/mcp/client.js +106 -0
  20. package/dist/runtime/mcp/http-client.d.ts +6 -0
  21. package/dist/runtime/mcp/http-client.js +87 -0
  22. package/dist/runtime/mcp/node-client.d.ts +3 -0
  23. package/dist/runtime/mcp/node-client.js +60 -0
  24. package/dist/runtime-entry.d.ts +1 -1
  25. package/dist/testing.js +1 -0
  26. package/dist/types.d.ts +33 -1
  27. package/dist-cjs/cli-agents-template.js +57 -19
  28. package/dist-cjs/compiler/build-project.js +27 -1
  29. package/dist-cjs/compiler/compile.js +148 -11
  30. package/dist-cjs/initialize-project.js +1 -1
  31. package/dist-cjs/orcha.js +11 -5
  32. package/dist-cjs/package-manager.js +109 -0
  33. package/dist-cjs/project-loader.js +10 -1
  34. package/dist-cjs/providers/dependencies.js +177 -0
  35. package/dist-cjs/runtime/agent.js +190 -7
  36. package/dist-cjs/runtime/create-orcha.js +6 -0
  37. package/dist-cjs/runtime/mcp/client.js +157 -0
  38. package/dist-cjs/runtime/mcp/http-client.js +134 -0
  39. package/dist-cjs/runtime/mcp/node-client.js +95 -0
  40. package/dist-cjs/testing.js +5 -1
  41. package/package.json +14 -3
@@ -6,21 +6,21 @@ files under \`.orcha/\`.
6
6
 
7
7
  ## Commands
8
8
 
9
- - \`orcha init\` creates the initial Orcha files without overwriting files.
10
- - \`orcha dev\` validates agent source and watches \`orcha/**\` for changes.
11
- - \`orcha playground\` opens the built-in local UI and hot reloads agent source.
12
- - \`orcha run <agent> --input "…"\` executes one registered agent.
13
- - \`orcha run <agent> --input-file request.json\` accepts structured input.
14
- - \`orcha run <agent> --session <id> --input "…"\` continues a session.
15
- - \`orcha run <agent> --session <id> --tool-results results.json\` submits
9
+ - \`orchajs init\` creates the initial Orcha files without overwriting files.
10
+ - \`orchajs dev\` validates agent source and watches \`orcha/**\` for changes.
11
+ - \`orchajs playground\` opens the built-in local UI and hot reloads agent source.
12
+ - \`orchajs run <agent> --input "…"\` executes one registered agent.
13
+ - \`orchajs run <agent> --input-file request.json\` accepts structured input.
14
+ - \`orchajs run <agent> --session <id> --input "…"\` continues a session.
15
+ - \`orchajs run <agent> --session <id> --tool-results results.json\` submits
16
16
  pending client-action results.
17
- - \`orcha test\` runs every enabled discovered agent test.
18
- - \`orcha test <agent>\` or \`orcha test <agent>/<case>\` narrows the run.
19
- - \`orcha migrate-storage --to sqlite|node-jsonl\` copies all session histories
17
+ - \`orchajs test\` runs every enabled discovered agent test.
18
+ - \`orchajs test <agent>\` or \`orchajs test <agent>/<case>\` narrows the run.
19
+ - \`orchajs migrate-storage --to sqlite|node-jsonl\` copies all session histories
20
20
  between local stores without deleting the source.
21
- - \`orcha export-session <agent> <sessionId> [--output <path>]\` exports one
21
+ - \`orchajs export-session <agent> <sessionId> [--output <path>]\` exports one
22
22
  session from the active store as JSONL.
23
- - \`orcha build\` creates the production Orcha bundle without calling models.
23
+ - \`orchajs build\` creates the production Orcha bundle without calling models.
24
24
  - Add \`--json\` to \`run\` and \`test\` for machine-readable output.
25
25
 
26
26
  \`run\`, \`test\`, and playground executions use real providers and require
@@ -30,7 +30,7 @@ under \`.orcha/sessions/<agentName>/\`; opt-in SQLite stores all agents in
30
30
 
31
31
  ## Production deployment
32
32
 
33
- \`orcha build\` writes \`.orcha/dist/bundle.js\` for bundler integrations and
33
+ \`orchajs build\` writes \`.orcha/dist/bundle.js\` for bundler integrations and
34
34
  \`.orcha/dist/manifest.json\` for unbundled production runtimes. If deployment
35
35
  uses plain \`tsc\`, \`serverless-plugin-typescript\`, or another packager that
36
36
  does not use \`orchajs/esbuild\`, explicitly include \`.orcha/dist/**\` in the
@@ -46,7 +46,7 @@ package:
46
46
  - ".orcha/dist/**"
47
47
  \`\`\`
48
48
 
49
- Do not assume that a successful \`orcha build\` means the generated files were
49
+ Do not assume that a successful \`orchajs build\` means the generated files were
50
50
  copied by a later packaging tool. Inspect the final ZIP or container image and
51
51
  confirm that \`.orcha/dist/manifest.json\` is present.
52
52
 
@@ -87,6 +87,8 @@ required.
87
87
  \`AMARSIA_API_URL\` and then \`https://api.amarsia.com\`.
88
88
  - \`actions\` (optional): overrides the native local-action runtime or configures
89
89
  its environment and sandbox settings.
90
+ - \`mcp.credentials\` (optional): runtime-only values used to resolve
91
+ \`\${NAME}\` placeholders in MCP headers or stdio environment values.
90
92
  - \`storage.strategy\` (optional): \`"node-jsonl"\` (default) or \`"sqlite"\`.
91
93
  The SQLite driver ships as an internal optional Orcha dependency.
92
94
  - \`storage.directory\` (optional): session directory relative to project
@@ -138,11 +140,47 @@ explicit service-account credentials are optional. Bedrock requires \`region\`;
138
140
  explicit AWS credentials are optional. Never place credentials in
139
141
  \`index.json\`, instructions, tests, session metadata, or committed files.
140
142
 
143
+ ## MCP connections
144
+
145
+ Assign named MCP folders in an agent or subagent registration:
146
+
147
+ \`\`\`ts
148
+ agents: {
149
+ supportBot: {
150
+ path: "./supportBot",
151
+ mcp: {
152
+ github: "./mcp/github",
153
+ },
154
+ },
155
+ }
156
+ \`\`\`
157
+
158
+ \`orcha/mcp/github/index.json\` configures either cross-platform Streamable
159
+ HTTP or Node-only stdio:
160
+
161
+ \`\`\`json
162
+ {
163
+ "transport": "streamable-http",
164
+ "url": "https://mcp.example.com",
165
+ "headers": {
166
+ "Authorization": "Bearer \${GITHUB_MCP_TOKEN}"
167
+ }
168
+ }
169
+ \`\`\`
170
+
171
+ All discovered tools are available as \`github__<toolName>\`. MCP output is
172
+ untrusted external data. Keep secrets out of JSON and provide placeholder
173
+ values through \`orcha.init().mcp.credentials\`; Node also reads
174
+ \`process.env\`.
175
+
141
176
  ## Agent folders
142
177
 
143
178
  \`\`\`text
144
179
  orcha/
145
180
  index.ts
181
+ mcp/
182
+ github/
183
+ index.json
146
184
  supportBot/
147
185
  index.json
148
186
  instructions.md
@@ -569,7 +607,7 @@ Test \`index.json\` fields:
569
607
  - \`expect.actions\` (optional): ordered expected calls. Each may assert
570
608
  \`arguments.equals\` or \`arguments.partial\`.
571
609
 
572
- The test folder name is the selector used by \`orcha test agent/testName\`.
610
+ The test folder name is the selector used by \`orchajs test agent/testName\`.
573
611
 
574
612
  ## Evaluations
575
613
 
@@ -597,7 +635,7 @@ metrics, and thresholds:
597
635
 
598
636
  \`execution.result\` does not wait for judges. Await
599
637
  \`execution.evaluations\` when results must finish before process exit.
600
- Evaluations always finish during \`orcha test\`; judge errors and missed
638
+ Evaluations always finish during \`orchajs test\`; judge errors and missed
601
639
  thresholds fail the test. Lifecycle events are \`evaluation.requested\`,
602
640
  \`evaluation.completed\`, and \`evaluation.failed\`.
603
641
 
@@ -1003,7 +1041,7 @@ number. A conversational \`resume(...content)\` starts a new run number.
1003
1041
  Concrete action arguments and outputs are validated against their schemas
1004
1042
  when the action is used.
1005
1043
 
1006
- \`orcha dev\` repeats validation when files change. \`orcha build\` performs
1044
+ \`orchajs dev\` repeats validation when files change. \`orchajs build\` performs
1007
1045
  offline production compilation. Neither command invokes a provider.
1008
1046
 
1009
1047
  ### Run lifecycle
@@ -1029,7 +1067,7 @@ offline production compilation. Neither command invokes a provider.
1029
1067
  The parent reports \`waiting_for_subagent\` until each synchronous child
1030
1068
  call returns.
1031
1069
  8. The model loop continues until final output, failure, a pause, or the
1032
- maximum of 10 action rounds.
1070
+ maximum of 20 action rounds.
1033
1071
  9. Usage is normalized and aggregated across every model call in the run.
1034
1072
  10. After \`run.completed\`, enabled evaluations start in the background.
1035
1073
  \`execution.result\` is already available; \`execution.evaluations\` waits
@@ -1082,7 +1120,7 @@ needed for faithful continuation but are omitted from evaluation transcripts.
1082
1120
  - Mock actions when tests must avoid side effects; document intentional live
1083
1121
  action coverage.
1084
1122
  - Do not commit \`.orcha/\`; it contains generated output and session data.
1085
- - Run \`orcha dev\` after filesystem changes and \`orcha test\` when behavior
1123
+ - Run \`orchajs dev\` after filesystem changes and \`orchajs test\` when behavior
1086
1124
  changes.
1087
1125
  - Do not weaken assertions to match incorrect behavior. Remove an assertion
1088
1126
  only when it is stricter than the documented agent contract.
package/dist/cli.js CHANGED
@@ -43,7 +43,7 @@ switch (command) {
43
43
  case "build": {
44
44
  const parsed = parseArguments(commandArguments, new Set(["--target"]), new Set());
45
45
  if (parsed.positionals.length > 0) {
46
- throw new Error("Usage: orcha build [--target node|browser|react-native]");
46
+ throw new Error("Usage: orchajs build [--target node|browser|react-native]");
47
47
  }
48
48
  const target = parseBuildTarget(parsed.values.get("--target"));
49
49
  loadProjectEnvironment(projectRoot);
@@ -58,12 +58,12 @@ switch (command) {
58
58
  printUsage();
59
59
  break;
60
60
  default:
61
- throw new Error(`Unknown command "${command}". Run "orcha --help".`);
61
+ throw new Error(`Unknown command "${command}". Run "orchajs --help".`);
62
62
  }
63
63
  async function watchProject(projectRoot, targets) {
64
64
  const registryDirectory = resolve(projectRoot, "orcha");
65
65
  if (!existsSync(registryDirectory)) {
66
- throw new Error('Missing "orcha/". Run "orcha init" first.');
66
+ throw new Error('Missing "orcha/". Run "orchajs init" first.');
67
67
  }
68
68
  loadProjectEnvironment(projectRoot);
69
69
  let validating = false;
@@ -117,7 +117,7 @@ async function runAgent(projectRoot, arguments_) {
117
117
  ]));
118
118
  const agentName = parsed.positionals[0];
119
119
  if (!agentName || parsed.positionals.length > 1) {
120
- throw new Error('Usage: orcha run <agent> (--input "…" | --input-file request.json) [--session <id>] [--json]');
120
+ throw new Error('Usage: orchajs run <agent> (--input "…" | --input-file request.json) [--session <id>] [--json]');
121
121
  }
122
122
  await loadProject(projectRoot);
123
123
  const agent = orcha[agentName];
@@ -164,7 +164,7 @@ async function runAgent(projectRoot, arguments_) {
164
164
  async function testAgents(projectRoot, arguments_) {
165
165
  const parsed = parseArguments(arguments_, new Set());
166
166
  if (parsed.positionals.length > 1) {
167
- throw new Error("Usage: orcha test [agent | agent/test] [--json]");
167
+ throw new Error("Usage: orchajs test [agent | agent/test] [--json]");
168
168
  }
169
169
  const selector = parsed.positionals[0];
170
170
  const [agent, test, extra] = selector?.split("/") ?? [];
@@ -207,7 +207,7 @@ async function testAgents(projectRoot, arguments_) {
207
207
  async function runPlayground(projectRoot, arguments_) {
208
208
  const parsed = parseArguments(arguments_, new Set(["--host", "--port"]), new Set(["--no-open"]));
209
209
  if (parsed.positionals.length > 0) {
210
- throw new Error("Usage: orcha playground [--host localhost] [--port 4310] [--no-open]");
210
+ throw new Error("Usage: orchajs playground [--host localhost] [--port 4310] [--no-open]");
211
211
  }
212
212
  const portValue = parsed.values.get("--port");
213
213
  const port = portValue ? Number.parseInt(portValue, 10) : 4310;
@@ -224,7 +224,7 @@ async function runPlayground(projectRoot, arguments_) {
224
224
  async function migrateStorage(projectRoot, arguments_) {
225
225
  const parsed = parseArguments(arguments_, new Set(["--to", "--agent"]), new Set());
226
226
  if (parsed.positionals.length > 0) {
227
- throw new Error("Usage: orcha migrate-storage --to <sqlite | node-jsonl> [--agent <name>]");
227
+ throw new Error("Usage: orchajs migrate-storage --to <sqlite | node-jsonl> [--agent <name>]");
228
228
  }
229
229
  const destinationStrategy = storageStrategy(parsed.values.get("--to"));
230
230
  const sourceStrategy = destinationStrategy === "sqlite" ? "node-jsonl" : "sqlite";
@@ -256,7 +256,7 @@ async function exportSession(projectRoot, arguments_) {
256
256
  const parsed = parseArguments(arguments_, new Set(["--output"]), new Set());
257
257
  const [agentName, sessionId] = parsed.positionals;
258
258
  if (!agentName || !sessionId || parsed.positionals.length !== 2) {
259
- throw new Error("Usage: orcha export-session <agent> <sessionId> [--output <path>]");
259
+ throw new Error("Usage: orchajs export-session <agent> <sessionId> [--output <path>]");
260
260
  }
261
261
  await loadProject(projectRoot);
262
262
  const context = getOrchaRuntimeContext(orcha);
@@ -298,7 +298,7 @@ function allAgentManifests(agents) {
298
298
  function parseDevTargets(arguments_) {
299
299
  const parsed = parseArguments(arguments_, new Set(["--target"]), new Set());
300
300
  if (parsed.positionals.length > 0) {
301
- throw new Error("Usage: orcha dev [--target node|browser|react-native|all]");
301
+ throw new Error("Usage: orchajs dev [--target node|browser|react-native|all]");
302
302
  }
303
303
  const target = parsed.values.get("--target") ?? "node";
304
304
  if (target === "all") {
@@ -555,12 +555,12 @@ async function sessionLogPath(projectRoot, agentName, sessionId) {
555
555
  }
556
556
  function assertNoArguments(arguments_, command) {
557
557
  if (arguments_.length > 0) {
558
- throw new Error(`Usage: orcha ${command}`);
558
+ throw new Error(`Usage: orchajs ${command}`);
559
559
  }
560
560
  }
561
561
  function printUsage() {
562
562
  console.log([
563
- "Usage: orcha <command>",
563
+ "Usage: orchajs <command>",
564
564
  "",
565
565
  "Commands:",
566
566
  " init Add Orcha to the current project",
@@ -7,6 +7,7 @@ import { orcha } from "../orcha.js";
7
7
  import { setRegistryCompiler } from "../runtime/compiler-hook.js";
8
8
  import { compileRegistry } from "./compile.js";
9
9
  import { builtInProviderCatalog, isBuiltInProvider, } from "../providers/catalog.js";
10
+ import { ensureCompiledMcpDependencies, ensureProviderDependencies, } from "../providers/dependencies.js";
10
11
  let registryImportSequence = 0;
11
12
  export async function buildProject(options = {}) {
12
13
  const projectRoot = resolve(options.projectRoot ?? process.cwd());
@@ -14,7 +15,7 @@ export async function buildProject(options = {}) {
14
15
  setRegistryCompiler((configuration, compilerProjectRoot) => compileRegistry(configuration.agents, resolve(compilerProjectRoot, "orcha"), configuration.actions?.runtime ?? "native", target));
15
16
  const registryPath = resolve(projectRoot, "orcha/index.ts");
16
17
  if (!existsSync(registryPath)) {
17
- throw new Error('Missing "orcha/index.ts". Run "orcha init" first.');
18
+ throw new Error('Missing "orcha/index.ts". Run "orchajs init" first.');
18
19
  }
19
20
  const temporaryDirectory = resolve(projectRoot, ".orcha/.build");
20
21
  const registryBundlePath = resolve(temporaryDirectory, "registry.mjs");
@@ -78,6 +79,12 @@ export async function buildProject(options = {}) {
78
79
  ])),
79
80
  ];
80
81
  const providerRuntimeSource = createProviderRuntimeSource(includedProviders, target);
82
+ await ensureProviderDependencies(includedProviders, projectRoot);
83
+ const hasMcp = allCompiledAgents(compiledBundle.agents).some((agent) => Object.keys(agent.mcpServers ?? {}).length > 0);
84
+ await ensureCompiledMcpDependencies(compiledBundle, projectRoot);
85
+ const mcpRuntimeSource = hasMcp
86
+ ? createMcpRuntimeSource(target)
87
+ : "";
81
88
  const needsNodeRequire = compiledBundle.actionRuntime === "sandbox" ||
82
89
  includedProviders.includes("vertexai") ||
83
90
  includedProviders.includes("bedrock");
@@ -89,6 +96,7 @@ export async function buildProject(options = {}) {
89
96
  nodeStorageExports,
90
97
  providerRuntimeSource,
91
98
  platformActionRuntimeSource,
99
+ mcpRuntimeSource,
92
100
  sandboxRuntimeSource,
93
101
  `const compiledBundle = ${JSON.stringify(compiledBundle)};`,
94
102
  "const generateProviderResponse = createProviderResponseGenerator(includedProviders);",
@@ -177,6 +185,20 @@ function createPlatformActionRuntimeSource(target) {
177
185
  "",
178
186
  ].join("\n");
179
187
  }
188
+ function createMcpRuntimeSource(target) {
189
+ const runtimeDirectory = dirname(fileURLToPath(import.meta.url));
190
+ const clientPath = resolve(runtimeDirectory, "../runtime/mcp/client.js").replaceAll("\\", "/");
191
+ const implementationPath = resolve(runtimeDirectory, target === "node"
192
+ ? "../runtime/mcp/node-client.js"
193
+ : "../runtime/mcp/http-client.js").replaceAll("\\", "/");
194
+ const factoryName = target === "node" ? "createNodeMcpClient" : "createHttpMcpClient";
195
+ return [
196
+ `import { setMcpClientFactory } from ${JSON.stringify(clientPath)};`,
197
+ `import { ${factoryName} } from ${JSON.stringify(implementationPath)};`,
198
+ `setMcpClientFactory(${factoryName});`,
199
+ "",
200
+ ].join("\n");
201
+ }
180
202
  function createNodeStorageExports() {
181
203
  const sourceRoot = dirname(fileURLToPath(import.meta.url));
182
204
  const jsonlPath = resolve(sourceRoot, "../storage/node-jsonl.js").replaceAll("\\", "/");
@@ -16,13 +16,14 @@ export function compileRegistry(registrations, registryRoot, actionRuntime = "na
16
16
  }
17
17
  const normalized = normalizeAgentRegistration(key, registration);
18
18
  const subagents = {};
19
- for (const [subagentKey, registeredPath] of Object.entries(normalized.subagents)) {
19
+ for (const [subagentKey, registration] of Object.entries(normalized.subagents)) {
20
20
  if (!subagentKey.trim()) {
21
21
  throw new Error(`Agent "${key}" has an empty subagent name.`);
22
22
  }
23
- subagents[subagentKey] = compileAgent(subagentKey, registeredPath, registryRoot, actionRuntime, target);
23
+ const subagent = normalizeSubagentRegistration(key, subagentKey, registration);
24
+ subagents[subagentKey] = compileAgent(subagentKey, subagent.path, subagent.mcp, registryRoot, actionRuntime, target);
24
25
  }
25
- const parent = compileAgent(key, normalized.path, registryRoot, actionRuntime, target);
26
+ const parent = compileAgent(key, normalized.path, normalized.mcp, registryRoot, actionRuntime, target);
26
27
  agents[key] = Object.freeze({
27
28
  ...parent,
28
29
  subagentPolicy: Object.keys(subagents).length > 0
@@ -48,7 +49,7 @@ function normalizeAgentRegistration(key, registration) {
48
49
  if (!registration.trim()) {
49
50
  throw new Error(`Agent "${key}" must register a folder path.`);
50
51
  }
51
- return { path: registration, subagents: {} };
52
+ return { path: registration, mcp: {}, subagents: {} };
52
53
  }
53
54
  if (!registration || typeof registration !== "object") {
54
55
  throw new Error(`Agent "${key}" must register a folder path.`);
@@ -60,19 +61,51 @@ function normalizeAgentRegistration(key, registration) {
60
61
  (!registration.subagents ||
61
62
  typeof registration.subagents !== "object" ||
62
63
  Array.isArray(registration.subagents))) {
63
- throw new Error(`Agent "${key}" subagents must be an object of folder paths.`);
64
+ throw new Error(`Agent "${key}" subagents must be an object of named registrations.`);
64
65
  }
65
- for (const [subagentKey, registeredPath] of Object.entries(registration.subagents ?? {})) {
66
- if (typeof registeredPath !== "string" || !registeredPath.trim()) {
67
- throw new Error(`Subagent "${key}/${subagentKey}" must register a folder path.`);
66
+ validateMcpRegistration(`Agent "${key}"`, registration.mcp);
67
+ return {
68
+ path: registration.path,
69
+ mcp: registration.mcp ?? {},
70
+ subagents: registration.subagents ?? {},
71
+ };
72
+ }
73
+ function normalizeSubagentRegistration(parentKey, key, registration) {
74
+ if (typeof registration === "string") {
75
+ if (!registration.trim()) {
76
+ throw new Error(`Subagent "${parentKey}/${key}" must register a folder path.`);
68
77
  }
78
+ return { path: registration, mcp: {} };
79
+ }
80
+ if (!registration ||
81
+ typeof registration !== "object" ||
82
+ typeof registration.path !== "string" ||
83
+ !registration.path.trim()) {
84
+ throw new Error(`Subagent "${parentKey}/${key}" must register a folder path.`);
69
85
  }
86
+ validateMcpRegistration(`Subagent "${parentKey}/${key}"`, registration.mcp);
70
87
  return {
71
88
  path: registration.path,
72
- subagents: registration.subagents ?? {},
89
+ mcp: registration.mcp ?? {},
73
90
  };
74
91
  }
75
- function compileAgent(key, registeredPath, registryRoot, actionRuntime, target) {
92
+ function validateMcpRegistration(owner, registration) {
93
+ if (registration !== undefined &&
94
+ (!registration ||
95
+ typeof registration !== "object" ||
96
+ Array.isArray(registration))) {
97
+ throw new Error(`${owner} mcp must be an object of named folder paths.`);
98
+ }
99
+ for (const [key, path] of Object.entries(registration ?? {})) {
100
+ if (!/^[a-zA-Z0-9_-]{1,32}$/.test(key)) {
101
+ throw new Error(`${owner} has invalid MCP name "${key}".`);
102
+ }
103
+ if (typeof path !== "string" || !path.trim()) {
104
+ throw new Error(`${owner} MCP "${key}" must register a folder path.`);
105
+ }
106
+ }
107
+ }
108
+ function compileAgent(key, registeredPath, mcpRegistration, registryRoot, actionRuntime, target) {
76
109
  const name = key;
77
110
  const sourceDirectory = resolve(registryRoot, registeredPath);
78
111
  const configPath = resolve(sourceDirectory, "index.json");
@@ -151,12 +184,100 @@ function compileAgent(key, registeredPath, registryRoot, actionRuntime, target)
151
184
  actions: compileActions(name, sourceDirectory, actionRuntime, target),
152
185
  skills: compileSkills(name, sourceDirectory),
153
186
  evaluations: compileEvaluations(name, sourceDirectory),
187
+ mcpServers: compileMcpServers(name, mcpRegistration, registryRoot, target),
154
188
  subagentPolicy: configuration.subagents
155
189
  ? Object.freeze({ ...configuration.subagents })
156
190
  : undefined,
157
191
  subagents: Object.freeze({}),
158
192
  });
159
193
  }
194
+ function compileMcpServers(agentName, registration, registryRoot, target) {
195
+ const servers = {};
196
+ for (const [key, registeredPath] of Object.entries(registration)) {
197
+ const directory = resolve(registryRoot, registeredPath);
198
+ const configurationPath = resolve(directory, "index.json");
199
+ let configuration;
200
+ try {
201
+ configuration = JSON.parse(readFileSync(configurationPath, "utf8"));
202
+ }
203
+ catch (error) {
204
+ throw new Error(`MCP server "${agentName}/${key}" is missing a valid index.json at ${configurationPath}.`, { cause: error });
205
+ }
206
+ validateMcpServerConfiguration(agentName, key, configuration, target);
207
+ servers[key] = Object.freeze({
208
+ ...configuration,
209
+ key,
210
+ directoryName: registeredPath,
211
+ });
212
+ }
213
+ return Object.freeze(servers);
214
+ }
215
+ function validateMcpServerConfiguration(agentName, key, configuration, target) {
216
+ const label = `MCP server "${agentName}/${key}"`;
217
+ if (!configuration ||
218
+ typeof configuration !== "object" ||
219
+ !["streamable-http", "stdio"].includes(configuration.transport)) {
220
+ throw new Error(`${label} transport must be "streamable-http" or "stdio".`);
221
+ }
222
+ if (configuration.transport === "streamable-http") {
223
+ let url;
224
+ try {
225
+ url = new URL(configuration.url);
226
+ }
227
+ catch {
228
+ throw new Error(`${label} requires a valid URL.`);
229
+ }
230
+ if (!["https:", "http:"].includes(url.protocol)) {
231
+ throw new Error(`${label} URL must use HTTP or HTTPS.`);
232
+ }
233
+ if (url.protocol === "http:" &&
234
+ !["localhost", "127.0.0.1", "::1"].includes(url.hostname)) {
235
+ throw new Error(`${label} must use HTTPS unless it connects to localhost.`);
236
+ }
237
+ if (configuration.headers !== undefined &&
238
+ (!configuration.headers ||
239
+ typeof configuration.headers !== "object" ||
240
+ Array.isArray(configuration.headers) ||
241
+ Object.values(configuration.headers).some((value) => typeof value !== "string"))) {
242
+ throw new Error(`${label} headers must contain string values.`);
243
+ }
244
+ if (configuration.credentials !== undefined &&
245
+ !["omit", "same-origin", "include"].includes(configuration.credentials)) {
246
+ throw new Error(`${label} has invalid credentials.`);
247
+ }
248
+ }
249
+ else {
250
+ if (target !== "node") {
251
+ throw new Error(`${label} uses stdio, which is only available for the node target.`);
252
+ }
253
+ if (typeof configuration.command !== "string" ||
254
+ !configuration.command.trim()) {
255
+ throw new Error(`${label} requires a command.`);
256
+ }
257
+ if (configuration.args !== undefined &&
258
+ (!Array.isArray(configuration.args) ||
259
+ configuration.args.some((value) => typeof value !== "string"))) {
260
+ throw new Error(`${label} args must be an array of strings.`);
261
+ }
262
+ if (configuration.env !== undefined &&
263
+ (!configuration.env ||
264
+ typeof configuration.env !== "object" ||
265
+ Array.isArray(configuration.env) ||
266
+ Object.values(configuration.env).some((value) => typeof value !== "string"))) {
267
+ throw new Error(`${label} env must contain string values.`);
268
+ }
269
+ }
270
+ validateNumber(label, "timeoutMs", configuration.timeoutMs, {
271
+ integer: true,
272
+ minimum: 1,
273
+ maximum: 300_000,
274
+ });
275
+ validateNumber(label, "maxOutputBytes", configuration.maxOutputBytes, {
276
+ integer: true,
277
+ minimum: 1,
278
+ maximum: 10_000_000,
279
+ });
280
+ }
160
281
  function compileActions(agentName, sourceDirectory, actionRuntime, target) {
161
282
  const actionsDirectory = resolve(sourceDirectory, "actions");
162
283
  if (!existsSync(actionsDirectory)) {
@@ -49,7 +49,7 @@ export async function initializeProject(projectRoot) {
49
49
  console.log(`Created ${relativePath}`);
50
50
  }
51
51
  await ensureGitignore(projectRoot);
52
- console.log('\nRun "orcha dev" to validate changes or "orcha run exampleAgent --input \\"Hello\\"" to execute the agent.');
52
+ console.log('\nRun "orchajs dev" to validate changes or "orchajs run exampleAgent --input \\"Hello\\"" to execute the agent.');
53
53
  }
54
54
  async function ensureGitignore(projectRoot) {
55
55
  const path = resolve(projectRoot, ".gitignore");
package/dist/orcha.js CHANGED
@@ -5,12 +5,18 @@ import { setNativeRuntimeLoader, setSandboxRuntimeLoader, } from "./runtime/acti
5
5
  import { executeNativeAction } from "./runtime/actions/native.js";
6
6
  import { getRegistryCompiler } from "./runtime/compiler-hook.js";
7
7
  import { createOrcha } from "./runtime/create-orcha.js";
8
+ import { setMcpClientFactory } from "./runtime/mcp/client.js";
8
9
  import { nodeRuntimePlatform } from "./runtime/platform-node.js";
9
10
  setNativeRuntimeLoader(async () => ({ executeNativeAction }));
10
11
  setSandboxRuntimeLoader(async () => {
11
12
  const modulePath = "./runtime/actions/sandbox.js";
12
13
  return import(modulePath);
13
14
  });
15
+ setMcpClientFactory(async (server, credentials) => {
16
+ const modulePath = "./runtime/mcp/node-client.js";
17
+ const { createNodeMcpClient } = await import(modulePath);
18
+ return createNodeMcpClient(server, credentials);
19
+ });
14
20
  export const orcha = createOrcha((configuration) => {
15
21
  const projectRoot = resolve(configuration.root ??
16
22
  process.env.ORCHA_PROJECT_ROOT ??
@@ -23,7 +29,7 @@ export const orcha = createOrcha((configuration) => {
23
29
  existsSync(compiledManifestPath(projectRoot))) {
24
30
  return loadCompiledManifest(projectRoot, configuration);
25
31
  }
26
- throw new Error('Orcha agents must be compiled before runtime initialization. Run "npx orcha dev" during development or "npx orcha build" before starting the application.');
32
+ throw new Error('Orcha agents must be compiled before runtime initialization. Run "npx orchajs dev" during development or "npx orchajs build" before starting the application.');
27
33
  }, generateProviderResponse, nodeRuntimePlatform);
28
34
  function isPrecompiledRuntime() {
29
35
  return (process.env.ORCHA_USE_BUILD === "1" ||
@@ -34,14 +40,14 @@ function isPrecompiledRuntime() {
34
40
  function loadCompiledManifest(projectRoot, configuration) {
35
41
  const manifestPath = compiledManifestPath(projectRoot);
36
42
  if (!existsSync(manifestPath)) {
37
- throw new Error(`ORCHA_PRODUCTION_BUNDLE_MISSING: "${manifestPath}" was not found. Run "npx orcha build" before packaging, include ".orcha/dist" in the deployment, or configure the Orcha build integration.`);
43
+ throw new Error(`ORCHA_PRODUCTION_BUNDLE_MISSING: "${manifestPath}" was not found. Run "npx orchajs build" before packaging, include ".orcha/dist" in the deployment, or configure the Orcha build integration.`);
38
44
  }
39
45
  let parsed;
40
46
  try {
41
47
  parsed = JSON.parse(readFileSync(manifestPath, "utf8"));
42
48
  }
43
49
  catch (error) {
44
- throw new Error(`Orcha could not read the compiled manifest at "${manifestPath}". Run "npx orcha build" again.`, { cause: error });
50
+ throw new Error(`Orcha could not read the compiled manifest at "${manifestPath}". Run "npx orchajs build" again.`, { cause: error });
45
51
  }
46
52
  if (typeof parsed !== "object" ||
47
53
  parsed === null ||
@@ -51,14 +57,14 @@ function loadCompiledManifest(projectRoot, configuration) {
51
57
  typeof parsed.agents !== "object" ||
52
58
  parsed.agents === null ||
53
59
  Array.isArray(parsed.agents)) {
54
- throw new Error(`Orcha compiled manifest "${manifestPath}" is invalid. Run "npx orcha build" again.`);
60
+ throw new Error(`Orcha compiled manifest "${manifestPath}" is invalid. Run "npx orchajs build" again.`);
55
61
  }
56
62
  const bundle = parsed;
57
63
  const registeredAgents = Object.keys(configuration.agents).sort();
58
64
  const compiledAgents = Object.keys(bundle.agents).sort();
59
65
  if (registeredAgents.length !== compiledAgents.length ||
60
66
  registeredAgents.some((name, index) => name !== compiledAgents[index])) {
61
- throw new Error(`Orcha compiled manifest does not match the registered agents. Run "npx orcha build" again. Expected [${registeredAgents.join(", ")}], found [${compiledAgents.join(", ")}].`);
67
+ throw new Error(`Orcha compiled manifest does not match the registered agents. Run "npx orchajs build" again. Expected [${registeredAgents.join(", ")}], found [${compiledAgents.join(", ")}].`);
62
68
  }
63
69
  return bundle;
64
70
  }
@@ -0,0 +1,10 @@
1
+ export type PackageManager = "npm" | "yarn" | "pnpm" | "bun";
2
+ export declare function detectPackageManager(projectRoot?: string): PackageManager;
3
+ export declare function installCommand(packageManager: PackageManager, packages: readonly string[], development: boolean): {
4
+ command: string;
5
+ arguments: string[];
6
+ };
7
+ export declare function runPackageManager(command: string, arguments_: string[], options?: {
8
+ cwd?: string;
9
+ env?: NodeJS.ProcessEnv;
10
+ }): Promise<number>;
@@ -0,0 +1,78 @@
1
+ import { spawn } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import { resolve } from "node:path";
4
+ export function detectPackageManager(projectRoot = process.cwd()) {
5
+ if (existsSync(resolve(projectRoot, "yarn.lock"))) {
6
+ return "yarn";
7
+ }
8
+ if (existsSync(resolve(projectRoot, "pnpm-lock.yaml"))) {
9
+ return "pnpm";
10
+ }
11
+ if (existsSync(resolve(projectRoot, "bun.lock")) ||
12
+ existsSync(resolve(projectRoot, "bun.lockb"))) {
13
+ return "bun";
14
+ }
15
+ const userAgent = process.env.npm_config_user_agent;
16
+ if (userAgent?.startsWith("yarn/")) {
17
+ return "yarn";
18
+ }
19
+ if (userAgent?.startsWith("pnpm/")) {
20
+ return "pnpm";
21
+ }
22
+ if (userAgent?.startsWith("bun/")) {
23
+ return "bun";
24
+ }
25
+ return "npm";
26
+ }
27
+ export function installCommand(packageManager, packages, development) {
28
+ switch (packageManager) {
29
+ case "yarn":
30
+ return {
31
+ command: executable("yarn"),
32
+ arguments: ["add", ...(development ? ["--dev"] : []), ...packages],
33
+ };
34
+ case "pnpm":
35
+ return {
36
+ command: executable("pnpm"),
37
+ arguments: [
38
+ "add",
39
+ ...(development ? ["--save-dev"] : []),
40
+ ...packages,
41
+ ],
42
+ };
43
+ case "bun":
44
+ return {
45
+ command: executable("bun"),
46
+ arguments: ["add", ...(development ? ["--dev"] : []), ...packages],
47
+ };
48
+ default:
49
+ return {
50
+ command: executable("npm"),
51
+ arguments: [
52
+ "install",
53
+ ...(development ? ["--save-dev"] : []),
54
+ ...packages,
55
+ ],
56
+ };
57
+ }
58
+ }
59
+ export function runPackageManager(command, arguments_, options = {}) {
60
+ return new Promise((resolveProcess, reject) => {
61
+ const child = spawn(command, arguments_, {
62
+ cwd: options.cwd ?? process.cwd(),
63
+ env: options.env ?? process.env,
64
+ stdio: "inherit",
65
+ });
66
+ child.once("error", reject);
67
+ child.once("exit", (code, signal) => {
68
+ if (signal) {
69
+ process.kill(process.pid, signal);
70
+ return;
71
+ }
72
+ resolveProcess(code ?? 1);
73
+ });
74
+ });
75
+ }
76
+ function executable(command) {
77
+ return process.platform === "win32" ? `${command}.cmd` : command;
78
+ }