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
@@ -0,0 +1,87 @@
1
+ import { Client } from "@modelcontextprotocol/sdk/client";
2
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
3
+ export async function createHttpMcpClient(server, credentials) {
4
+ if (server.transport !== "streamable-http") {
5
+ throw new Error(`MCP transport "${server.transport}" is not available in this runtime.`);
6
+ }
7
+ const client = new Client({
8
+ name: "orchajs",
9
+ version: "1.0.0",
10
+ });
11
+ const transport = new StreamableHTTPClientTransport(new URL(server.url), {
12
+ requestInit: {
13
+ headers: resolveValues(server.headers ?? {}, credentials),
14
+ credentials: server.credentials,
15
+ },
16
+ redirectPolicy: "same-origin",
17
+ });
18
+ await client.connect(transport, {
19
+ timeout: server.timeoutMs ?? 30_000,
20
+ });
21
+ return {
22
+ async listTools(signal) {
23
+ const tools = [];
24
+ let cursor;
25
+ do {
26
+ const result = await client.listTools(cursor ? { cursor } : undefined, {
27
+ signal,
28
+ timeout: server.timeoutMs ?? 30_000,
29
+ });
30
+ tools.push(...result.tools.map((tool) => ({
31
+ name: tool.name,
32
+ description: tool.description,
33
+ inputSchema: tool.inputSchema,
34
+ })));
35
+ cursor = result.nextCursor;
36
+ } while (cursor);
37
+ return tools;
38
+ },
39
+ async callTool(name, arguments_, signal) {
40
+ const result = await client.callTool({ name, arguments: arguments_ }, undefined, {
41
+ signal,
42
+ timeout: server.timeoutMs ?? 30_000,
43
+ maxTotalTimeout: server.timeoutMs ?? 30_000,
44
+ });
45
+ return normalizeMcpToolResult(result);
46
+ },
47
+ async close() {
48
+ await client.close();
49
+ },
50
+ };
51
+ }
52
+ function resolveValues(values, credentials) {
53
+ return Object.fromEntries(Object.entries(values).map(([name, value]) => [
54
+ name,
55
+ value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_match, key) => {
56
+ const resolved = credentials[key];
57
+ if (resolved === undefined) {
58
+ throw new Error(`MCP credential "${key}" required by header "${name}" is not configured.`);
59
+ }
60
+ return resolved;
61
+ }),
62
+ ]));
63
+ }
64
+ export function normalizeMcpToolResult(result) {
65
+ if (!isRecord(result)) {
66
+ throw new Error("MCP tool returned an invalid result.");
67
+ }
68
+ if ("toolResult" in result) {
69
+ return normalizeMcpToolResult(result.toolResult);
70
+ }
71
+ if (!("content" in result)) {
72
+ throw new Error("MCP tool result is missing content.");
73
+ }
74
+ return {
75
+ output: result.structuredContent === undefined
76
+ ? result.content
77
+ : {
78
+ content: result.content,
79
+ structuredContent: result.structuredContent,
80
+ },
81
+ isError: typeof result.isError === "boolean" ? result.isError : undefined,
82
+ };
83
+ }
84
+ export { resolveValues as resolveMcpConfigurationValues };
85
+ function isRecord(value) {
86
+ return typeof value === "object" && value !== null;
87
+ }
@@ -0,0 +1,3 @@
1
+ import type { CompiledMcpServerManifest } from "../../types.js";
2
+ import type { McpClientConnection } from "./client.js";
3
+ export declare function createNodeMcpClient(server: CompiledMcpServerManifest, configuredCredentials: Record<string, string | undefined>): Promise<McpClientConnection>;
@@ -0,0 +1,60 @@
1
+ import { Client } from "@modelcontextprotocol/sdk/client";
2
+ import { getDefaultEnvironment, StdioClientTransport, } from "@modelcontextprotocol/sdk/client/stdio.js";
3
+ import { createHttpMcpClient, normalizeMcpToolResult, resolveMcpConfigurationValues, } from "./http-client.js";
4
+ export async function createNodeMcpClient(server, configuredCredentials) {
5
+ const credentials = {
6
+ ...process.env,
7
+ ...configuredCredentials,
8
+ };
9
+ if (server.transport === "streamable-http") {
10
+ return createHttpMcpClient(server, credentials);
11
+ }
12
+ const client = new Client({
13
+ name: "orchajs",
14
+ version: "1.0.0",
15
+ });
16
+ const transport = new StdioClientTransport({
17
+ command: server.command,
18
+ args: server.args,
19
+ env: server.env
20
+ ? {
21
+ ...getDefaultEnvironment(),
22
+ ...resolveMcpConfigurationValues(server.env, credentials),
23
+ }
24
+ : undefined,
25
+ stderr: "inherit",
26
+ });
27
+ await client.connect(transport, {
28
+ timeout: server.timeoutMs ?? 30_000,
29
+ });
30
+ return {
31
+ async listTools(signal) {
32
+ const tools = [];
33
+ let cursor;
34
+ do {
35
+ const result = await client.listTools(cursor ? { cursor } : undefined, {
36
+ signal,
37
+ timeout: server.timeoutMs ?? 30_000,
38
+ });
39
+ tools.push(...result.tools.map((tool) => ({
40
+ name: tool.name,
41
+ description: tool.description,
42
+ inputSchema: tool.inputSchema,
43
+ })));
44
+ cursor = result.nextCursor;
45
+ } while (cursor);
46
+ return tools;
47
+ },
48
+ async callTool(name, arguments_, signal) {
49
+ const result = await client.callTool({ name, arguments: arguments_ }, undefined, {
50
+ signal,
51
+ timeout: server.timeoutMs ?? 30_000,
52
+ maxTotalTimeout: server.timeoutMs ?? 30_000,
53
+ });
54
+ return normalizeMcpToolResult(result);
55
+ },
56
+ async close() {
57
+ await client.close();
58
+ },
59
+ };
60
+ }
@@ -2,4 +2,4 @@ export { OrchaError } from "./errors.js";
2
2
  export type { Orcha, OrchaClient, } from "./runtime/create-orcha.js";
3
3
  export { exportSessionJsonl, migrateSessionStore, } from "./storage/migrate.js";
4
4
  export type { SessionStoreMigrationResult, } from "./storage/migrate.js";
5
- export type { ActionConfiguration, AgentTestActionConfiguration, AgentTestActionExpectation, AgentTestActionResponse, AgentTestAssertionResult, AgentTestCaseConfiguration, AgentTestCaseReport, AgentTestCaseSummary, AgentTestExpectation, AgentTestReport, AgentTestTextExpectation, AgentTestValueExpectation, AgentTestWarning, ApiKeyProviderConfiguration, AwsCredentials, AgentContinueInput, AgentConfiguration, AgentContentInput, AgentInput, AgentRegistration, AgentRuntime, ClientCapability, ClientToolCall, CompletedRunResult, CompiledActionManifest, CompiledAgentManifest, CompiledBundle, CompiledEvaluationManifest, CompiledSkillManifest, EvaluationConfiguration, EvaluationMetricConfiguration, EvaluationMetricResult, EvaluationResult, Execution, ExecutionSnapshot, FailedRunResult, FileContent, FilePathContentInput, LocalFileContent, LocalActionRuntimeConfiguration, MessageContent, MessageContentInput, MetadataValue, OrchaErrorCode, OrchaInitConfiguration, PausedRunResult, PaginationOptions, ProjectConfiguration, ProviderConfiguration, ProviderInitConfigurations, ProviderName, BedrockProviderConfiguration, RunError, RunStatus, RunTestsOptions, ResumeInput, RunResult, SessionEvent, SessionEventListOptions, SessionEvents, SessionEventType, SessionHistory, SessionHistoryItem, SessionList, SessionListOptions, SessionMetadata, SessionSnapshot, SessionStatus, SessionStore, SkillConfiguration, SessionUpdate, StreamingRunSnapshot, SubagentConfiguration, TextContent, ToolResult, ToolResumeInput, UrlContentInput, Usage, VertexAIProviderConfiguration, GoogleServiceAccountCredentials, WaitingRunResult, WaitingForSubagentSnapshot, } from "./types.js";
5
+ export type { ActionConfiguration, AgentTestActionConfiguration, AgentTestActionExpectation, AgentTestActionResponse, AgentTestAssertionResult, AgentTestCaseConfiguration, AgentTestCaseReport, AgentTestCaseSummary, AgentTestExpectation, AgentTestReport, AgentTestTextExpectation, AgentTestValueExpectation, AgentTestWarning, ApiKeyProviderConfiguration, AwsCredentials, AgentContinueInput, AgentConfiguration, AgentContentInput, AgentInput, AgentRegistration, AgentRuntime, ClientCapability, ClientToolCall, CompletedRunResult, CompiledActionManifest, CompiledAgentManifest, CompiledBundle, CompiledEvaluationManifest, CompiledMcpServerManifest, CompiledSkillManifest, EvaluationConfiguration, EvaluationMetricConfiguration, EvaluationMetricResult, EvaluationResult, Execution, ExecutionSnapshot, FailedRunResult, FileContent, FilePathContentInput, LocalFileContent, LocalActionRuntimeConfiguration, MessageContent, MessageContentInput, McpHttpServerConfiguration, McpRegistration, McpServerConfiguration, McpStdioServerConfiguration, MetadataValue, OrchaErrorCode, OrchaInitConfiguration, PausedRunResult, PaginationOptions, ProjectConfiguration, ProviderConfiguration, ProviderInitConfigurations, ProviderName, BedrockProviderConfiguration, RunError, RunStatus, RunTestsOptions, ResumeInput, RunResult, SessionEvent, SessionEventListOptions, SessionEvents, SessionEventType, SessionHistory, SessionHistoryItem, SessionList, SessionListOptions, SessionMetadata, SessionSnapshot, SessionStatus, SessionStore, SkillConfiguration, SessionUpdate, StreamingRunSnapshot, SubagentConfiguration, SubagentRegistration, TextContent, ToolResult, ToolResumeInput, UrlContentInput, Usage, VertexAIProviderConfiguration, GoogleServiceAccountCredentials, WaitingRunResult, WaitingForSubagentSnapshot, } from "./types.js";
package/dist/testing.js CHANGED
@@ -302,6 +302,7 @@ function testWarnings(manifest, configuration) {
302
302
  const mocked = new Set(Object.keys(configuration.actions ?? {}));
303
303
  const actions = Object.keys(manifest.actions)
304
304
  .filter((name) => !mocked.has(name))
305
+ .concat(Object.keys(manifest.mcpServers ?? {}).map((name) => `mcp:${name}`))
305
306
  .sort();
306
307
  if (actions.length === 0) {
307
308
  return [];
package/dist/types.d.ts CHANGED
@@ -42,14 +42,23 @@ export type ProviderInitConfigurations = {
42
42
  export interface ProjectConfiguration {
43
43
  providers: ResolvedProviderConfigurations;
44
44
  actions?: LocalActionRuntimeConfiguration;
45
+ mcp?: {
46
+ credentials?: Record<string, string | undefined>;
47
+ };
45
48
  storage?: {
46
49
  strategy?: "node-jsonl" | "sqlite" | "indexeddb" | "react-native";
47
50
  directory?: string;
48
51
  };
49
52
  }
53
+ export type McpRegistration = Record<string, string>;
54
+ export type SubagentRegistration = string | {
55
+ path: string;
56
+ mcp?: McpRegistration;
57
+ };
50
58
  export type AgentRegistration = string | {
51
59
  path: string;
52
- subagents?: Record<string, string>;
60
+ mcp?: McpRegistration;
61
+ subagents?: Record<string, SubagentRegistration>;
53
62
  };
54
63
  export interface OrchaInitConfiguration {
55
64
  providers: ProviderInitConfigurations;
@@ -61,6 +70,7 @@ export interface OrchaInitConfiguration {
61
70
  endpoint?: string;
62
71
  };
63
72
  actions?: LocalActionRuntimeConfiguration;
73
+ mcp?: ProjectConfiguration["mcp"];
64
74
  storage?: ProjectConfiguration["storage"];
65
75
  root?: string;
66
76
  }
@@ -233,6 +243,27 @@ export interface LocalActionRuntimeConfiguration {
233
243
  stackLimitKb?: number;
234
244
  };
235
245
  }
246
+ export interface McpHttpServerConfiguration {
247
+ transport: "streamable-http";
248
+ url: string;
249
+ headers?: Record<string, string>;
250
+ credentials?: RequestCredentials;
251
+ timeoutMs?: number;
252
+ maxOutputBytes?: number;
253
+ }
254
+ export interface McpStdioServerConfiguration {
255
+ transport: "stdio";
256
+ command: string;
257
+ args?: string[];
258
+ env?: Record<string, string>;
259
+ timeoutMs?: number;
260
+ maxOutputBytes?: number;
261
+ }
262
+ export type McpServerConfiguration = McpHttpServerConfiguration | McpStdioServerConfiguration;
263
+ export type CompiledMcpServerManifest = McpServerConfiguration & {
264
+ key: string;
265
+ directoryName: string;
266
+ };
236
267
  export interface CompiledAgentManifest extends Omit<AgentConfiguration, "provider" | "subagents"> {
237
268
  key: string;
238
269
  name: string;
@@ -241,6 +272,7 @@ export interface CompiledAgentManifest extends Omit<AgentConfiguration, "provide
241
272
  actions: Record<string, CompiledActionManifest>;
242
273
  skills: Record<string, CompiledSkillManifest>;
243
274
  evaluations: Record<string, CompiledEvaluationManifest>;
275
+ mcpServers: Record<string, CompiledMcpServerManifest>;
244
276
  subagentPolicy?: SubagentConfiguration;
245
277
  subagents: Record<string, CompiledAgentManifest>;
246
278
  }
@@ -30,21 +30,21 @@ files under \`.orcha/\`.
30
30
 
31
31
  ## Commands
32
32
 
33
- - \`orcha init\` creates the initial Orcha files without overwriting files.
34
- - \`orcha dev\` validates agent source and watches \`orcha/**\` for changes.
35
- - \`orcha playground\` opens the built-in local UI and hot reloads agent source.
36
- - \`orcha run <agent> --input "\u2026"\` executes one registered agent.
37
- - \`orcha run <agent> --input-file request.json\` accepts structured input.
38
- - \`orcha run <agent> --session <id> --input "\u2026"\` continues a session.
39
- - \`orcha run <agent> --session <id> --tool-results results.json\` submits
33
+ - \`orchajs init\` creates the initial Orcha files without overwriting files.
34
+ - \`orchajs dev\` validates agent source and watches \`orcha/**\` for changes.
35
+ - \`orchajs playground\` opens the built-in local UI and hot reloads agent source.
36
+ - \`orchajs run <agent> --input "\u2026"\` executes one registered agent.
37
+ - \`orchajs run <agent> --input-file request.json\` accepts structured input.
38
+ - \`orchajs run <agent> --session <id> --input "\u2026"\` continues a session.
39
+ - \`orchajs run <agent> --session <id> --tool-results results.json\` submits
40
40
  pending client-action results.
41
- - \`orcha test\` runs every enabled discovered agent test.
42
- - \`orcha test <agent>\` or \`orcha test <agent>/<case>\` narrows the run.
43
- - \`orcha migrate-storage --to sqlite|node-jsonl\` copies all session histories
41
+ - \`orchajs test\` runs every enabled discovered agent test.
42
+ - \`orchajs test <agent>\` or \`orchajs test <agent>/<case>\` narrows the run.
43
+ - \`orchajs migrate-storage --to sqlite|node-jsonl\` copies all session histories
44
44
  between local stores without deleting the source.
45
- - \`orcha export-session <agent> <sessionId> [--output <path>]\` exports one
45
+ - \`orchajs export-session <agent> <sessionId> [--output <path>]\` exports one
46
46
  session from the active store as JSONL.
47
- - \`orcha build\` creates the production Orcha bundle without calling models.
47
+ - \`orchajs build\` creates the production Orcha bundle without calling models.
48
48
  - Add \`--json\` to \`run\` and \`test\` for machine-readable output.
49
49
 
50
50
  \`run\`, \`test\`, and playground executions use real providers and require
@@ -54,7 +54,7 @@ under \`.orcha/sessions/<agentName>/\`; opt-in SQLite stores all agents in
54
54
 
55
55
  ## Production deployment
56
56
 
57
- \`orcha build\` writes \`.orcha/dist/bundle.js\` for bundler integrations and
57
+ \`orchajs build\` writes \`.orcha/dist/bundle.js\` for bundler integrations and
58
58
  \`.orcha/dist/manifest.json\` for unbundled production runtimes. If deployment
59
59
  uses plain \`tsc\`, \`serverless-plugin-typescript\`, or another packager that
60
60
  does not use \`orchajs/esbuild\`, explicitly include \`.orcha/dist/**\` in the
@@ -70,7 +70,7 @@ package:
70
70
  - ".orcha/dist/**"
71
71
  \`\`\`
72
72
 
73
- Do not assume that a successful \`orcha build\` means the generated files were
73
+ Do not assume that a successful \`orchajs build\` means the generated files were
74
74
  copied by a later packaging tool. Inspect the final ZIP or container image and
75
75
  confirm that \`.orcha/dist/manifest.json\` is present.
76
76
 
@@ -111,6 +111,8 @@ required.
111
111
  \`AMARSIA_API_URL\` and then \`https://api.amarsia.com\`.
112
112
  - \`actions\` (optional): overrides the native local-action runtime or configures
113
113
  its environment and sandbox settings.
114
+ - \`mcp.credentials\` (optional): runtime-only values used to resolve
115
+ \`\${NAME}\` placeholders in MCP headers or stdio environment values.
114
116
  - \`storage.strategy\` (optional): \`"node-jsonl"\` (default) or \`"sqlite"\`.
115
117
  The SQLite driver ships as an internal optional Orcha dependency.
116
118
  - \`storage.directory\` (optional): session directory relative to project
@@ -162,11 +164,47 @@ explicit service-account credentials are optional. Bedrock requires \`region\`;
162
164
  explicit AWS credentials are optional. Never place credentials in
163
165
  \`index.json\`, instructions, tests, session metadata, or committed files.
164
166
 
167
+ ## MCP connections
168
+
169
+ Assign named MCP folders in an agent or subagent registration:
170
+
171
+ \`\`\`ts
172
+ agents: {
173
+ supportBot: {
174
+ path: "./supportBot",
175
+ mcp: {
176
+ github: "./mcp/github",
177
+ },
178
+ },
179
+ }
180
+ \`\`\`
181
+
182
+ \`orcha/mcp/github/index.json\` configures either cross-platform Streamable
183
+ HTTP or Node-only stdio:
184
+
185
+ \`\`\`json
186
+ {
187
+ "transport": "streamable-http",
188
+ "url": "https://mcp.example.com",
189
+ "headers": {
190
+ "Authorization": "Bearer \${GITHUB_MCP_TOKEN}"
191
+ }
192
+ }
193
+ \`\`\`
194
+
195
+ All discovered tools are available as \`github__<toolName>\`. MCP output is
196
+ untrusted external data. Keep secrets out of JSON and provide placeholder
197
+ values through \`orcha.init().mcp.credentials\`; Node also reads
198
+ \`process.env\`.
199
+
165
200
  ## Agent folders
166
201
 
167
202
  \`\`\`text
168
203
  orcha/
169
204
  index.ts
205
+ mcp/
206
+ github/
207
+ index.json
170
208
  supportBot/
171
209
  index.json
172
210
  instructions.md
@@ -593,7 +631,7 @@ Test \`index.json\` fields:
593
631
  - \`expect.actions\` (optional): ordered expected calls. Each may assert
594
632
  \`arguments.equals\` or \`arguments.partial\`.
595
633
 
596
- The test folder name is the selector used by \`orcha test agent/testName\`.
634
+ The test folder name is the selector used by \`orchajs test agent/testName\`.
597
635
 
598
636
  ## Evaluations
599
637
 
@@ -621,7 +659,7 @@ metrics, and thresholds:
621
659
 
622
660
  \`execution.result\` does not wait for judges. Await
623
661
  \`execution.evaluations\` when results must finish before process exit.
624
- Evaluations always finish during \`orcha test\`; judge errors and missed
662
+ Evaluations always finish during \`orchajs test\`; judge errors and missed
625
663
  thresholds fail the test. Lifecycle events are \`evaluation.requested\`,
626
664
  \`evaluation.completed\`, and \`evaluation.failed\`.
627
665
 
@@ -1027,7 +1065,7 @@ number. A conversational \`resume(...content)\` starts a new run number.
1027
1065
  Concrete action arguments and outputs are validated against their schemas
1028
1066
  when the action is used.
1029
1067
 
1030
- \`orcha dev\` repeats validation when files change. \`orcha build\` performs
1068
+ \`orchajs dev\` repeats validation when files change. \`orchajs build\` performs
1031
1069
  offline production compilation. Neither command invokes a provider.
1032
1070
 
1033
1071
  ### Run lifecycle
@@ -1053,7 +1091,7 @@ offline production compilation. Neither command invokes a provider.
1053
1091
  The parent reports \`waiting_for_subagent\` until each synchronous child
1054
1092
  call returns.
1055
1093
  8. The model loop continues until final output, failure, a pause, or the
1056
- maximum of 10 action rounds.
1094
+ maximum of 20 action rounds.
1057
1095
  9. Usage is normalized and aggregated across every model call in the run.
1058
1096
  10. After \`run.completed\`, enabled evaluations start in the background.
1059
1097
  \`execution.result\` is already available; \`execution.evaluations\` waits
@@ -1106,7 +1144,7 @@ needed for faithful continuation but are omitted from evaluation transcripts.
1106
1144
  - Mock actions when tests must avoid side effects; document intentional live
1107
1145
  action coverage.
1108
1146
  - Do not commit \`.orcha/\`; it contains generated output and session data.
1109
- - Run \`orcha dev\` after filesystem changes and \`orcha test\` when behavior
1147
+ - Run \`orchajs dev\` after filesystem changes and \`orchajs test\` when behavior
1110
1148
  changes.
1111
1149
  - Do not weaken assertions to match incorrect behavior. Remove an assertion
1112
1150
  only when it is stricter than the documented agent contract.
@@ -31,6 +31,7 @@ var import_orcha = require("../orcha.js");
31
31
  var import_compiler_hook = require("../runtime/compiler-hook.js");
32
32
  var import_compile = require("./compile.js");
33
33
  var import_catalog = require("../providers/catalog.js");
34
+ var import_dependencies = require("../providers/dependencies.js");
34
35
  let registryImportSequence = 0;
35
36
  async function buildProject(options = {}) {
36
37
  const projectRoot = (0, import_path.resolve)(options.projectRoot ?? process.cwd());
@@ -45,7 +46,7 @@ async function buildProject(options = {}) {
45
46
  );
46
47
  const registryPath = (0, import_path.resolve)(projectRoot, "orcha/index.ts");
47
48
  if (!(0, import_fs.existsSync)(registryPath)) {
48
- throw new Error('Missing "orcha/index.ts". Run "orcha init" first.');
49
+ throw new Error('Missing "orcha/index.ts". Run "orchajs init" first.');
49
50
  }
50
51
  const temporaryDirectory = (0, import_path.resolve)(projectRoot, ".orcha/.build");
51
52
  const registryBundlePath = (0, import_path.resolve)(temporaryDirectory, "registry.mjs");
@@ -128,6 +129,12 @@ async function buildProject(options = {}) {
128
129
  )
129
130
  ];
130
131
  const providerRuntimeSource = createProviderRuntimeSource(includedProviders, target);
132
+ await (0, import_dependencies.ensureProviderDependencies)(includedProviders, projectRoot);
133
+ const hasMcp = allCompiledAgents(compiledBundle.agents).some(
134
+ (agent) => Object.keys(agent.mcpServers ?? {}).length > 0
135
+ );
136
+ await (0, import_dependencies.ensureCompiledMcpDependencies)(compiledBundle, projectRoot);
137
+ const mcpRuntimeSource = hasMcp ? createMcpRuntimeSource(target) : "";
131
138
  const needsNodeRequire = compiledBundle.actionRuntime === "sandbox" || includedProviders.includes("vertexai") || includedProviders.includes("bedrock");
132
139
  await (0, import_promises.writeFile)(
133
140
  productionEntryPath,
@@ -139,6 +146,7 @@ async function buildProject(options = {}) {
139
146
  nodeStorageExports,
140
147
  providerRuntimeSource,
141
148
  platformActionRuntimeSource,
149
+ mcpRuntimeSource,
142
150
  sandboxRuntimeSource,
143
151
  `const compiledBundle = ${JSON.stringify(compiledBundle)};`,
144
152
  "const generateProviderResponse = createProviderResponseGenerator(includedProviders);",
@@ -237,6 +245,24 @@ function createPlatformActionRuntimeSource(target) {
237
245
  ""
238
246
  ].join("\n");
239
247
  }
248
+ function createMcpRuntimeSource(target) {
249
+ const runtimeDirectory = (0, import_path.dirname)((0, import_url.fileURLToPath)(__orchaImportMetaUrl));
250
+ const clientPath = (0, import_path.resolve)(
251
+ runtimeDirectory,
252
+ "../runtime/mcp/client.js"
253
+ ).replaceAll("\\", "/");
254
+ const implementationPath = (0, import_path.resolve)(
255
+ runtimeDirectory,
256
+ target === "node" ? "../runtime/mcp/node-client.js" : "../runtime/mcp/http-client.js"
257
+ ).replaceAll("\\", "/");
258
+ const factoryName = target === "node" ? "createNodeMcpClient" : "createHttpMcpClient";
259
+ return [
260
+ `import { setMcpClientFactory } from ${JSON.stringify(clientPath)};`,
261
+ `import { ${factoryName} } from ${JSON.stringify(implementationPath)};`,
262
+ `setMcpClientFactory(${factoryName});`,
263
+ ""
264
+ ].join("\n");
265
+ }
240
266
  function createNodeStorageExports() {
241
267
  const sourceRoot = (0, import_path.dirname)((0, import_url.fileURLToPath)(__orchaImportMetaUrl));
242
268
  const jsonlPath = (0, import_path.resolve)(
@@ -41,15 +41,21 @@ function compileRegistry(registrations, registryRoot, actionRuntime = "native",
41
41
  }
42
42
  const normalized = normalizeAgentRegistration(key, registration);
43
43
  const subagents = {};
44
- for (const [subagentKey, registeredPath] of Object.entries(
44
+ for (const [subagentKey, registration2] of Object.entries(
45
45
  normalized.subagents
46
46
  )) {
47
47
  if (!subagentKey.trim()) {
48
48
  throw new Error(`Agent "${key}" has an empty subagent name.`);
49
49
  }
50
+ const subagent = normalizeSubagentRegistration(
51
+ key,
52
+ subagentKey,
53
+ registration2
54
+ );
50
55
  subagents[subagentKey] = compileAgent(
51
56
  subagentKey,
52
- registeredPath,
57
+ subagent.path,
58
+ subagent.mcp,
53
59
  registryRoot,
54
60
  actionRuntime,
55
61
  target
@@ -58,6 +64,7 @@ function compileRegistry(registrations, registryRoot, actionRuntime = "native",
58
64
  const parent = compileAgent(
59
65
  key,
60
66
  normalized.path,
67
+ normalized.mcp,
61
68
  registryRoot,
62
69
  actionRuntime,
63
70
  target
@@ -85,7 +92,7 @@ function normalizeAgentRegistration(key, registration) {
85
92
  if (!registration.trim()) {
86
93
  throw new Error(`Agent "${key}" must register a folder path.`);
87
94
  }
88
- return { path: registration, subagents: {} };
95
+ return { path: registration, mcp: {}, subagents: {} };
89
96
  }
90
97
  if (!registration || typeof registration !== "object") {
91
98
  throw new Error(`Agent "${key}" must register a folder path.`);
@@ -94,23 +101,56 @@ function normalizeAgentRegistration(key, registration) {
94
101
  throw new Error(`Agent "${key}" must register a folder path.`);
95
102
  }
96
103
  if (registration.subagents !== void 0 && (!registration.subagents || typeof registration.subagents !== "object" || Array.isArray(registration.subagents))) {
97
- throw new Error(`Agent "${key}" subagents must be an object of folder paths.`);
104
+ throw new Error(
105
+ `Agent "${key}" subagents must be an object of named registrations.`
106
+ );
98
107
  }
99
- for (const [subagentKey, registeredPath] of Object.entries(
100
- registration.subagents ?? {}
101
- )) {
102
- if (typeof registeredPath !== "string" || !registeredPath.trim()) {
108
+ validateMcpRegistration(`Agent "${key}"`, registration.mcp);
109
+ return {
110
+ path: registration.path,
111
+ mcp: registration.mcp ?? {},
112
+ subagents: registration.subagents ?? {}
113
+ };
114
+ }
115
+ function normalizeSubagentRegistration(parentKey, key, registration) {
116
+ if (typeof registration === "string") {
117
+ if (!registration.trim()) {
103
118
  throw new Error(
104
- `Subagent "${key}/${subagentKey}" must register a folder path.`
119
+ `Subagent "${parentKey}/${key}" must register a folder path.`
105
120
  );
106
121
  }
122
+ return { path: registration, mcp: {} };
123
+ }
124
+ if (!registration || typeof registration !== "object" || typeof registration.path !== "string" || !registration.path.trim()) {
125
+ throw new Error(
126
+ `Subagent "${parentKey}/${key}" must register a folder path.`
127
+ );
107
128
  }
129
+ validateMcpRegistration(
130
+ `Subagent "${parentKey}/${key}"`,
131
+ registration.mcp
132
+ );
108
133
  return {
109
134
  path: registration.path,
110
- subagents: registration.subagents ?? {}
135
+ mcp: registration.mcp ?? {}
111
136
  };
112
137
  }
113
- function compileAgent(key, registeredPath, registryRoot, actionRuntime, target) {
138
+ function validateMcpRegistration(owner, registration) {
139
+ if (registration !== void 0 && (!registration || typeof registration !== "object" || Array.isArray(registration))) {
140
+ throw new Error(`${owner} mcp must be an object of named folder paths.`);
141
+ }
142
+ for (const [key, path] of Object.entries(registration ?? {})) {
143
+ if (!/^[a-zA-Z0-9_-]{1,32}$/.test(key)) {
144
+ throw new Error(`${owner} has invalid MCP name "${key}".`);
145
+ }
146
+ if (typeof path !== "string" || !path.trim()) {
147
+ throw new Error(
148
+ `${owner} MCP "${key}" must register a folder path.`
149
+ );
150
+ }
151
+ }
152
+ }
153
+ function compileAgent(key, registeredPath, mcpRegistration, registryRoot, actionRuntime, target) {
114
154
  const name = key;
115
155
  const sourceDirectory = (0, import_path.resolve)(registryRoot, registeredPath);
116
156
  const configPath = (0, import_path.resolve)(sourceDirectory, "index.json");
@@ -205,10 +245,107 @@ function compileAgent(key, registeredPath, registryRoot, actionRuntime, target)
205
245
  ),
206
246
  skills: compileSkills(name, sourceDirectory),
207
247
  evaluations: compileEvaluations(name, sourceDirectory),
248
+ mcpServers: compileMcpServers(
249
+ name,
250
+ mcpRegistration,
251
+ registryRoot,
252
+ target
253
+ ),
208
254
  subagentPolicy: configuration.subagents ? Object.freeze({ ...configuration.subagents }) : void 0,
209
255
  subagents: Object.freeze({})
210
256
  });
211
257
  }
258
+ function compileMcpServers(agentName, registration, registryRoot, target) {
259
+ const servers = {};
260
+ for (const [key, registeredPath] of Object.entries(registration)) {
261
+ const directory = (0, import_path.resolve)(registryRoot, registeredPath);
262
+ const configurationPath = (0, import_path.resolve)(directory, "index.json");
263
+ let configuration;
264
+ try {
265
+ configuration = JSON.parse(
266
+ (0, import_fs.readFileSync)(configurationPath, "utf8")
267
+ );
268
+ } catch (error) {
269
+ throw new Error(
270
+ `MCP server "${agentName}/${key}" is missing a valid index.json at ${configurationPath}.`,
271
+ { cause: error }
272
+ );
273
+ }
274
+ validateMcpServerConfiguration(agentName, key, configuration, target);
275
+ servers[key] = Object.freeze({
276
+ ...configuration,
277
+ key,
278
+ directoryName: registeredPath
279
+ });
280
+ }
281
+ return Object.freeze(servers);
282
+ }
283
+ function validateMcpServerConfiguration(agentName, key, configuration, target) {
284
+ const label = `MCP server "${agentName}/${key}"`;
285
+ if (!configuration || typeof configuration !== "object" || !["streamable-http", "stdio"].includes(configuration.transport)) {
286
+ throw new Error(
287
+ `${label} transport must be "streamable-http" or "stdio".`
288
+ );
289
+ }
290
+ if (configuration.transport === "streamable-http") {
291
+ let url;
292
+ try {
293
+ url = new URL(configuration.url);
294
+ } catch {
295
+ throw new Error(`${label} requires a valid URL.`);
296
+ }
297
+ if (!["https:", "http:"].includes(url.protocol)) {
298
+ throw new Error(`${label} URL must use HTTP or HTTPS.`);
299
+ }
300
+ if (url.protocol === "http:" && !["localhost", "127.0.0.1", "::1"].includes(url.hostname)) {
301
+ throw new Error(
302
+ `${label} must use HTTPS unless it connects to localhost.`
303
+ );
304
+ }
305
+ if (configuration.headers !== void 0 && (!configuration.headers || typeof configuration.headers !== "object" || Array.isArray(configuration.headers) || Object.values(configuration.headers).some(
306
+ (value) => typeof value !== "string"
307
+ ))) {
308
+ throw new Error(`${label} headers must contain string values.`);
309
+ }
310
+ if (configuration.credentials !== void 0 && !["omit", "same-origin", "include"].includes(
311
+ configuration.credentials
312
+ )) {
313
+ throw new Error(`${label} has invalid credentials.`);
314
+ }
315
+ } else {
316
+ if (target !== "node") {
317
+ throw new Error(
318
+ `${label} uses stdio, which is only available for the node target.`
319
+ );
320
+ }
321
+ if (typeof configuration.command !== "string" || !configuration.command.trim()) {
322
+ throw new Error(`${label} requires a command.`);
323
+ }
324
+ if (configuration.args !== void 0 && (!Array.isArray(configuration.args) || configuration.args.some((value) => typeof value !== "string"))) {
325
+ throw new Error(`${label} args must be an array of strings.`);
326
+ }
327
+ if (configuration.env !== void 0 && (!configuration.env || typeof configuration.env !== "object" || Array.isArray(configuration.env) || Object.values(configuration.env).some(
328
+ (value) => typeof value !== "string"
329
+ ))) {
330
+ throw new Error(`${label} env must contain string values.`);
331
+ }
332
+ }
333
+ validateNumber(label, "timeoutMs", configuration.timeoutMs, {
334
+ integer: true,
335
+ minimum: 1,
336
+ maximum: 3e5
337
+ });
338
+ validateNumber(
339
+ label,
340
+ "maxOutputBytes",
341
+ configuration.maxOutputBytes,
342
+ {
343
+ integer: true,
344
+ minimum: 1,
345
+ maximum: 1e7
346
+ }
347
+ );
348
+ }
212
349
  function compileActions(agentName, sourceDirectory, actionRuntime, target) {
213
350
  const actionsDirectory = (0, import_path.resolve)(sourceDirectory, "actions");
214
351
  if (!(0, import_fs.existsSync)(actionsDirectory)) {