@mcpc-tech/cli 0.1.1-beta.1

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.
package/src/bin.mjs ADDED
@@ -0,0 +1,3096 @@
1
+ #!/usr/bin/env node
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __esm = (fn, res) => function __init() {
5
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
6
+ };
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+
12
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/mcpc__core/src/plugins/built-in/config-plugin.js
13
+ var createConfigPlugin, config_plugin_default;
14
+ var init_config_plugin = __esm({
15
+ "../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/mcpc__core/src/plugins/built-in/config-plugin.js"() {
16
+ createConfigPlugin = () => ({
17
+ name: "built-in-config",
18
+ enforce: "pre",
19
+ transformTool: (tool, context) => {
20
+ const server2 = context.server;
21
+ const config2 = server2.findToolConfig?.(context.toolName);
22
+ if (config2?.description) {
23
+ tool.description = config2.description;
24
+ }
25
+ return tool;
26
+ }
27
+ });
28
+ config_plugin_default = createConfigPlugin();
29
+ }
30
+ });
31
+
32
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/mcpc__core/src/plugins/built-in/tool-name-mapping-plugin.js
33
+ var createToolNameMappingPlugin, tool_name_mapping_plugin_default;
34
+ var init_tool_name_mapping_plugin = __esm({
35
+ "../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/mcpc__core/src/plugins/built-in/tool-name-mapping-plugin.js"() {
36
+ createToolNameMappingPlugin = () => ({
37
+ name: "built-in-tool-name-mapping",
38
+ enforce: "pre",
39
+ transformTool: (tool, context) => {
40
+ const server2 = context.server;
41
+ const toolName = context.toolName;
42
+ const dotNotation = toolName.replace(/_/g, ".");
43
+ const underscoreNotation = toolName.replace(/\./g, "_");
44
+ if (dotNotation !== toolName && server2.toolNameMapping) {
45
+ server2.toolNameMapping.set(dotNotation, toolName);
46
+ server2.toolNameMapping.set(toolName, dotNotation);
47
+ }
48
+ if (underscoreNotation !== toolName && server2.toolNameMapping) {
49
+ server2.toolNameMapping.set(underscoreNotation, toolName);
50
+ server2.toolNameMapping.set(toolName, underscoreNotation);
51
+ }
52
+ return tool;
53
+ }
54
+ });
55
+ tool_name_mapping_plugin_default = createToolNameMappingPlugin();
56
+ }
57
+ });
58
+
59
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/mcpc__core/src/plugins/built-in/logging-plugin.js
60
+ var createLoggingPlugin, logging_plugin_default;
61
+ var init_logging_plugin = __esm({
62
+ "../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/mcpc__core/src/plugins/built-in/logging-plugin.js"() {
63
+ createLoggingPlugin = (options = {}) => {
64
+ const { enabled = true, verbose = false, compact: compact2 = true } = options;
65
+ return {
66
+ name: "built-in-logging",
67
+ composeEnd: (context) => {
68
+ if (!enabled) return;
69
+ if (compact2) {
70
+ const pluginCount = context.pluginNames.length;
71
+ const server2 = context.server;
72
+ const externalList = server2.getExternalToolNames();
73
+ const internalList = server2.getInternalToolNames();
74
+ const hiddenList = server2.getHiddenToolNames();
75
+ const publicToolNames = server2.getPublicToolNames();
76
+ const externalCount = externalList.length;
77
+ const internalCount = internalList.length;
78
+ const hiddenCount = hiddenList.length;
79
+ const globalCount = publicToolNames.length;
80
+ console.log(`\u{1F9E9} [${context.toolName}] ${pluginCount} plugins \u2022 ${externalCount} external \u2022 ${internalCount} internal \u2022 ${hiddenCount} hidden \u2022 ${globalCount} global`);
81
+ } else if (verbose) {
82
+ console.log(`\u{1F9E9} [${context.toolName}]`);
83
+ console.log(` \u251C\u2500 Plugins: ${context.pluginNames.join(", ")}`);
84
+ const server2 = context.server;
85
+ const globalToolNames = Array.from(new Set(server2.getPublicToolNames().map(String)));
86
+ const external = Array.from(new Set(server2.getExternalToolNames().map(String)));
87
+ const internal = Array.from(new Set(server2.getInternalToolNames().map(String)));
88
+ const hidden = Array.from(new Set(server2.getHiddenToolNames().map(String)));
89
+ const globalNames = globalToolNames.map(String);
90
+ const totalSet = /* @__PURE__ */ new Set([
91
+ ...external,
92
+ ...internal,
93
+ ...globalNames
94
+ ]);
95
+ const totalList = Array.from(totalSet);
96
+ if (external.length > 0) {
97
+ console.log(` \u251C\u2500 External: ${external.join(", ")}`);
98
+ }
99
+ if (internal.length > 0) {
100
+ console.log(` \u251C\u2500 Internal: ${internal.join(", ")}`);
101
+ }
102
+ if (globalNames.length > 0) {
103
+ console.log(` \u251C\u2500 Global: ${globalNames.join(", ")}`);
104
+ }
105
+ if (hidden.length > 0) {
106
+ console.log(` \u251C\u2500 Hidden: ${hidden.join(", ")}`);
107
+ }
108
+ if (totalList.length > 0) {
109
+ console.log(` \u2514\u2500 Total: ${totalList.length} tools`);
110
+ }
111
+ }
112
+ }
113
+ };
114
+ };
115
+ logging_plugin_default = createLoggingPlugin({
116
+ verbose: true,
117
+ compact: false
118
+ });
119
+ }
120
+ });
121
+
122
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/mcpc__core/src/plugins/built-in/index.js
123
+ var built_in_exports = {};
124
+ __export(built_in_exports, {
125
+ createConfigPlugin: () => createConfigPlugin,
126
+ createLoggingPlugin: () => createLoggingPlugin,
127
+ createToolNameMappingPlugin: () => createToolNameMappingPlugin,
128
+ getBuiltInPlugins: () => getBuiltInPlugins
129
+ });
130
+ function getBuiltInPlugins() {
131
+ return [
132
+ tool_name_mapping_plugin_default,
133
+ config_plugin_default,
134
+ logging_plugin_default
135
+ ];
136
+ }
137
+ var init_built_in = __esm({
138
+ "../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/mcpc__core/src/plugins/built-in/index.js"() {
139
+ init_config_plugin();
140
+ init_tool_name_mapping_plugin();
141
+ init_logging_plugin();
142
+ init_config_plugin();
143
+ init_tool_name_mapping_plugin();
144
+ init_logging_plugin();
145
+ }
146
+ });
147
+
148
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@mcpc/cli/src/bin.ts
149
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
150
+
151
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@mcpc/cli/src/app.js
152
+ import { OpenAPIHono } from "@hono/zod-openapi";
153
+
154
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@mcpc/cli/src/controllers/messages.controller.js
155
+ import { createRoute } from "@hono/zod-openapi";
156
+ import { z } from "zod";
157
+
158
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/mcpc__utils/src/transport/sse.js
159
+ import { JSONRPCMessageSchema } from "@modelcontextprotocol/sdk/types.js";
160
+
161
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/std__http/server_sent_event_stream.js
162
+ var NEWLINE_REGEXP = /\r\n|\r|\n/;
163
+ var encoder = new TextEncoder();
164
+ function assertHasNoNewline(value, varName, errPrefix) {
165
+ if (value.match(NEWLINE_REGEXP) !== null) {
166
+ throw new SyntaxError(`${errPrefix}: ${varName} cannot contain a newline`);
167
+ }
168
+ }
169
+ function stringify(message) {
170
+ const lines = [];
171
+ if (message.comment) {
172
+ assertHasNoNewline(message.comment, "`message.comment`", "Cannot serialize message");
173
+ lines.push(`:${message.comment}`);
174
+ }
175
+ if (message.event) {
176
+ assertHasNoNewline(message.event, "`message.event`", "Cannot serialize message");
177
+ lines.push(`event:${message.event}`);
178
+ }
179
+ if (message.data) {
180
+ message.data.split(NEWLINE_REGEXP).forEach((line) => lines.push(`data:${line}`));
181
+ }
182
+ if (message.id) {
183
+ assertHasNoNewline(message.id.toString(), "`message.id`", "Cannot serialize message");
184
+ lines.push(`id:${message.id}`);
185
+ }
186
+ if (message.retry) lines.push(`retry:${message.retry}`);
187
+ return encoder.encode(lines.join("\n") + "\n\n");
188
+ }
189
+ var ServerSentEventStream = class extends TransformStream {
190
+ constructor() {
191
+ super({
192
+ transform: (message, controller) => {
193
+ controller.enqueue(stringify(message));
194
+ }
195
+ });
196
+ }
197
+ };
198
+
199
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@mcpc/cli/src/controllers/sse.controller.js
200
+ import { createRoute as createRoute2, z as z2 } from "@hono/zod-openapi";
201
+
202
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/mcpc__core/src/compose.js
203
+ import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
204
+ import { jsonSchema as jsonSchema3 } from "ai";
205
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
206
+
207
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/mcpc__utils/src/json.js
208
+ import { jsonrepair } from "jsonrepair";
209
+ function parseJSON(text, throwError) {
210
+ try {
211
+ return JSON.parse(text);
212
+ } catch (_error) {
213
+ try {
214
+ const repairedText = jsonrepair(text);
215
+ console.warn(`Failed to parse JSON, attempting to repair, result: ${text}`);
216
+ if (throwError) {
217
+ throw _error;
218
+ }
219
+ return JSON.parse(repairedText);
220
+ } catch {
221
+ if (throwError) {
222
+ throw new Error("Failed to parse repaired JSON");
223
+ }
224
+ return null;
225
+ }
226
+ }
227
+ }
228
+
229
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/mcpc__utils/src/ai.js
230
+ var p = (template, options = {}) => {
231
+ const { missingVariableHandling = "warn" } = options;
232
+ const names = /* @__PURE__ */ new Set();
233
+ const regex = /\{((\w|\.)+)\}/g;
234
+ let match;
235
+ while ((match = regex.exec(template)) !== null) {
236
+ names.add(match[1]);
237
+ }
238
+ const required = Array.from(names);
239
+ return (input) => {
240
+ let result = template;
241
+ for (const name of required) {
242
+ const key = name;
243
+ const value = input[key];
244
+ const re = new RegExp(`\\{${String(name)}\\}`, "g");
245
+ if (value !== void 0 && value !== null) {
246
+ result = result.replace(re, String(value));
247
+ } else {
248
+ switch (missingVariableHandling) {
249
+ case "error":
250
+ throw new Error(`Missing variable "${String(name)}" in input for template.`);
251
+ case "empty":
252
+ result = result.replace(re, "");
253
+ break;
254
+ case "warn":
255
+ case "ignore":
256
+ default:
257
+ break;
258
+ }
259
+ }
260
+ }
261
+ return result;
262
+ };
263
+ };
264
+
265
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/mcpc__utils/src/tool-tags.js
266
+ import { load } from "cheerio";
267
+ function parseTags(htmlString, tags) {
268
+ const $ = load(htmlString, {
269
+ xml: {
270
+ decodeEntities: false
271
+ }
272
+ });
273
+ const tagToResults = {};
274
+ for (const tag of tags) {
275
+ const elements = $(tag);
276
+ tagToResults[tag] = elements.toArray();
277
+ }
278
+ return {
279
+ tagToResults,
280
+ $
281
+ };
282
+ }
283
+
284
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/mcpc__core/src/utils/common/mcp.js
285
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
286
+ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
287
+ import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
288
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
289
+
290
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/mcpc__core/src/utils/common/registory.js
291
+ function connectToSmitheryServer(smitheryConfig) {
292
+ const serverUrl = new URL(smitheryConfig.deploymentUrl);
293
+ serverUrl.searchParams.set("config", btoa(JSON.stringify(smitheryConfig.config)));
294
+ serverUrl.searchParams.set("api_key", smitheryConfig?.smitheryApiKey ?? smitheryConfig?.config?.smitheryApiKey);
295
+ return {
296
+ url: serverUrl.toString()
297
+ };
298
+ }
299
+ function smitheryToolNameCompatibale(name, scope) {
300
+ if (!name.startsWith("toolbox_")) {
301
+ return {
302
+ toolNameWithScope: `${scope}.${name}`,
303
+ toolName: name
304
+ };
305
+ }
306
+ const [, ...toolNames] = name.split("_");
307
+ const toolName = toolNames.join("_");
308
+ const toolNameWithScope = `${scope}.${toolName}`;
309
+ return {
310
+ toolNameWithScope,
311
+ toolName
312
+ };
313
+ }
314
+
315
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/mcpc__core/src/utils/common/mcp.js
316
+ import { cwd } from "node:process";
317
+ import process2 from "node:process";
318
+ import { createHash } from "node:crypto";
319
+ var mcpClientPool = /* @__PURE__ */ new Map();
320
+ var mcpClientConnecting = /* @__PURE__ */ new Map();
321
+ var shortHash = (s) => createHash("sha256").update(s).digest("hex").slice(0, 8);
322
+ function defSignature(def) {
323
+ return JSON.stringify(def);
324
+ }
325
+ async function getOrCreateMcpClient(defKey, def) {
326
+ const pooled = mcpClientPool.get(defKey);
327
+ if (pooled) {
328
+ pooled.refCount += 1;
329
+ return pooled.client;
330
+ }
331
+ const existingConnecting = mcpClientConnecting.get(defKey);
332
+ if (existingConnecting) {
333
+ const client = await existingConnecting;
334
+ const entry = mcpClientPool.get(defKey);
335
+ if (entry) entry.refCount += 1;
336
+ return client;
337
+ }
338
+ let transport2;
339
+ if (typeof def.transportType === "string" && def.transportType === "sse") {
340
+ const options = {};
341
+ if (def.headers) {
342
+ options.requestInit = {
343
+ headers: def.headers
344
+ };
345
+ options.eventSourceInit = {
346
+ headers: def.headers
347
+ };
348
+ }
349
+ transport2 = new SSEClientTransport(new URL(def.url), options);
350
+ } else if ("url" in def && typeof def.url === "string") {
351
+ const options = {};
352
+ if (def.headers) {
353
+ options.requestInit = {
354
+ headers: def.headers
355
+ };
356
+ }
357
+ transport2 = new StreamableHTTPClientTransport(new URL(def.url), options);
358
+ } else if (typeof def.transportType === "string" && def.transportType === "stdio" || "command" in def) {
359
+ transport2 = new StdioClientTransport({
360
+ command: def.command,
361
+ args: def.args,
362
+ env: {
363
+ ...process2.env,
364
+ ...def.env ?? {}
365
+ },
366
+ cwd: cwd()
367
+ });
368
+ } else {
369
+ throw new Error(`Unsupported transport type: ${JSON.stringify(def)}`);
370
+ }
371
+ const connecting = (async () => {
372
+ const client = new Client({
373
+ name: `mcp_${shortHash(defSignature(def))}`,
374
+ version: "1.0.0"
375
+ });
376
+ await client.connect(transport2, {
377
+ timeout: 6e4 * 10
378
+ });
379
+ return client;
380
+ })();
381
+ mcpClientConnecting.set(defKey, connecting);
382
+ try {
383
+ const client = await connecting;
384
+ mcpClientPool.set(defKey, {
385
+ client,
386
+ refCount: 1
387
+ });
388
+ return client;
389
+ } finally {
390
+ mcpClientConnecting.delete(defKey);
391
+ }
392
+ }
393
+ async function releaseMcpClient(defKey) {
394
+ const entry = mcpClientPool.get(defKey);
395
+ if (!entry) return;
396
+ entry.refCount -= 1;
397
+ if (entry.refCount <= 0) {
398
+ mcpClientPool.delete(defKey);
399
+ try {
400
+ await entry.client.close();
401
+ } catch (err) {
402
+ console.error("Error closing MCP client:", err);
403
+ }
404
+ }
405
+ }
406
+ var cleanupAllPooledClients = async () => {
407
+ const entries = Array.from(mcpClientPool.entries());
408
+ mcpClientPool.clear();
409
+ await Promise.all(entries.map(async ([, { client }]) => {
410
+ try {
411
+ await client.close();
412
+ } catch (err) {
413
+ console.error("Error closing MCP client:", err);
414
+ }
415
+ }));
416
+ };
417
+ process2.once?.("exit", () => {
418
+ cleanupAllPooledClients();
419
+ });
420
+ process2.once?.("SIGINT", () => {
421
+ cleanupAllPooledClients().finally(() => process2.exit(0));
422
+ });
423
+ async function composeMcpDepTools(mcpConfig, filterIn) {
424
+ const allTools = {};
425
+ const allClients = {};
426
+ const acquiredKeys = [];
427
+ for (const [name, definition] of Object.entries(mcpConfig.mcpServers)) {
428
+ const def = definition;
429
+ if (def.disabled) continue;
430
+ const defKey = shortHash(defSignature(def));
431
+ const serverId = name;
432
+ try {
433
+ const client = await getOrCreateMcpClient(defKey, def);
434
+ acquiredKeys.push(defKey);
435
+ allClients[serverId] = client;
436
+ const { tools } = await client.listTools();
437
+ tools.forEach((tool) => {
438
+ const { toolNameWithScope, toolName: internalToolName } = smitheryToolNameCompatibale(tool.name, name);
439
+ const toolId = `${serverId}_${internalToolName}`;
440
+ if (filterIn && !filterIn({
441
+ action: internalToolName,
442
+ tool,
443
+ mcpName: name,
444
+ toolNameWithScope,
445
+ internalToolName,
446
+ toolId
447
+ })) {
448
+ return;
449
+ }
450
+ const execute = (args) => allClients[serverId].callTool({
451
+ name: internalToolName,
452
+ arguments: args
453
+ }, void 0, {
454
+ timeout: def.toolCallTimeout
455
+ });
456
+ allTools[toolId] = {
457
+ ...tool,
458
+ execute
459
+ };
460
+ });
461
+ } catch (error) {
462
+ console.error(`Error creating MCP client for ${name}:`, error);
463
+ }
464
+ }
465
+ const cleanupClients = async () => {
466
+ await Promise.all(acquiredKeys.map((k) => releaseMcpClient(k)));
467
+ acquiredKeys.length = 0;
468
+ Object.keys(allTools).forEach((key) => delete allTools[key]);
469
+ Object.keys(allClients).forEach((key) => delete allClients[key]);
470
+ };
471
+ return {
472
+ tools: allTools,
473
+ clients: allClients,
474
+ cleanupClients
475
+ };
476
+ }
477
+
478
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/mcpc__core/src/utils/common/schema.js
479
+ import traverse from "json-schema-traverse";
480
+ function updateRefPaths(schema, wrapperPath) {
481
+ if (!schema || typeof schema !== "object") {
482
+ return schema;
483
+ }
484
+ if (!wrapperPath || typeof wrapperPath !== "string") {
485
+ throw new Error("wrapperPath must be a non-empty string");
486
+ }
487
+ const clonedSchema = JSON.parse(JSON.stringify(schema));
488
+ try {
489
+ traverse(clonedSchema, {
490
+ allKeys: true,
491
+ cb: function(schemaNode, _jsonPtr, _rootSchema, _parentJsonPtr, _parentKeyword, _parentSchema, _keyIndex) {
492
+ if (schemaNode && typeof schemaNode === "object" && schemaNode.$ref) {
493
+ const ref = schemaNode.$ref;
494
+ if (ref.startsWith("#/properties/")) {
495
+ const relativePath = ref.substring(13);
496
+ schemaNode.$ref = `#/properties/${wrapperPath}/properties/${relativePath}`;
497
+ } else if (ref === "#") {
498
+ schemaNode.$ref = `#/properties/${wrapperPath}`;
499
+ }
500
+ }
501
+ }
502
+ });
503
+ } catch (error) {
504
+ console.warn(`Failed to traverse schema for path "${wrapperPath}":`, error);
505
+ return clonedSchema;
506
+ }
507
+ return clonedSchema;
508
+ }
509
+
510
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/mcpc__core/src/executors/agentic/agentic-tool-registrar.js
511
+ import { jsonSchema } from "ai";
512
+
513
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/mcpc__core/src/utils/common/config.js
514
+ import process3 from "node:process";
515
+ var GEMINI_PREFERRED_FORMAT = process3.env.GEMINI_PREFERRED_FORMAT === "0" ? false : true;
516
+
517
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/mcpc__core/src/utils/common/json.js
518
+ import { jsonrepair as jsonrepair2 } from "jsonrepair";
519
+ import { inspect } from "node:util";
520
+
521
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/mcpc__core/src/utils/common/provider.js
522
+ var createGoogleCompatibleJSONSchema = (schema) => {
523
+ if (!GEMINI_PREFERRED_FORMAT) {
524
+ return schema;
525
+ }
526
+ const { oneOf: _oneOf, allOf: _allOf, anyOf: _anyOf, ...cleanSchema } = schema;
527
+ const removeAdditionalProperties = (obj) => {
528
+ if (Array.isArray(obj)) {
529
+ return obj.map(removeAdditionalProperties);
530
+ }
531
+ if (obj && typeof obj === "object") {
532
+ const result = {};
533
+ for (const [key, value] of Object.entries(obj)) {
534
+ if (key !== "additionalProperties") {
535
+ result[key] = removeAdditionalProperties(value);
536
+ }
537
+ }
538
+ return result;
539
+ }
540
+ return obj;
541
+ };
542
+ return removeAdditionalProperties(cleanSchema);
543
+ };
544
+
545
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/mcpc__core/src/prompts/index.js
546
+ var SystemPrompts = {
547
+ /**
548
+ * Base system prompt for autonomous MCP execution
549
+ */
550
+ AUTONOMOUS_EXECUTION: `Autonomous AI Agent \`{toolName}\` that answers user questions through iterative self-invocation and collecting feedback.
551
+
552
+ <instructions>{description}</instructions>
553
+
554
+ ## Execution Rules
555
+ 1. **Follow instructions above** carefully
556
+ 2. **Answer user question** as primary goal
557
+ 3. **Execute** one action per call
558
+ 4. **Collect feedback** from each action result
559
+ 5. **Decide** next step:
560
+ - **proceed**: More work needed
561
+ - **complete**: Question answered
562
+ - **retry**: Current action failed
563
+ 6. **Provide** parameter object matching action name
564
+ 7. **Continue** until complete
565
+
566
+ ## Call Format
567
+ \`\`\`json
568
+ {
569
+ "action": "tool_name",
570
+ "decision": "proceed|retry|complete",
571
+ "tool_name": { /* tool parameters */ }
572
+ }
573
+ \`\`\``,
574
+ /**
575
+ * Workflow execution system prompt
576
+ */
577
+ WORKFLOW_EXECUTION: `Agentic workflow execution tool \`{toolName}\` that processes requests through structured multi-step workflows.
578
+
579
+ <instructions>{description}</instructions>
580
+
581
+ ## Workflow Execution Protocol
582
+
583
+ **\u{1F3AF} FIRST CALL (Planning):**
584
+ {planningInstructions}
585
+
586
+ **\u26A1 SUBSEQUENT CALLS (Execution):**
587
+ - Provide ONLY current step parameters
588
+ - **ADVANCE STEP**: Set \`decision: "proceed"\` to move to next step
589
+ - **RETRY STEP**: Set \`decision: "retry"\`
590
+ - **COMPLETE WORKFLOW**: Set \`decision: "complete"\` when ready to finish
591
+
592
+ **\u{1F6AB} Do NOT include \`steps\` parameter during normal execution**
593
+ **\u2705 Include \`steps\` parameter ONLY when restarting workflow with \`init: true\`**
594
+ **\u26A0\uFE0F CRITICAL: When retrying failed steps, MUST use \`decision: "retry"\`**`,
595
+ /**
596
+ * JSON-only execution system prompt
597
+ */
598
+ SAMPLING_EXECUTION: `Autonomous AI Agent \`{toolName}\` that answers user questions by iteratively collecting feedback and adapting your approach.
599
+
600
+ <instructions>{description}</instructions>
601
+
602
+ ## Execution Rules
603
+ - Respond with valid JSON only
604
+ - **Follow instructions above** carefully
605
+ - **Answer user question** as primary goal
606
+ - **Collect feedback** from each action result
607
+ - **Adapt approach** based on gathered information
608
+ - action = "X" \u2192 provide parameter "X"
609
+ - Continue until question answered
610
+
611
+ ## JSON Response Format
612
+ \`\`\`json
613
+ {
614
+ "action": "tool_name",
615
+ "decision": "proceed|retry|complete",
616
+ "tool_name": { /* tool parameters */ }
617
+ }
618
+ \`\`\`
619
+
620
+ ## Available Tools
621
+ {toolList}`,
622
+ /**
623
+ * Sampling workflow execution system prompt combining sampling with workflow capabilities
624
+ */
625
+ SAMPLING_WORKFLOW_EXECUTION: `You are an autonomous AI Agent named \`{toolName}\` that processes instructions through iterative sampling execution within structured workflows.
626
+
627
+ <instructions>{description}</instructions>
628
+
629
+ ## Agentic Sampling Workflow Protocol
630
+
631
+ **\u{1F9E0} AGENTIC REASONING (First Call - Workflow Planning):**
632
+ 1. **Autonomous Analysis:** Independently analyze the user's instruction and identify the end goal
633
+ 2. **Workflow Design:** Autonomously design a structured workflow with clear steps
634
+ 3. **Tool Mapping:** Determine which tools are needed for each workflow step
635
+ 4. **Initialization:** Start the workflow with proper step definitions
636
+
637
+ **\u26A1 AGENTIC EXECUTION RULES (Subsequent Calls):**
638
+ - Each response demonstrates autonomous reasoning and decision-making within workflow context
639
+ - Make self-directed choices about step execution, retry, or advancement
640
+ - Adapt your approach based on previous step results without external guidance
641
+ - Balance workflow structure with autonomous flexibility
642
+
643
+ **\u{1F504} JSON Response Format (Agentic Workflow Decision Output):**
644
+ You MUST respond with a JSON object for workflow execution:
645
+
646
+ **For Workflow Initialization (First Call):**
647
+ - action: "{toolName}"
648
+ - init: true
649
+ - steps: Autonomously designed workflow steps array
650
+ - [other workflow parameters]: As you autonomously determine
651
+
652
+ **For Step Execution (Subsequent Calls):**
653
+ - action: "{toolName}"
654
+ - decision: "proceed" (advance), "retry" (retry), or "complete" (finish - sampling mode only)
655
+ - [step parameters]: Tool-specific parameters you autonomously determine for current step
656
+
657
+ **\u{1F3AF} AGENTIC WORKFLOW CONSTRAINTS:**
658
+ - Response must be pure JSON demonstrating autonomous decision-making within workflow structure
659
+ - Invalid JSON indicates failure in agentic workflow reasoning
660
+ - Tool parameters must reflect your independent analysis and workflow planning
661
+ - Balance autonomous decision-making with structured workflow progression
662
+
663
+ **\u{1F6AB} Do NOT include \`steps\` parameter during normal execution**
664
+ **\u2705 Include \`steps\` parameter ONLY when restarting workflow with \`init: true\`**
665
+ **\u26A0\uFE0F CRITICAL: When retrying failed steps, MUST use \`decision: "retry"\`**`
666
+ };
667
+ var WorkflowPrompts = {
668
+ /**
669
+ * Workflow initialization instructions
670
+ */
671
+ WORKFLOW_INIT: `Workflow initialized with {stepCount} steps. Agent MUST start the workflow with the first step to \`{currentStepDescription}\`.
672
+
673
+ ## EXECUTE tool \`{toolName}\` with the following new parameter definition
674
+
675
+ {schemaDefinition}
676
+
677
+ ## Important Instructions
678
+ - **Include 'steps' parameter ONLY when restarting workflow (with 'init: true')**
679
+ - **Do NOT include 'steps' parameter during normal step execution**
680
+ - **MUST Use the provided JSON schema definition above for parameter generation and validation**
681
+ - **ADVANCE STEP: Set 'decision' to "proceed" to advance to next step**
682
+ - **RETRY STEP: Set 'decision' to "retry" to re-execute current step**
683
+ - **FINAL STEP: Execute normally for workflow completion, do NOT use 'decision: complete' unless workflow is truly finished**
684
+ - **\u26A0\uFE0F CRITICAL: When retrying failed steps, MUST set 'decision' to "retry"**
685
+ - **\u26A0\uFE0F CRITICAL: Only use 'decision: complete' when the entire workflow has been successfully executed**
686
+
687
+ {workflowSteps}`,
688
+ /**
689
+ * Tool description enhancement for workflow mode
690
+ */
691
+ WORKFLOW_TOOL_DESCRIPTION: `{description}
692
+ {initTitle}
693
+ {ensureStepActions}
694
+ {schemaDefinition}`,
695
+ /**
696
+ * Planning instructions for predefined workflows
697
+ */
698
+ PREDEFINED_WORKFLOW_PLANNING: `- Set \`init: true\` (steps are predefined)`,
699
+ /**
700
+ * Planning instructions for dynamic workflows
701
+ */
702
+ DYNAMIC_WORKFLOW_PLANNING: `- Set \`init: true\` and define complete \`steps\` array`,
703
+ /**
704
+ * Next step decision prompt
705
+ */
706
+ NEXT_STEP_DECISION: `**Next Step Decision Required**
707
+
708
+ Previous step completed. Choose your action:
709
+
710
+ **\u{1F504} RETRY Current Step:**
711
+ - Call \`{toolName}\` with current parameters
712
+ - \u26A0\uFE0F CRITICAL: Set \`decision: "retry"\`
713
+
714
+ **\u25B6\uFE0F PROCEED to Next Step:**
715
+ - Call \`{toolName}\` with parameters below
716
+ - Set \`decision: "proceed"\`
717
+
718
+ Next step: \`{nextStepDescription}\`
719
+
720
+ {nextStepSchema}
721
+
722
+ **Important:** Exclude \`steps\` key from parameters`,
723
+ /**
724
+ * Final step completion prompt
725
+ */
726
+ FINAL_STEP_COMPLETION: `**Final Step Complete** {statusIcon}
727
+
728
+ Step executed {statusText}. Choose action:
729
+
730
+ **\u{1F504} RETRY:** Call \`{toolName}\` with \`decision: "retry"\`
731
+ **\u2705 COMPLETE:** Call \`{toolName}\` with \`decision: "complete"\`
732
+ **\u{1F195} NEW:** Call \`{toolName}\` with \`init: true\`{newWorkflowInstructions}`,
733
+ /**
734
+ * Workflow completion success message
735
+ */
736
+ WORKFLOW_COMPLETED: `**Workflow Completed Successfully** \u2705
737
+
738
+ All workflow steps have been executed and the workflow is now complete.
739
+
740
+ **Summary:**
741
+ - Total steps: {totalSteps}
742
+ - All steps executed successfully
743
+
744
+ Agent can now start a new workflow if needed by calling \`{toolName}\` with \`init: true\`{newWorkflowInstructions}.`,
745
+ /**
746
+ * Error messages
747
+ */
748
+ ERRORS: {
749
+ NOT_INITIALIZED: {
750
+ WITH_PREDEFINED: "Error: Workflow not initialized. Please provide 'init' parameter to start a new workflow.",
751
+ WITHOUT_PREDEFINED: "Error: Workflow not initialized. Please provide 'init' and 'steps' parameter to start a new workflow."
752
+ },
753
+ ALREADY_AT_FINAL: "Error: Cannot proceed, already at the final step.",
754
+ CANNOT_COMPLETE_NOT_AT_FINAL: "Error: Cannot complete workflow - you are not at the final step. Please use decision=proceed to continue to the next step.",
755
+ NO_STEPS_PROVIDED: "Error: No steps provided",
756
+ NO_CURRENT_STEP: "Error: No current step to execute"
757
+ }
758
+ };
759
+ var ResponseTemplates = {
760
+ /**
761
+ * Success response for action execution
762
+ */
763
+ ACTION_SUCCESS: `**Action Completed Successfully** \u2705
764
+
765
+ Previous action (\`{currentAction}\`) executed successfully.
766
+
767
+ **Next Action Required:** \`{nextAction}\`
768
+
769
+ Agent MUST call tool \`{toolName}\` again with the \`{nextAction}\` action to continue the autonomous execution sequence.
770
+
771
+ **Instructions:**
772
+ - Analyze the result from previous action: \`{currentAction}\`
773
+ - Execute the next planned action: \`{nextAction}\`
774
+ - Maintain execution context and progress toward the final goal`,
775
+ /**
776
+ * Planning prompt when no next action is specified
777
+ */
778
+ PLANNING_PROMPT: `**Action Evaluation & Planning Required** \u{1F3AF}
779
+
780
+ Previous action (\`{currentAction}\`) completed. You need to determine the next step.
781
+
782
+ **Evaluation & Planning Process:**
783
+ 1. **Analyze Results:** Review the outcome of \`{currentAction}\`
784
+ 2. **Assess Progress:** Determine how close you are to fulfilling the user request
785
+ 3. **Plan Next Action:** Identify the most appropriate next action (if needed)
786
+ 4. **Execute Decision:** Call \`{toolName}\` with the planned action
787
+
788
+ **Options:**
789
+ - **Continue:** If more actions are needed to fulfill the request
790
+ - **Complete:** If the user request has been fully satisfied
791
+
792
+ Choose the next action that best advances toward completing the user's request.`,
793
+ /**
794
+ * Error response template
795
+ */
796
+ ERROR_RESPONSE: `Action argument validation failed: {errorMessage}`,
797
+ WORKFLOW_ERROR_RESPONSE: `Action argument validation failed: {errorMessage}
798
+ Set \`decision: "retry"\` to retry the current step, or check your parameters and try again.`,
799
+ /**
800
+ * Completion message
801
+ */
802
+ COMPLETION_MESSAGE: `Completed, no dependent actions to execute`,
803
+ /**
804
+ * Security validation messages
805
+ */
806
+ SECURITY_VALIDATION: {
807
+ PASSED: `Security validation PASSED for {operation} on {path}`,
808
+ FAILED: `Security validation FAILED for {operation} on {path}`
809
+ },
810
+ /**
811
+ * Audit log messages
812
+ */
813
+ AUDIT_LOG: `Audit log entry created: [{timestamp}] {level}: {action} on {resource}{userInfo}`
814
+ };
815
+ var CompiledPrompts = {
816
+ autonomousExecution: p(SystemPrompts.AUTONOMOUS_EXECUTION),
817
+ workflowExecution: p(SystemPrompts.WORKFLOW_EXECUTION),
818
+ samplingExecution: p(SystemPrompts.SAMPLING_EXECUTION),
819
+ samplingWorkflowExecution: p(SystemPrompts.SAMPLING_WORKFLOW_EXECUTION),
820
+ workflowInit: p(WorkflowPrompts.WORKFLOW_INIT),
821
+ workflowToolDescription: p(WorkflowPrompts.WORKFLOW_TOOL_DESCRIPTION),
822
+ nextStepDecision: p(WorkflowPrompts.NEXT_STEP_DECISION),
823
+ finalStepCompletion: p(WorkflowPrompts.FINAL_STEP_COMPLETION),
824
+ workflowCompleted: p(WorkflowPrompts.WORKFLOW_COMPLETED),
825
+ actionSuccess: p(ResponseTemplates.ACTION_SUCCESS),
826
+ planningPrompt: p(ResponseTemplates.PLANNING_PROMPT),
827
+ errorResponse: p(ResponseTemplates.ERROR_RESPONSE),
828
+ workflowErrorResponse: p(ResponseTemplates.WORKFLOW_ERROR_RESPONSE),
829
+ securityPassed: p(ResponseTemplates.SECURITY_VALIDATION.PASSED),
830
+ securityFailed: p(ResponseTemplates.SECURITY_VALIDATION.FAILED),
831
+ auditLog: p(ResponseTemplates.AUDIT_LOG),
832
+ completionMessage: () => ResponseTemplates.COMPLETION_MESSAGE
833
+ };
834
+ var PromptUtils = {
835
+ /**
836
+ * Generate tool list for descriptions
837
+ */
838
+ generateToolList: (tools) => {
839
+ return tools.filter((tool) => !tool.hide).map((tool) => `<tool name="${tool.name}"${tool.description ? ` description="${tool.description}"` : ""}/>`).join("\n");
840
+ },
841
+ /**
842
+ * Generate hidden tool list for descriptions
843
+ */
844
+ generateHiddenToolList: (tools) => {
845
+ return tools.filter((tool) => tool.hide).map((tool) => `<tool name="${tool.name}" hide/>`).join("\n");
846
+ },
847
+ /**
848
+ * Format workflow steps for display
849
+ */
850
+ formatWorkflowSteps: (steps) => {
851
+ if (!steps.length) return "";
852
+ return `## Workflow Steps
853
+ ${JSON.stringify(steps, null, 2)}`;
854
+ },
855
+ /**
856
+ * Format workflow progress display with status icons
857
+ */
858
+ formatWorkflowProgress: (progressData) => {
859
+ const statusIcons = {
860
+ pending: "\u23F3",
861
+ running: "\u{1F504}",
862
+ completed: "\u2705",
863
+ failed: "\u274C"
864
+ };
865
+ return progressData.steps.map((step, index) => {
866
+ const status = progressData.statuses[index] || "pending";
867
+ const icon = statusIcons[status] || "\u23F3";
868
+ const current = index === progressData.currentStepIndex ? " **[CURRENT]**" : "";
869
+ const actions = step.actions.length > 0 ? ` | Action: ${step.actions.join(", ")}` : "";
870
+ return `${icon} **Step ${index + 1}:** ${step.description}${actions}${current}`;
871
+ }).join("\n");
872
+ },
873
+ /**
874
+ * Generate user info for audit logs
875
+ */
876
+ formatUserInfo: (user) => {
877
+ return user ? ` by ${user}` : "";
878
+ },
879
+ /**
880
+ * Format timestamp for logs
881
+ */
882
+ formatTimestamp: () => {
883
+ return (/* @__PURE__ */ new Date()).toISOString();
884
+ }
885
+ };
886
+
887
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/mcpc__core/src/executors/agentic/agentic-executor.js
888
+ import { Ajv } from "ajv";
889
+ import { AggregateAjvError } from "@segment/ajv-human-errors";
890
+ import addFormats from "ajv-formats";
891
+ var ajv = new Ajv({
892
+ allErrors: true,
893
+ verbose: true
894
+ });
895
+ addFormats(ajv);
896
+ var AgenticExecutor = class {
897
+ name;
898
+ allToolNames;
899
+ toolNameToDetailList;
900
+ server;
901
+ ACTION_KEY;
902
+ NEXT_ACTION_KEY;
903
+ constructor(name, allToolNames, toolNameToDetailList, server2, ACTION_KEY = "action", NEXT_ACTION_KEY = "nextAction") {
904
+ this.name = name;
905
+ this.allToolNames = allToolNames;
906
+ this.toolNameToDetailList = toolNameToDetailList;
907
+ this.server = server2;
908
+ this.ACTION_KEY = ACTION_KEY;
909
+ this.NEXT_ACTION_KEY = NEXT_ACTION_KEY;
910
+ }
911
+ async execute(args, schema) {
912
+ const validationResult = this.validate(args, schema);
913
+ if (!validationResult.valid) {
914
+ return {
915
+ content: [
916
+ {
917
+ type: "text",
918
+ text: CompiledPrompts.errorResponse({
919
+ errorMessage: validationResult.error || "Validation failed"
920
+ })
921
+ }
922
+ ],
923
+ isError: true
924
+ };
925
+ }
926
+ const actionName = args[this.ACTION_KEY];
927
+ const currentTool = this.toolNameToDetailList.find(([name, _detail]) => name === actionName)?.[1];
928
+ if (currentTool) {
929
+ const nextAction = args[this.NEXT_ACTION_KEY];
930
+ const currentResult = await currentTool.execute({
931
+ ...args[actionName]
932
+ });
933
+ if (args[nextAction]) {
934
+ currentResult?.content?.push({
935
+ type: "text",
936
+ text: CompiledPrompts.actionSuccess({
937
+ toolName: this.name,
938
+ nextAction,
939
+ currentAction: actionName
940
+ })
941
+ });
942
+ } else {
943
+ currentResult?.content?.push({
944
+ type: "text",
945
+ text: CompiledPrompts.planningPrompt({
946
+ currentAction: actionName
947
+ })
948
+ });
949
+ }
950
+ return currentResult;
951
+ }
952
+ if (this.allToolNames.includes(actionName)) {
953
+ try {
954
+ const result = await this.server.callTool(actionName, args[actionName]);
955
+ const nextAction = args[this.NEXT_ACTION_KEY];
956
+ const callToolResult = result ?? {
957
+ content: []
958
+ };
959
+ if (nextAction && this.allToolNames.includes(nextAction)) {
960
+ callToolResult.content.push({
961
+ type: "text",
962
+ text: CompiledPrompts.actionSuccess({
963
+ toolName: this.name,
964
+ nextAction,
965
+ currentAction: actionName
966
+ })
967
+ });
968
+ } else {
969
+ callToolResult.content.push({
970
+ type: "text",
971
+ text: CompiledPrompts.planningPrompt({
972
+ currentAction: actionName
973
+ })
974
+ });
975
+ }
976
+ return callToolResult;
977
+ } catch (error) {
978
+ return {
979
+ content: [
980
+ {
981
+ type: "text",
982
+ text: `Error executing internal tool ${actionName}: ${error instanceof Error ? error.message : String(error)}`
983
+ }
984
+ ],
985
+ isError: true
986
+ };
987
+ }
988
+ }
989
+ return {
990
+ content: [
991
+ {
992
+ type: "text",
993
+ text: CompiledPrompts.completionMessage()
994
+ }
995
+ ]
996
+ };
997
+ }
998
+ // Validate arguments using JSON schema
999
+ validate(args, schema) {
1000
+ if (args.decision === "complete") {
1001
+ return {
1002
+ valid: true
1003
+ };
1004
+ }
1005
+ const validate = ajv.compile(schema);
1006
+ if (!validate(args)) {
1007
+ const errors = new AggregateAjvError(validate.errors);
1008
+ return {
1009
+ valid: false,
1010
+ error: errors.message
1011
+ };
1012
+ }
1013
+ return {
1014
+ valid: true
1015
+ };
1016
+ }
1017
+ };
1018
+
1019
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/es-toolkit__es-toolkit/src/function/partial.js
1020
+ function partial(func, ...partialArgs) {
1021
+ return partialImpl(func, placeholderSymbol, ...partialArgs);
1022
+ }
1023
+ function partialImpl(func, placeholder, ...partialArgs) {
1024
+ const partialed = function(...providedArgs) {
1025
+ let providedArgsIndex = 0;
1026
+ const substitutedArgs = partialArgs.slice().map((arg) => arg === placeholder ? providedArgs[providedArgsIndex++] : arg);
1027
+ const remainingArgs = providedArgs.slice(providedArgsIndex);
1028
+ return func.apply(this, substitutedArgs.concat(remainingArgs));
1029
+ };
1030
+ if (func.prototype) {
1031
+ partialed.prototype = Object.create(func.prototype);
1032
+ }
1033
+ return partialed;
1034
+ }
1035
+ var placeholderSymbol = Symbol("partial.placeholder");
1036
+ partial.placeholder = placeholderSymbol;
1037
+
1038
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/es-toolkit__es-toolkit/src/function/partialRight.js
1039
+ function partialRight(func, ...partialArgs) {
1040
+ return partialRightImpl(func, placeholderSymbol2, ...partialArgs);
1041
+ }
1042
+ function partialRightImpl(func, placeholder, ...partialArgs) {
1043
+ const partialedRight = function(...providedArgs) {
1044
+ const placeholderLength = partialArgs.filter((arg) => arg === placeholder).length;
1045
+ const rangeLength = Math.max(providedArgs.length - placeholderLength, 0);
1046
+ const remainingArgs = providedArgs.slice(0, rangeLength);
1047
+ let providedArgsIndex = rangeLength;
1048
+ const substitutedArgs = partialArgs.slice().map((arg) => arg === placeholder ? providedArgs[providedArgsIndex++] : arg);
1049
+ return func.apply(this, remainingArgs.concat(substitutedArgs));
1050
+ };
1051
+ if (func.prototype) {
1052
+ partialedRight.prototype = Object.create(func.prototype);
1053
+ }
1054
+ return partialedRight;
1055
+ }
1056
+ var placeholderSymbol2 = Symbol("partialRight.placeholder");
1057
+ partialRight.placeholder = placeholderSymbol2;
1058
+
1059
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/es-toolkit__es-toolkit/src/function/retry.js
1060
+ var DEFAULT_RETRIES = Number.POSITIVE_INFINITY;
1061
+
1062
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/es-toolkit__es-toolkit/src/object/pick.js
1063
+ function pick(obj, keys) {
1064
+ const result = {};
1065
+ for (let i = 0; i < keys.length; i++) {
1066
+ const key = keys[i];
1067
+ if (Object.hasOwn(obj, key)) {
1068
+ result[key] = obj[key];
1069
+ }
1070
+ }
1071
+ return result;
1072
+ }
1073
+
1074
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/es-toolkit__es-toolkit/src/string/deburr.js
1075
+ var deburrMap = new Map(
1076
+ // eslint-disable-next-line no-restricted-syntax
1077
+ Object.entries({
1078
+ \u00C6: "Ae",
1079
+ \u00D0: "D",
1080
+ \u00D8: "O",
1081
+ \u00DE: "Th",
1082
+ \u00DF: "ss",
1083
+ \u00E6: "ae",
1084
+ \u00F0: "d",
1085
+ \u00F8: "o",
1086
+ \u00FE: "th",
1087
+ \u0110: "D",
1088
+ \u0111: "d",
1089
+ \u0126: "H",
1090
+ \u0127: "h",
1091
+ \u0131: "i",
1092
+ \u0132: "IJ",
1093
+ \u0133: "ij",
1094
+ \u0138: "k",
1095
+ \u013F: "L",
1096
+ \u0140: "l",
1097
+ \u0141: "L",
1098
+ \u0142: "l",
1099
+ \u0149: "'n",
1100
+ \u014A: "N",
1101
+ \u014B: "n",
1102
+ \u0152: "Oe",
1103
+ \u0153: "oe",
1104
+ \u0166: "T",
1105
+ \u0167: "t",
1106
+ \u017F: "s"
1107
+ })
1108
+ );
1109
+
1110
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/mcpc__core/src/factories/args-def-factory.js
1111
+ var DECISION_OPTIONS = {
1112
+ RETRY: "retry",
1113
+ PROCEED: "proceed",
1114
+ COMPLETE: "complete"
1115
+ };
1116
+ function createArgsDefFactory(name, allToolNames, depGroups, predefinedSteps, ensureStepActions) {
1117
+ const formatEnsureStepActions = () => {
1118
+ if (!ensureStepActions || ensureStepActions.length === 0) {
1119
+ return "";
1120
+ }
1121
+ return `
1122
+
1123
+ ## Required Actions
1124
+ The workflow MUST include at least one of these actions:
1125
+ ${ensureStepActions.map((action) => `- \`${action}\``).join("\n")}`;
1126
+ };
1127
+ return {
1128
+ common: (extra, optionalFields = []) => {
1129
+ const requiredFields = Object.keys(extra).filter((key) => !optionalFields.includes(key));
1130
+ return {
1131
+ type: "object",
1132
+ description: `**Tool parameters dynamically update per workflow step**`,
1133
+ properties: {
1134
+ ...extra
1135
+ },
1136
+ required: requiredFields
1137
+ };
1138
+ },
1139
+ steps: () => ({
1140
+ type: "array",
1141
+ description: `
1142
+ Workflow step definitions - provide ONLY on initial call.
1143
+
1144
+ **CRITICAL RULES:**
1145
+ - **Sequential Dependency:** If Action B depends on Action A's result \u2192 separate steps
1146
+ - **Concurrent Actions:** Independent actions can share one step
1147
+ - **Complete Mapping:** Include ALL requested operations
1148
+ - **Predefined Steps:** Leave unspecified if predefined steps exist
1149
+
1150
+ **BEST PRACTICES:**
1151
+ - Atomic, focused steps
1152
+ - Idempotent actions for safe retries
1153
+ - Clear step descriptions with input/output context`,
1154
+ items: {
1155
+ type: "object",
1156
+ description: `A single step containing actions that execute concurrently. All actions in this step run simultaneously with no guaranteed order.`,
1157
+ properties: {
1158
+ description: {
1159
+ type: "string",
1160
+ description: `**Step purpose, required inputs, and expected outputs**`
1161
+ },
1162
+ actions: {
1163
+ type: "array",
1164
+ description: `Array of action names for this step. **CURRENT LIMITATION: Only 1 action per step is allowed.** Action names must match available tool names exactly.`,
1165
+ items: {
1166
+ ...{
1167
+ enum: allToolNames
1168
+ },
1169
+ type: "string",
1170
+ description: `Individual action name from available tools. Must be exactly one of the allowed tool names.`
1171
+ },
1172
+ uniqueItems: true,
1173
+ minItems: 0,
1174
+ // TODO: remove this restriction when workflow planning is good enough
1175
+ maxItems: 1
1176
+ }
1177
+ },
1178
+ required: [
1179
+ "description",
1180
+ "actions"
1181
+ ],
1182
+ additionalProperties: false
1183
+ },
1184
+ default: predefinedSteps ? predefinedSteps : void 0,
1185
+ minItems: 1
1186
+ }),
1187
+ init: () => ({
1188
+ type: "boolean",
1189
+ description: `Init a new workflow`,
1190
+ enum: [
1191
+ true
1192
+ ]
1193
+ }),
1194
+ decision: () => ({
1195
+ type: "string",
1196
+ enum: Object.values(DECISION_OPTIONS),
1197
+ description: `**Step control: \`${DECISION_OPTIONS.PROCEED}\` = next step, \`${DECISION_OPTIONS.RETRY}\` = retry/repeat current, \`${DECISION_OPTIONS.COMPLETE}\` = finish workflow**`
1198
+ }),
1199
+ action: () => ({
1200
+ type: "string",
1201
+ description: "Define the current workflow action to be performed",
1202
+ enum: allToolNames,
1203
+ required: [
1204
+ "action"
1205
+ ]
1206
+ }),
1207
+ forTool: function() {
1208
+ return this.common({});
1209
+ },
1210
+ forCurrentState: function(state) {
1211
+ const currentStep = state.getCurrentStep();
1212
+ if (!state.isWorkflowInitialized() || !currentStep) {
1213
+ state.reset();
1214
+ const initSchema = {
1215
+ init: this.init()
1216
+ };
1217
+ if (!predefinedSteps) {
1218
+ initSchema.steps = this.steps();
1219
+ }
1220
+ return this.common(initSchema);
1221
+ }
1222
+ const stepDependencies = {
1223
+ ...pick(depGroups, currentStep.actions)
1224
+ };
1225
+ stepDependencies["decision"] = this.decision();
1226
+ stepDependencies["action"] = this.action();
1227
+ return this.common(stepDependencies);
1228
+ },
1229
+ forSampling: function() {
1230
+ return {
1231
+ type: "object",
1232
+ description: "Provide user request for autonomous tool execution",
1233
+ properties: {
1234
+ userRequest: {
1235
+ type: "string",
1236
+ description: "The task or request that should be completed autonomously by the agentic system using available tools"
1237
+ }
1238
+ },
1239
+ required: [
1240
+ "userRequest"
1241
+ ]
1242
+ };
1243
+ },
1244
+ forAgentic: function(toolNameToDetailList, _sampling = false, ACTION_KEY = "action", NEXT_ACTION_KEY = "nextAction") {
1245
+ const allOf = toolNameToDetailList.map(([toolName, _toolDetail]) => {
1246
+ return {
1247
+ if: {
1248
+ properties: {
1249
+ [ACTION_KEY]: {
1250
+ const: toolName
1251
+ }
1252
+ },
1253
+ required: [
1254
+ ACTION_KEY
1255
+ ]
1256
+ },
1257
+ then: {
1258
+ required: [
1259
+ toolName
1260
+ ]
1261
+ }
1262
+ };
1263
+ });
1264
+ const actionDescription = `Specifies the action to be performed from the enum. **\u26A0\uFE0F When setting \`action: "example_action"\`, you MUST also provide \`"example_action": { ... }\`**`;
1265
+ const baseProperties = {
1266
+ [ACTION_KEY]: {
1267
+ type: "string",
1268
+ enum: allToolNames,
1269
+ description: actionDescription
1270
+ },
1271
+ [NEXT_ACTION_KEY]: {
1272
+ type: "string",
1273
+ enum: allToolNames,
1274
+ description: "Optional: Specify the next action to execute. Only include this when you know additional actions are needed after the current one completes."
1275
+ },
1276
+ decision: this.decision(),
1277
+ ...depGroups
1278
+ };
1279
+ const requiredFields = [
1280
+ ACTION_KEY,
1281
+ "decision"
1282
+ ];
1283
+ const schema = {
1284
+ additionalProperties: false,
1285
+ type: "object",
1286
+ properties: baseProperties,
1287
+ required: requiredFields
1288
+ };
1289
+ if (allOf.length > 0) {
1290
+ schema.allOf = allOf;
1291
+ }
1292
+ return schema;
1293
+ },
1294
+ forNextState: function(state) {
1295
+ if (!state.isWorkflowInitialized() || !state.hasNextStep()) {
1296
+ throw new Error(`Cannot get next state schema: no next step available`);
1297
+ }
1298
+ const currentStepIndex = state.getCurrentStepIndex();
1299
+ const allSteps = state.getSteps();
1300
+ const nextStep = allSteps[currentStepIndex + 1];
1301
+ if (!nextStep) {
1302
+ throw new Error(`Next step not found`);
1303
+ }
1304
+ const stepDependencies = {
1305
+ ...pick(depGroups, nextStep.actions)
1306
+ };
1307
+ stepDependencies["decision"] = this.decision();
1308
+ stepDependencies["action"] = this.action();
1309
+ return this.common(stepDependencies);
1310
+ },
1311
+ forToolDescription: function(description, state) {
1312
+ const enforceToolArgs = this.forCurrentState(state);
1313
+ const initTitle = predefinedSteps ? `**YOU MUST execute this tool with following tool arguments to init the workflow**
1314
+ NOTE: The \`steps\` has been predefined` : `**You MUST execute this tool with following tool arguments to plan and init the workflow**`;
1315
+ return CompiledPrompts.workflowToolDescription({
1316
+ description,
1317
+ initTitle,
1318
+ ensureStepActions: formatEnsureStepActions(),
1319
+ schemaDefinition: JSON.stringify(enforceToolArgs, null, 2)
1320
+ });
1321
+ },
1322
+ forInitialStepDescription: function(steps, state) {
1323
+ return CompiledPrompts.workflowInit({
1324
+ stepCount: steps.length.toString(),
1325
+ currentStepDescription: state.getCurrentStep()?.description || "",
1326
+ toolName: name,
1327
+ schemaDefinition: JSON.stringify(this.forCurrentState(state), null, 2),
1328
+ // Remove redundant workflow steps display
1329
+ workflowSteps: ""
1330
+ });
1331
+ }
1332
+ };
1333
+ }
1334
+
1335
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/mcpc__core/src/executors/sampling/base-sampling-executor.js
1336
+ import { Ajv as Ajv2 } from "ajv";
1337
+ import { AggregateAjvError as AggregateAjvError2 } from "@segment/ajv-human-errors";
1338
+ import addFormats2 from "ajv-formats";
1339
+ import { inspect as inspect2 } from "node:util";
1340
+ var ajv2 = new Ajv2({
1341
+ allErrors: true,
1342
+ verbose: true
1343
+ });
1344
+ addFormats2(ajv2);
1345
+ var BaseSamplingExecutor = class {
1346
+ name;
1347
+ description;
1348
+ allToolNames;
1349
+ toolNameToDetailList;
1350
+ server;
1351
+ conversationHistory;
1352
+ maxIterations;
1353
+ currentIteration;
1354
+ constructor(name, description, allToolNames, toolNameToDetailList, server2, config2) {
1355
+ this.name = name;
1356
+ this.description = description;
1357
+ this.allToolNames = allToolNames;
1358
+ this.toolNameToDetailList = toolNameToDetailList;
1359
+ this.server = server2;
1360
+ this.conversationHistory = [];
1361
+ this.maxIterations = 33;
1362
+ this.currentIteration = 0;
1363
+ if (config2?.maxIterations) {
1364
+ this.maxIterations = config2.maxIterations;
1365
+ }
1366
+ }
1367
+ async runSamplingLoop(systemPrompt, schema, state) {
1368
+ this.conversationHistory = [];
1369
+ try {
1370
+ for (this.currentIteration = 0; this.currentIteration < this.maxIterations; this.currentIteration++) {
1371
+ const response = await this.server.createMessage({
1372
+ systemPrompt: systemPrompt(),
1373
+ messages: this.conversationHistory,
1374
+ maxTokens: Number.MAX_SAFE_INTEGER
1375
+ });
1376
+ const responseContent = response.content.text || "{}";
1377
+ let parsedData;
1378
+ try {
1379
+ parsedData = parseJSON(responseContent.trim(), true);
1380
+ } catch (parseError) {
1381
+ this.addParsingErrorToHistory(responseContent, parseError);
1382
+ continue;
1383
+ }
1384
+ if (parsedData) {
1385
+ this.conversationHistory.push({
1386
+ role: "assistant",
1387
+ content: {
1388
+ type: "text",
1389
+ text: JSON.stringify(parsedData, null, 2)
1390
+ }
1391
+ });
1392
+ }
1393
+ const result = await this.processAction(parsedData, schema, state);
1394
+ this.logIterationProgress(parsedData, result);
1395
+ if (result.isError) {
1396
+ this.conversationHistory.push({
1397
+ role: "user",
1398
+ content: {
1399
+ type: "text",
1400
+ text: result.content[0].text
1401
+ }
1402
+ });
1403
+ continue;
1404
+ }
1405
+ if (result.isComplete) {
1406
+ return result;
1407
+ }
1408
+ }
1409
+ return this.createMaxIterationsError();
1410
+ } catch (error) {
1411
+ return this.createExecutionError(error);
1412
+ }
1413
+ }
1414
+ addParsingErrorToHistory(responseText, parseError) {
1415
+ this.conversationHistory.push({
1416
+ role: "assistant",
1417
+ content: {
1418
+ type: "text",
1419
+ text: `JSON parsing failed. Response was: ${responseText}`
1420
+ }
1421
+ });
1422
+ this.conversationHistory.push({
1423
+ role: "user",
1424
+ content: {
1425
+ type: "text",
1426
+ text: CompiledPrompts.errorResponse({
1427
+ errorMessage: `JSON parsing failed: ${parseError instanceof Error ? parseError.message : String(parseError)}
1428
+
1429
+ Please respond with valid JSON.`
1430
+ })
1431
+ }
1432
+ });
1433
+ }
1434
+ createMaxIterationsError() {
1435
+ const result = this.createCompletionResult(`Action argument validation failed: Execution reached maximum iterations (${this.maxIterations}). Please try with a more specific request or break down the task into smaller parts.`);
1436
+ return {
1437
+ ...result,
1438
+ isError: true,
1439
+ isComplete: false
1440
+ };
1441
+ }
1442
+ createExecutionError(error) {
1443
+ const errorMessage = `Sampling execution error: ${error instanceof Error ? error.message : String(error)}`;
1444
+ const result = this.createCompletionResult(errorMessage);
1445
+ return {
1446
+ ...result,
1447
+ isError: true,
1448
+ isComplete: false
1449
+ };
1450
+ }
1451
+ createCompletionResult(text) {
1452
+ const conversationDetails = this.getConversationDetails();
1453
+ return {
1454
+ content: [
1455
+ {
1456
+ type: "text",
1457
+ text: `Task Completed
1458
+ ${text}
1459
+ **Execution Summary:**
1460
+ - Iterations used: ${this.currentIteration + 1}/${this.maxIterations}
1461
+ - Agent: ${this.name}${conversationDetails}`
1462
+ }
1463
+ ],
1464
+ isError: false,
1465
+ isComplete: true
1466
+ };
1467
+ }
1468
+ getConversationDetails() {
1469
+ if (this.conversationHistory.length === 0) {
1470
+ return "\n\n**No conversation history available**";
1471
+ }
1472
+ let details = "\n\n**Detailed Conversation History:**";
1473
+ this.conversationHistory.forEach((message) => {
1474
+ if (message.role === "assistant") {
1475
+ try {
1476
+ const parsed = JSON.parse(message.content.text);
1477
+ details += "\n```json\n" + JSON.stringify(parsed, null, 2) + "\n```";
1478
+ } catch {
1479
+ details += "\n```\n" + message.content.text + "\n```";
1480
+ }
1481
+ } else {
1482
+ details += "\n```\n" + message.content.text + "\n```";
1483
+ }
1484
+ });
1485
+ return details;
1486
+ }
1487
+ logIterationProgress(parsedData, result) {
1488
+ console.log(`Iteration ${this.currentIteration + 1}/${this.maxIterations}:`, {
1489
+ parsedData,
1490
+ isError: result.isError,
1491
+ isComplete: result.isComplete,
1492
+ result: inspect2(result, {
1493
+ depth: 5,
1494
+ maxArrayLength: 10,
1495
+ breakLength: 120,
1496
+ compact: true,
1497
+ maxStringLength: 120
1498
+ })
1499
+ });
1500
+ }
1501
+ injectJsonInstruction({ prompt, schema, schemaPrefix = "JSON schema:", schemaSuffix = `STRICT REQUIREMENTS:
1502
+ 1. Return ONLY raw JSON that passes JSON.parse() - no markdown, code blocks, explanatory text, or extra characters
1503
+ 2. Include ALL required fields with correct data types and satisfy ALL schema constraints (anyOf, oneOf, allOf, not, enum, pattern, min/max, conditionals)
1504
+ 3. Your response must be the JSON object itself, nothing else
1505
+
1506
+ INVALID: \`\`\`json{"key":"value"}\`\`\` or "Here is: {"key":"value"}"
1507
+ VALID: {"key":"value"}` }) {
1508
+ return [
1509
+ prompt != null && prompt.length > 0 ? prompt : void 0,
1510
+ prompt != null && prompt.length > 0 ? "" : void 0,
1511
+ schemaPrefix,
1512
+ schema != null ? JSON.stringify(schema, null, 2) : void 0,
1513
+ schemaSuffix
1514
+ ].filter((line) => line != null).join("\n");
1515
+ }
1516
+ // Validate arguments using JSON schema
1517
+ validateSchema(args, schema) {
1518
+ const validate = ajv2.compile(schema);
1519
+ if (!validate(args)) {
1520
+ const errors = new AggregateAjvError2(validate.errors);
1521
+ return {
1522
+ valid: false,
1523
+ error: errors.message
1524
+ };
1525
+ }
1526
+ return {
1527
+ valid: true
1528
+ };
1529
+ }
1530
+ };
1531
+
1532
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/mcpc__core/src/executors/sampling/agentic-sampling-executor.js
1533
+ var SamplingExecutor = class extends BaseSamplingExecutor {
1534
+ agenticExecutor;
1535
+ constructor(name, description, allToolNames, toolNameToDetailList, server2, config2) {
1536
+ super(name, description, allToolNames, toolNameToDetailList, server2, config2);
1537
+ this.agenticExecutor = new AgenticExecutor(name, allToolNames, toolNameToDetailList, server2);
1538
+ }
1539
+ buildDepGroups() {
1540
+ const depGroups = {};
1541
+ this.toolNameToDetailList.forEach(([toolName, tool]) => {
1542
+ if (tool?.inputSchema) {
1543
+ depGroups[toolName] = {
1544
+ type: "object",
1545
+ description: tool.description || `Tool: ${toolName}`,
1546
+ ...tool.inputSchema
1547
+ };
1548
+ } else {
1549
+ const toolSchema = this.server.getInternalToolSchema(toolName);
1550
+ if (toolSchema) {
1551
+ depGroups[toolName] = {
1552
+ ...toolSchema.schema,
1553
+ description: toolSchema.description
1554
+ };
1555
+ }
1556
+ }
1557
+ });
1558
+ return depGroups;
1559
+ }
1560
+ executeSampling(args, schema) {
1561
+ const validationResult = this.validateSchema(args, schema);
1562
+ if (!validationResult.valid) {
1563
+ return {
1564
+ content: [
1565
+ {
1566
+ type: "text",
1567
+ text: CompiledPrompts.errorResponse({
1568
+ errorMessage: validationResult.error || "Validation failed"
1569
+ })
1570
+ }
1571
+ ],
1572
+ isError: true
1573
+ };
1574
+ }
1575
+ const createArgsDef = createArgsDefFactory(this.name, this.allToolNames, this.buildDepGroups(), void 0, void 0);
1576
+ const agenticSchema = createArgsDef.forAgentic(this.toolNameToDetailList, true);
1577
+ const systemPrompt = this.buildSystemPrompt(args.userRequest, agenticSchema);
1578
+ return this.runSamplingLoop(() => systemPrompt, agenticSchema);
1579
+ }
1580
+ async processAction(parsedData, schema) {
1581
+ const toolCallData = parsedData;
1582
+ if (toolCallData.decision === "complete") {
1583
+ return this.createCompletionResult("Task completed");
1584
+ }
1585
+ try {
1586
+ const { action: _action, decision: _decision, ..._toolArgs } = toolCallData;
1587
+ const toolResult = await this.agenticExecutor.execute(toolCallData, schema);
1588
+ const resultText = toolResult.content?.filter((content) => content.type === "text")?.map((content) => content.text)?.join("\n") || "No result";
1589
+ this.conversationHistory.push({
1590
+ role: "assistant",
1591
+ content: {
1592
+ type: "text",
1593
+ text: resultText
1594
+ }
1595
+ });
1596
+ return toolResult;
1597
+ } catch (error) {
1598
+ return this.createExecutionError(error);
1599
+ }
1600
+ }
1601
+ buildSystemPrompt(userRequest, agenticSchema) {
1602
+ const toolList = this.allToolNames.map((name) => {
1603
+ const tool = this.toolNameToDetailList.find(([toolName]) => toolName === name);
1604
+ const toolSchema = this.server.getInternalToolSchema(name);
1605
+ if (tool && tool[1]) {
1606
+ return `- ${name}: ${tool[1].description || `Tool: ${name}`}`;
1607
+ } else if (toolSchema) {
1608
+ return `- ${name}: ${toolSchema.description}`;
1609
+ }
1610
+ return `- ${name}`;
1611
+ }).join("\n");
1612
+ const basePrompt = CompiledPrompts.samplingExecution({
1613
+ toolName: this.name,
1614
+ description: this.description,
1615
+ toolList
1616
+ });
1617
+ const taskPrompt = `
1618
+
1619
+ ## Current Task
1620
+ I will now use agentic sampling to complete the following task: "${userRequest}"
1621
+
1622
+ When I need to use a tool, I should specify the tool name in 'action' and provide tool-specific parameters as additional properties.
1623
+ When the task is complete, I should use "action": "complete".`;
1624
+ return this.injectJsonInstruction({
1625
+ prompt: basePrompt + taskPrompt,
1626
+ schema: agenticSchema
1627
+ });
1628
+ }
1629
+ };
1630
+
1631
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/mcpc__core/src/executors/agentic/agentic-tool-registrar.js
1632
+ function registerAgenticTool(server2, { description, name, allToolNames, depGroups, toolNameToDetailList, sampling = false }) {
1633
+ const createArgsDef = createArgsDefFactory(name, allToolNames, depGroups, void 0, void 0);
1634
+ const isSamplingMode = sampling === true || typeof sampling === "object";
1635
+ const samplingConfig = typeof sampling === "object" ? sampling : void 0;
1636
+ const agenticExecutor = new AgenticExecutor(name, allToolNames, toolNameToDetailList, server2);
1637
+ const samplingExecutor = new SamplingExecutor(name, description, allToolNames, toolNameToDetailList, server2, samplingConfig);
1638
+ description = isSamplingMode ? CompiledPrompts.samplingExecution({
1639
+ toolName: name,
1640
+ description,
1641
+ toolList: allToolNames.map((name2) => `- ${name2}`).join("\n")
1642
+ }) : CompiledPrompts.autonomousExecution({
1643
+ toolName: name,
1644
+ description
1645
+ });
1646
+ const agenticArgsDef = createArgsDef.forAgentic(toolNameToDetailList, false);
1647
+ const argsDef = isSamplingMode ? createArgsDef.forSampling() : agenticArgsDef;
1648
+ const schema = allToolNames.length > 0 ? argsDef : {
1649
+ type: "object",
1650
+ properties: {}
1651
+ };
1652
+ server2.tool(name, description, jsonSchema(createGoogleCompatibleJSONSchema(schema)), async (args) => {
1653
+ if (isSamplingMode) {
1654
+ return await samplingExecutor.executeSampling(args, schema);
1655
+ } else {
1656
+ return await agenticExecutor.execute(args, schema);
1657
+ }
1658
+ });
1659
+ }
1660
+
1661
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/mcpc__core/src/executors/workflow/workflow-tool-registrar.js
1662
+ import { jsonSchema as jsonSchema2 } from "ai";
1663
+
1664
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/mcpc__core/src/utils/state.js
1665
+ var WorkflowState = class {
1666
+ currentStepIndex = -1;
1667
+ steps = [];
1668
+ stepStatuses = [];
1669
+ stepResults = [];
1670
+ stepErrors = [];
1671
+ isInitialized = false;
1672
+ isStarted = false;
1673
+ constructor(steps) {
1674
+ if (steps) {
1675
+ this.initialize(steps);
1676
+ }
1677
+ }
1678
+ getCurrentStepIndex() {
1679
+ return this.currentStepIndex;
1680
+ }
1681
+ getSteps() {
1682
+ return this.steps;
1683
+ }
1684
+ isWorkflowInitialized() {
1685
+ return this.isInitialized;
1686
+ }
1687
+ getCurrentStep() {
1688
+ if (!this.isInitialized || this.currentStepIndex < 0) {
1689
+ return null;
1690
+ }
1691
+ return this.steps[this.currentStepIndex] || null;
1692
+ }
1693
+ getNextStep() {
1694
+ if (!this.isInitialized) return null;
1695
+ const nextIndex = this.currentStepIndex + 1;
1696
+ return this.steps[nextIndex] || null;
1697
+ }
1698
+ // Get the previous step in the workflow
1699
+ getPreviousStep() {
1700
+ if (!this.isInitialized) return null;
1701
+ const prevIndex = this.currentStepIndex - 1;
1702
+ return this.steps[prevIndex] || null;
1703
+ }
1704
+ hasNextStep() {
1705
+ return this.getNextStep() !== null;
1706
+ }
1707
+ // Check if there is a previous step available
1708
+ hasPreviousStep() {
1709
+ return this.getPreviousStep() !== null;
1710
+ }
1711
+ // Check if currently at the first step
1712
+ isAtFirstStep() {
1713
+ return this.isInitialized && this.currentStepIndex === 0;
1714
+ }
1715
+ // Check if currently at the last step
1716
+ isAtLastStep() {
1717
+ return this.isInitialized && this.currentStepIndex >= this.steps.length - 1;
1718
+ }
1719
+ isWorkflowStarted() {
1720
+ return this.isStarted;
1721
+ }
1722
+ isCompleted() {
1723
+ return this.isInitialized && this.currentStepIndex > this.steps.length - 1;
1724
+ }
1725
+ // Mark workflow as completed by moving beyond the last step
1726
+ markCompleted() {
1727
+ if (this.isInitialized) {
1728
+ this.currentStepIndex = this.steps.length;
1729
+ }
1730
+ }
1731
+ initialize(steps) {
1732
+ this.steps = steps;
1733
+ this.stepStatuses = new Array(steps.length).fill("pending");
1734
+ this.stepResults = new Array(steps.length).fill("");
1735
+ this.stepErrors = new Array(steps.length).fill("");
1736
+ this.currentStepIndex = 0;
1737
+ this.isInitialized = true;
1738
+ this.isStarted = false;
1739
+ }
1740
+ // Mark current step as running
1741
+ markCurrentStepRunning() {
1742
+ if (this.isInitialized && this.currentStepIndex >= 0 && this.currentStepIndex < this.steps.length) {
1743
+ this.stepStatuses[this.currentStepIndex] = "running";
1744
+ }
1745
+ }
1746
+ // Mark current step as completed
1747
+ markCurrentStepCompleted(result) {
1748
+ if (this.isInitialized && this.currentStepIndex >= 0 && this.currentStepIndex < this.steps.length) {
1749
+ this.stepStatuses[this.currentStepIndex] = "completed";
1750
+ if (result) {
1751
+ this.stepResults[this.currentStepIndex] = result;
1752
+ }
1753
+ }
1754
+ }
1755
+ // Mark current step as failed
1756
+ markCurrentStepFailed(error) {
1757
+ if (this.isInitialized && this.currentStepIndex >= 0 && this.currentStepIndex < this.steps.length) {
1758
+ this.stepStatuses[this.currentStepIndex] = "failed";
1759
+ if (error) {
1760
+ this.stepErrors[this.currentStepIndex] = error;
1761
+ }
1762
+ }
1763
+ }
1764
+ // Get steps with their status
1765
+ getStepsWithStatus() {
1766
+ return this.steps.map((step, index) => ({
1767
+ ...step,
1768
+ status: this.stepStatuses[index] || "pending",
1769
+ result: this.stepResults[index] || void 0,
1770
+ error: this.stepErrors[index] || void 0
1771
+ }));
1772
+ }
1773
+ // Get basic workflow progress data for template rendering
1774
+ getProgressData() {
1775
+ return {
1776
+ steps: this.steps,
1777
+ statuses: this.stepStatuses,
1778
+ results: this.stepResults,
1779
+ errors: this.stepErrors,
1780
+ currentStepIndex: this.currentStepIndex,
1781
+ totalSteps: this.steps.length
1782
+ };
1783
+ }
1784
+ start() {
1785
+ this.isStarted = true;
1786
+ }
1787
+ moveToNextStep() {
1788
+ if (!this.hasNextStep()) {
1789
+ return false;
1790
+ }
1791
+ this.currentStepIndex++;
1792
+ return true;
1793
+ }
1794
+ // Move to the previous step in the workflow
1795
+ moveToPreviousStep() {
1796
+ if (!this.hasPreviousStep()) {
1797
+ return false;
1798
+ }
1799
+ this.currentStepIndex--;
1800
+ return true;
1801
+ }
1802
+ // Move to a specific step by index (optional feature)
1803
+ moveToStep(stepIndex) {
1804
+ if (!this.isInitialized || stepIndex < 0 || stepIndex >= this.steps.length) {
1805
+ return false;
1806
+ }
1807
+ this.currentStepIndex = stepIndex;
1808
+ return true;
1809
+ }
1810
+ reset() {
1811
+ this.currentStepIndex = -1;
1812
+ this.steps = [];
1813
+ this.stepStatuses = [];
1814
+ this.stepResults = [];
1815
+ this.stepErrors = [];
1816
+ this.isInitialized = false;
1817
+ this.isStarted = false;
1818
+ }
1819
+ getDebugInfo() {
1820
+ return {
1821
+ currentStepIndex: this.currentStepIndex,
1822
+ totalSteps: this.steps.length,
1823
+ isInitialized: this.isInitialized,
1824
+ currentStep: this.getCurrentStep()?.description,
1825
+ nextStep: this.getNextStep()?.description,
1826
+ previousStep: this.getPreviousStep()?.description,
1827
+ isAtFirstStep: this.isAtFirstStep(),
1828
+ hasPreviousStep: this.hasPreviousStep()
1829
+ };
1830
+ }
1831
+ };
1832
+
1833
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/mcpc__core/src/executors/workflow/workflow-executor.js
1834
+ import { Ajv as Ajv3 } from "ajv";
1835
+ import { AggregateAjvError as AggregateAjvError3 } from "@segment/ajv-human-errors";
1836
+ import addFormats3 from "ajv-formats";
1837
+ var ajv3 = new Ajv3({
1838
+ allErrors: true,
1839
+ verbose: true
1840
+ });
1841
+ addFormats3(ajv3);
1842
+ var WorkflowExecutor = class {
1843
+ name;
1844
+ allToolNames;
1845
+ toolNameToDetailList;
1846
+ createArgsDef;
1847
+ server;
1848
+ predefinedSteps;
1849
+ ensureStepActions;
1850
+ toolNameToIdMapping;
1851
+ constructor(name, allToolNames, toolNameToDetailList, createArgsDef, server2, predefinedSteps, ensureStepActions, toolNameToIdMapping) {
1852
+ this.name = name;
1853
+ this.allToolNames = allToolNames;
1854
+ this.toolNameToDetailList = toolNameToDetailList;
1855
+ this.createArgsDef = createArgsDef;
1856
+ this.server = server2;
1857
+ this.predefinedSteps = predefinedSteps;
1858
+ this.ensureStepActions = ensureStepActions;
1859
+ this.toolNameToIdMapping = toolNameToIdMapping;
1860
+ }
1861
+ // Helper method to validate required actions are present in workflow steps
1862
+ validateRequiredActions(steps) {
1863
+ if (!this.ensureStepActions || this.ensureStepActions.length === 0) {
1864
+ return {
1865
+ valid: true,
1866
+ missing: []
1867
+ };
1868
+ }
1869
+ const allStepActions = /* @__PURE__ */ new Set();
1870
+ steps.forEach((step) => {
1871
+ step.actions.forEach((action) => allStepActions.add(action));
1872
+ });
1873
+ const missing = [];
1874
+ for (const requiredAction of this.ensureStepActions) {
1875
+ if (allStepActions.has(requiredAction)) {
1876
+ continue;
1877
+ }
1878
+ if (this.toolNameToIdMapping) {
1879
+ const mappedToolId = this.toolNameToIdMapping.get(requiredAction);
1880
+ if (mappedToolId && allStepActions.has(mappedToolId)) {
1881
+ continue;
1882
+ }
1883
+ }
1884
+ missing.push(requiredAction);
1885
+ }
1886
+ return {
1887
+ valid: missing.length === 0,
1888
+ missing
1889
+ };
1890
+ }
1891
+ // Helper method to format workflow progress
1892
+ formatProgress(state) {
1893
+ const progressData = state.getProgressData();
1894
+ return PromptUtils.formatWorkflowProgress(progressData);
1895
+ }
1896
+ async execute(args, state) {
1897
+ if (args.init) {
1898
+ state.reset();
1899
+ } else {
1900
+ if (!state.isWorkflowInitialized() && !args.init) {
1901
+ return {
1902
+ content: [
1903
+ {
1904
+ type: "text",
1905
+ text: this.predefinedSteps ? WorkflowPrompts.ERRORS.NOT_INITIALIZED.WITH_PREDEFINED : WorkflowPrompts.ERRORS.NOT_INITIALIZED.WITHOUT_PREDEFINED
1906
+ }
1907
+ ],
1908
+ isError: true
1909
+ };
1910
+ }
1911
+ const decision2 = args.decision;
1912
+ if (decision2 === "proceed") {
1913
+ if (state.isAtLastStep() && state.isWorkflowStarted()) {
1914
+ state.markCompleted();
1915
+ return {
1916
+ content: [
1917
+ {
1918
+ type: "text",
1919
+ text: `## Workflow Completed!
1920
+
1921
+ ${this.formatProgress(state)}
1922
+
1923
+ ${CompiledPrompts.workflowCompleted({
1924
+ totalSteps: state.getSteps().length,
1925
+ toolName: this.name,
1926
+ newWorkflowInstructions: this.predefinedSteps ? "" : " and new `steps` array"
1927
+ })}`
1928
+ }
1929
+ ],
1930
+ isError: false
1931
+ };
1932
+ }
1933
+ if (state.isCompleted()) {
1934
+ return {
1935
+ content: [
1936
+ {
1937
+ type: "text",
1938
+ text: WorkflowPrompts.ERRORS.ALREADY_AT_FINAL
1939
+ }
1940
+ ],
1941
+ isError: true
1942
+ };
1943
+ }
1944
+ const currentStepIndex = state.getCurrentStepIndex();
1945
+ const wasStarted = state.isWorkflowStarted();
1946
+ if (state.isWorkflowStarted()) {
1947
+ state.moveToNextStep();
1948
+ } else {
1949
+ state.start();
1950
+ }
1951
+ const nextStepValidationSchema = this.createArgsDef.forCurrentState(state);
1952
+ const nextStepValidationResult = this.validate(args, nextStepValidationSchema);
1953
+ if (!nextStepValidationResult.valid) {
1954
+ if (wasStarted) {
1955
+ state.moveToStep(currentStepIndex);
1956
+ } else {
1957
+ state.moveToStep(currentStepIndex);
1958
+ }
1959
+ return {
1960
+ content: [
1961
+ {
1962
+ type: "text",
1963
+ text: CompiledPrompts.workflowErrorResponse({
1964
+ errorMessage: `Cannot proceed to next step: ${nextStepValidationResult.error || "Arguments validation failed"}`
1965
+ })
1966
+ }
1967
+ ],
1968
+ isError: true
1969
+ };
1970
+ }
1971
+ } else if (decision2 === "complete") {
1972
+ if (state.isAtLastStep() && state.isWorkflowStarted()) {
1973
+ state.markCompleted();
1974
+ return {
1975
+ content: [
1976
+ {
1977
+ type: "text",
1978
+ text: `## Workflow Completed!
1979
+
1980
+ ${this.formatProgress(state)}
1981
+
1982
+ ${CompiledPrompts.workflowCompleted({
1983
+ totalSteps: state.getSteps().length,
1984
+ toolName: this.name,
1985
+ newWorkflowInstructions: this.predefinedSteps ? "" : " and new `steps` array"
1986
+ })}`
1987
+ }
1988
+ ],
1989
+ isError: false
1990
+ };
1991
+ } else {
1992
+ return {
1993
+ content: [
1994
+ {
1995
+ type: "text",
1996
+ text: WorkflowPrompts.ERRORS.CANNOT_COMPLETE_NOT_AT_FINAL
1997
+ }
1998
+ ],
1999
+ isError: true
2000
+ };
2001
+ }
2002
+ }
2003
+ }
2004
+ const decision = args.decision;
2005
+ if (decision !== "proceed") {
2006
+ const validationSchema = this.createArgsDef.forCurrentState(state);
2007
+ const validationResult = this.validate(args, validationSchema);
2008
+ if (!validationResult.valid) {
2009
+ return {
2010
+ content: [
2011
+ {
2012
+ type: "text",
2013
+ text: CompiledPrompts.workflowErrorResponse({
2014
+ errorMessage: validationResult.error || "Arguments validation failed"
2015
+ })
2016
+ }
2017
+ ],
2018
+ isError: true
2019
+ };
2020
+ }
2021
+ }
2022
+ if (args.init) {
2023
+ return this.initialize(args, state);
2024
+ }
2025
+ return await this.executeStep(args, state);
2026
+ }
2027
+ initialize(args, state) {
2028
+ const steps = args.steps ?? this.predefinedSteps;
2029
+ if (!steps || steps.length === 0) {
2030
+ return {
2031
+ content: [
2032
+ {
2033
+ type: "text",
2034
+ text: WorkflowPrompts.ERRORS.NO_STEPS_PROVIDED
2035
+ }
2036
+ ],
2037
+ isError: true
2038
+ };
2039
+ }
2040
+ const validation = this.validateRequiredActions(steps);
2041
+ if (!validation.valid) {
2042
+ return {
2043
+ content: [
2044
+ {
2045
+ type: "text",
2046
+ text: `## Workflow Validation Failed \u274C
2047
+
2048
+ **Missing Required Actions:** The following actions must be included in the workflow steps:
2049
+
2050
+ ${validation.missing.map((action) => `- \`${this.toolNameToIdMapping?.get(action) ?? action}\``).join("\n")}`
2051
+ }
2052
+ ],
2053
+ isError: true
2054
+ };
2055
+ }
2056
+ state.initialize(steps);
2057
+ return {
2058
+ content: [
2059
+ {
2060
+ type: "text",
2061
+ text: `## Workflow Initialized
2062
+ ${this.formatProgress(state)}
2063
+ ${this.createArgsDef.forInitialStepDescription(steps, state)}`
2064
+ }
2065
+ ],
2066
+ isError: false
2067
+ };
2068
+ }
2069
+ async executeStep(args, state) {
2070
+ const currentStep = state.getCurrentStep();
2071
+ if (!currentStep) {
2072
+ return {
2073
+ content: [
2074
+ {
2075
+ type: "text",
2076
+ text: WorkflowPrompts.ERRORS.NO_CURRENT_STEP
2077
+ }
2078
+ ],
2079
+ isError: true
2080
+ };
2081
+ }
2082
+ state.markCurrentStepRunning();
2083
+ const results = {
2084
+ content: [],
2085
+ isError: false
2086
+ };
2087
+ for (const action of currentStep.actions) {
2088
+ try {
2089
+ const actionArgs = args[action] || {};
2090
+ const actionResult = await this.server.callTool(action, actionArgs);
2091
+ if (!results.isError) {
2092
+ results.isError = actionResult.isError;
2093
+ }
2094
+ results.content = results.content.concat(actionResult.content ?? []);
2095
+ results.content.push({
2096
+ type: "text",
2097
+ text: `Action \`${action}\` executed ${actionResult.isError ? "\u274C **FAILED**" : "\u2705 **SUCCESS**"}:`
2098
+ });
2099
+ } catch (error) {
2100
+ results.content.push({
2101
+ type: "text",
2102
+ text: `${error.message}`
2103
+ });
2104
+ results.content.push({
2105
+ type: "text",
2106
+ text: `Action \`${action}\` \u274C **FAILED** with error: `
2107
+ });
2108
+ results.isError = true;
2109
+ }
2110
+ }
2111
+ if (results.isError) {
2112
+ state.markCurrentStepFailed("Step execution failed");
2113
+ } else {
2114
+ state.markCurrentStepCompleted("Step completed successfully");
2115
+ }
2116
+ if (state.hasNextStep()) {
2117
+ const nextStepArgsDef = this.createArgsDef.forNextState(state);
2118
+ results.content.push({
2119
+ type: "text",
2120
+ text: CompiledPrompts.nextStepDecision({
2121
+ toolName: this.name,
2122
+ nextStepDescription: state.getNextStep()?.description || "Unknown step",
2123
+ nextStepSchema: JSON.stringify(nextStepArgsDef, null, 2)
2124
+ })
2125
+ });
2126
+ } else {
2127
+ results.content.push({
2128
+ type: "text",
2129
+ text: CompiledPrompts.finalStepCompletion({
2130
+ statusIcon: results.isError ? "\u274C" : "\u2705",
2131
+ statusText: results.isError ? "with errors" : "successfully",
2132
+ toolName: this.name,
2133
+ newWorkflowInstructions: this.predefinedSteps ? "" : " and new `steps` array"
2134
+ })
2135
+ });
2136
+ }
2137
+ results.content.push({
2138
+ type: "text",
2139
+ text: `## Workflow Progress
2140
+ ${this.formatProgress(state)}`
2141
+ });
2142
+ return results;
2143
+ }
2144
+ // Validate arguments using JSON schema
2145
+ validate(args, schema) {
2146
+ const validate = ajv3.compile(schema);
2147
+ if (!validate(args)) {
2148
+ const errors = new AggregateAjvError3(validate.errors);
2149
+ return {
2150
+ valid: false,
2151
+ error: errors.message
2152
+ };
2153
+ }
2154
+ return {
2155
+ valid: true
2156
+ };
2157
+ }
2158
+ };
2159
+
2160
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/mcpc__core/src/executors/sampling/workflow-sampling-executor.js
2161
+ var WorkflowSamplingExecutor = class extends BaseSamplingExecutor {
2162
+ createArgsDef;
2163
+ predefinedSteps;
2164
+ workflowExecutor;
2165
+ constructor(name, description, allToolNames, toolNameToDetailList, createArgsDef, server2, predefinedSteps, config2) {
2166
+ super(name, description, allToolNames, toolNameToDetailList, server2, config2), this.createArgsDef = createArgsDef, this.predefinedSteps = predefinedSteps;
2167
+ this.workflowExecutor = new WorkflowExecutor(name, allToolNames, toolNameToDetailList, createArgsDef, server2, predefinedSteps);
2168
+ }
2169
+ async executeWorkflowSampling(args, schema, state) {
2170
+ const validationResult = this.validateSchema(args, schema);
2171
+ if (!validationResult.valid) {
2172
+ return {
2173
+ content: [
2174
+ {
2175
+ type: "text",
2176
+ text: CompiledPrompts.workflowErrorResponse({
2177
+ errorMessage: validationResult.error || "Validation failed"
2178
+ })
2179
+ }
2180
+ ],
2181
+ isError: true
2182
+ };
2183
+ }
2184
+ return await this.runSamplingLoop(() => this.buildWorkflowSystemPrompt(args, state), schema, state);
2185
+ }
2186
+ async processAction(parsedData, _schema, state) {
2187
+ const workflowState = state;
2188
+ if (!workflowState) {
2189
+ throw new Error("WorkflowState is required for workflow");
2190
+ }
2191
+ const toolCallData = parsedData;
2192
+ if (toolCallData.decision === "complete") {
2193
+ return this.createCompletionResult("Task completed");
2194
+ }
2195
+ try {
2196
+ const workflowResult = await this.workflowExecutor.execute(parsedData, workflowState);
2197
+ const resultText = workflowResult.content?.filter((content) => content.type === "text")?.map((content) => content.text)?.join("\n") || "No result";
2198
+ this.conversationHistory.push({
2199
+ role: "assistant",
2200
+ content: {
2201
+ type: "text",
2202
+ text: resultText
2203
+ }
2204
+ });
2205
+ return workflowResult;
2206
+ } catch (error) {
2207
+ return this.createExecutionError(error);
2208
+ }
2209
+ }
2210
+ buildWorkflowSystemPrompt(args, state) {
2211
+ const workflowSchema = this.createArgsDef.forCurrentState(state);
2212
+ const basePrompt = CompiledPrompts.samplingWorkflowExecution({
2213
+ toolName: this.name,
2214
+ description: this.description,
2215
+ workflowSchema: `${JSON.stringify(workflowSchema, null, 2)}`
2216
+ });
2217
+ const workflowPrompt = `
2218
+
2219
+ Current Task: <user_request>${args.userRequest}</user_request>`;
2220
+ return this.injectJsonInstruction({
2221
+ prompt: basePrompt + workflowPrompt,
2222
+ schema: workflowSchema
2223
+ });
2224
+ }
2225
+ };
2226
+
2227
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/mcpc__core/src/executors/workflow/workflow-tool-registrar.js
2228
+ function registerAgenticWorkflowTool(server2, { description, name, allToolNames, depGroups, toolNameToDetailList, predefinedSteps, sampling = false, ensureStepActions, toolNameToIdMapping }) {
2229
+ const createArgsDef = createArgsDefFactory(name, allToolNames, depGroups, predefinedSteps, ensureStepActions);
2230
+ const isSamplingMode = sampling === true || typeof sampling === "object";
2231
+ const samplingConfig = typeof sampling === "object" ? sampling : void 0;
2232
+ const workflowExecutor = new WorkflowExecutor(name, allToolNames, toolNameToDetailList, createArgsDef, server2, predefinedSteps, ensureStepActions, toolNameToIdMapping);
2233
+ const workflowSamplingExecutor = new WorkflowSamplingExecutor(name, description, allToolNames, toolNameToDetailList, createArgsDef, server2, predefinedSteps, samplingConfig);
2234
+ const workflowState = new WorkflowState();
2235
+ const planningInstructions = predefinedSteps ? "- Set `init: true` (steps are predefined)" : "- Set `init: true` and define complete `steps` array";
2236
+ const baseDescription = isSamplingMode ? CompiledPrompts.samplingExecution({
2237
+ toolName: name,
2238
+ description,
2239
+ toolList: allToolNames.map((name2) => `- ${name2}`).join("\n")
2240
+ }) : CompiledPrompts.workflowExecution({
2241
+ toolName: name,
2242
+ description,
2243
+ planningInstructions
2244
+ });
2245
+ const argsDef = isSamplingMode ? createArgsDef.forSampling() : createArgsDef.forTool();
2246
+ const toolDescription = isSamplingMode ? baseDescription : createArgsDef.forToolDescription(baseDescription, workflowState);
2247
+ server2.tool(name, toolDescription, jsonSchema2(createGoogleCompatibleJSONSchema(argsDef)), async (args) => {
2248
+ try {
2249
+ if (isSamplingMode) {
2250
+ return await workflowSamplingExecutor.executeWorkflowSampling(args, argsDef, workflowState);
2251
+ } else {
2252
+ return await workflowExecutor.execute(args, workflowState);
2253
+ }
2254
+ } catch (error) {
2255
+ workflowState.reset();
2256
+ return {
2257
+ content: [
2258
+ {
2259
+ type: "text",
2260
+ text: `Workflow execution error: ${error.message}`
2261
+ }
2262
+ ],
2263
+ isError: true
2264
+ };
2265
+ }
2266
+ });
2267
+ }
2268
+
2269
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/mcpc__core/src/utils/common/tool-tag-processor.js
2270
+ var ALL_TOOLS_PLACEHOLDER = "__ALL__";
2271
+ function findToolId(toolName, tools, toolNameMapping) {
2272
+ const mappedId = toolNameMapping?.get(toolName);
2273
+ if (mappedId) {
2274
+ return mappedId;
2275
+ }
2276
+ return Object.keys(tools).find((id) => {
2277
+ const dotNotation = id.replace(/_/g, ".");
2278
+ return toolName === id || toolName === dotNotation;
2279
+ });
2280
+ }
2281
+ function processToolTags({ description, tagToResults, $, tools, toolOverrides, toolNameMapping }) {
2282
+ tagToResults.tool.forEach((toolEl) => {
2283
+ const toolName = toolEl.attribs.name;
2284
+ if (!toolName || toolName.includes(ALL_TOOLS_PLACEHOLDER)) {
2285
+ $(toolEl).remove();
2286
+ return;
2287
+ }
2288
+ const override = toolOverrides.get(toolName);
2289
+ if (override?.visibility?.hide) {
2290
+ $(toolEl).remove();
2291
+ } else if (override?.visibility?.global) {
2292
+ $(toolEl).replaceWith(`<tool name="${toolName}"/>`);
2293
+ } else {
2294
+ const toolId = findToolId(toolName, tools, toolNameMapping);
2295
+ if (toolId) {
2296
+ $(toolEl).replaceWith(`<action action="${toolId}"/>`);
2297
+ }
2298
+ }
2299
+ });
2300
+ return $.root().html() ?? description;
2301
+ }
2302
+
2303
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/mcpc__core/src/compose.js
2304
+ init_built_in();
2305
+
2306
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/mcpc__core/src/plugin-utils.js
2307
+ function shouldApplyPlugin(plugin, mode) {
2308
+ if (!plugin.apply) return true;
2309
+ if (typeof plugin.apply === "string") {
2310
+ return mode.includes(plugin.apply);
2311
+ }
2312
+ if (typeof plugin.apply === "function") {
2313
+ return plugin.apply(mode);
2314
+ }
2315
+ return plugin.apply;
2316
+ }
2317
+ function isValidPlugin(plugin) {
2318
+ return plugin && plugin.name && (plugin.configureServer || plugin.composeStart || plugin.transformTool || plugin.finalizeComposition || plugin.composeEnd);
2319
+ }
2320
+ async function loadPlugin(pluginPath) {
2321
+ try {
2322
+ const [rawPath, queryString] = pluginPath.split("?", 2);
2323
+ const searchParams = new URLSearchParams(queryString || "");
2324
+ const params = Object.fromEntries(searchParams.entries());
2325
+ const pluginModule = await import(rawPath);
2326
+ const pluginFactory = pluginModule.createPlugin;
2327
+ const defaultPlugin = pluginModule.default;
2328
+ let plugin;
2329
+ if (Object.keys(params).length > 0) {
2330
+ if (typeof pluginFactory === "function") {
2331
+ const typedParams = {};
2332
+ for (const [key, value] of Object.entries(params)) {
2333
+ const numValue = Number(value);
2334
+ if (!isNaN(numValue)) {
2335
+ typedParams[key] = numValue;
2336
+ } else if (value === "true") {
2337
+ typedParams[key] = true;
2338
+ } else if (value === "false") {
2339
+ typedParams[key] = false;
2340
+ } else {
2341
+ typedParams[key] = value;
2342
+ }
2343
+ }
2344
+ plugin = pluginFactory(typedParams);
2345
+ } else {
2346
+ throw new Error(`Plugin ${rawPath} has parameters but no createPlugin export`);
2347
+ }
2348
+ } else {
2349
+ plugin = defaultPlugin;
2350
+ }
2351
+ if (isValidPlugin(plugin)) {
2352
+ return plugin;
2353
+ } else {
2354
+ throw new Error(`Invalid plugin format in ${rawPath} - plugin must have a name and at least one lifecycle hook`);
2355
+ }
2356
+ } catch (error) {
2357
+ throw new Error(`Failed to load plugin from ${pluginPath}: ${error}`);
2358
+ }
2359
+ }
2360
+
2361
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/mcpc__core/src/compose.js
2362
+ var ALL_TOOLS_PLACEHOLDER2 = "__ALL__";
2363
+ var ComposableMCPServer = class extends Server {
2364
+ tools = [];
2365
+ toolRegistry = /* @__PURE__ */ new Map();
2366
+ toolConfigs = /* @__PURE__ */ new Map();
2367
+ globalPlugins = [];
2368
+ toolNameMapping = /* @__PURE__ */ new Map();
2369
+ constructor(_serverInfo, options) {
2370
+ super(_serverInfo, options);
2371
+ }
2372
+ /**
2373
+ * Initialize built-in plugins - called during setup
2374
+ */
2375
+ async initBuiltInPlugins() {
2376
+ const builtInPlugins = getBuiltInPlugins();
2377
+ for (const plugin of builtInPlugins) {
2378
+ await this.addPlugin(plugin);
2379
+ }
2380
+ }
2381
+ /**
2382
+ * Apply plugin transformations to tool arguments/results
2383
+ * TODO: Implement transformResult lifecycle hooks
2384
+ */
2385
+ applyPluginTransforms(_toolName, args, _mode, _originalArgs) {
2386
+ return args;
2387
+ }
2388
+ /**
2389
+ * Resolve a tool name to its internal format
2390
+ */
2391
+ resolveToolName(name) {
2392
+ if (this.toolRegistry.has(name)) {
2393
+ return name;
2394
+ }
2395
+ const mappedName = this.toolNameMapping.get(name);
2396
+ if (mappedName && this.toolRegistry.has(mappedName)) {
2397
+ return mappedName;
2398
+ }
2399
+ if (this.toolConfigs.has(name)) {
2400
+ const cfgMapped = this.toolNameMapping.get(name);
2401
+ if (cfgMapped && this.toolRegistry.has(cfgMapped)) {
2402
+ return cfgMapped;
2403
+ }
2404
+ }
2405
+ return void 0;
2406
+ }
2407
+ tool(name, description, paramsSchema, cb, options = {}) {
2408
+ this.toolRegistry.set(name, {
2409
+ callback: cb,
2410
+ description,
2411
+ schema: paramsSchema.jsonSchema
2412
+ });
2413
+ if (options.plugins) {
2414
+ for (const plugin of options.plugins) {
2415
+ this.globalPlugins.push(plugin);
2416
+ }
2417
+ }
2418
+ if (options.internal) {
2419
+ this.toolConfigs.set(name, {
2420
+ visibility: {
2421
+ internal: true
2422
+ }
2423
+ });
2424
+ } else {
2425
+ const existingTool = this.tools.find((t) => t.name === name);
2426
+ if (!existingTool) {
2427
+ const newTool = {
2428
+ name,
2429
+ description,
2430
+ inputSchema: paramsSchema.jsonSchema
2431
+ };
2432
+ this.tools = [
2433
+ ...this.tools,
2434
+ newTool
2435
+ ];
2436
+ }
2437
+ }
2438
+ this.setRequestHandler(ListToolsRequestSchema, () => {
2439
+ return {
2440
+ tools: this.tools
2441
+ };
2442
+ });
2443
+ this.setRequestHandler(CallToolRequestSchema, (request, extra) => {
2444
+ const { name: toolName, arguments: args } = request.params;
2445
+ const handler = this.getToolCallback(toolName);
2446
+ if (!handler) {
2447
+ throw new Error(`Tool ${toolName} not found`);
2448
+ }
2449
+ const processedArgs = this.applyPluginTransforms(toolName, args, "input");
2450
+ const result = handler(processedArgs, extra);
2451
+ return this.applyPluginTransforms(toolName, result, "output", args);
2452
+ });
2453
+ }
2454
+ /**
2455
+ * Register a tool override with description, hide, args transformation, and/or custom handler
2456
+ */
2457
+ /**
2458
+ * Get tool callback from registry
2459
+ */
2460
+ getToolCallback(name) {
2461
+ return this.toolRegistry.get(name)?.callback;
2462
+ }
2463
+ /**
2464
+ * Find tool configuration (simplified - dot/underscore mapping now handled by plugin)
2465
+ */
2466
+ findToolConfig(toolId) {
2467
+ const directConfig = this.toolConfigs.get(toolId);
2468
+ if (directConfig) {
2469
+ return directConfig;
2470
+ }
2471
+ const mappedName = this.toolNameMapping.get(toolId);
2472
+ if (mappedName && this.toolConfigs.has(mappedName)) {
2473
+ return this.toolConfigs.get(mappedName);
2474
+ }
2475
+ return void 0;
2476
+ }
2477
+ /**
2478
+ * Call any registered tool directly, whether it's public or internal
2479
+ */
2480
+ async callTool(name, args) {
2481
+ const resolvedName = this.resolveToolName(name);
2482
+ if (!resolvedName) {
2483
+ throw new Error(`Tool ${name} not found`);
2484
+ }
2485
+ const callback = this.getToolCallback(resolvedName);
2486
+ if (!callback) {
2487
+ throw new Error(`Tool ${name} not found`);
2488
+ }
2489
+ const processedArgs = this.applyPluginTransforms(resolvedName, args, "input");
2490
+ const result = await callback(processedArgs);
2491
+ return this.applyPluginTransforms(resolvedName, result, "output", args);
2492
+ }
2493
+ /**
2494
+ * Get all internal tool names
2495
+ */
2496
+ getInternalToolNames() {
2497
+ return Array.from(this.toolConfigs.entries()).filter(([_name, config2]) => config2.visibility?.internal).map(([name]) => this.resolveToolName(name) ?? name);
2498
+ }
2499
+ /**
2500
+ * Get all public tool names
2501
+ */
2502
+ getPublicToolNames() {
2503
+ return Array.from(this.toolConfigs.entries()).filter(([_name, config2]) => config2.visibility?.global).map(([name]) => this.resolveToolName(name) ?? name);
2504
+ }
2505
+ /**
2506
+ * Get all external (non-global, non-internal, non-hidden) tool names
2507
+ */
2508
+ getExternalToolNames() {
2509
+ const allRegistered = Array.from(this.toolRegistry.keys());
2510
+ const publicSet = new Set(this.getPublicToolNames());
2511
+ const internalSet = new Set(this.getInternalToolNames());
2512
+ const hiddenSet = new Set(this.getHiddenToolNames());
2513
+ return allRegistered.filter((n) => !publicSet.has(n) && !internalSet.has(n) && !hiddenSet.has(n));
2514
+ }
2515
+ /**
2516
+ * Get all hidden tool names
2517
+ */
2518
+ getHiddenToolNames() {
2519
+ return Array.from(this.toolConfigs.entries()).filter(([_name, config2]) => config2.visibility?.hide).map(([name]) => this.resolveToolName(name) ?? name);
2520
+ }
2521
+ /**
2522
+ * Get internal tool schema by name
2523
+ */
2524
+ getInternalToolSchema(name) {
2525
+ const tool = this.toolRegistry.get(name);
2526
+ const config2 = this.toolConfigs.get(name);
2527
+ if (tool && config2?.visibility?.internal && tool.schema) {
2528
+ return {
2529
+ description: tool.description,
2530
+ schema: tool.schema
2531
+ };
2532
+ }
2533
+ return void 0;
2534
+ }
2535
+ /**
2536
+ * Check if a tool exists (visible or internal)
2537
+ */
2538
+ hasToolNamed(name) {
2539
+ return this.toolRegistry.has(name) || this.toolNameMapping.has(name) && this.toolRegistry.has(this.toolNameMapping.get(name));
2540
+ }
2541
+ /**
2542
+ * Configure tool behavior (simplified replacement for middleware)
2543
+ * @example
2544
+ * ```typescript
2545
+ * // Override description
2546
+ * server.configTool('myTool', {
2547
+ * callback: originalCallback,
2548
+ * description: 'Enhanced tool description'
2549
+ * });
2550
+ *
2551
+ * // Hide tool from agentic execution
2552
+ * server.configTool('myTool', {
2553
+ * callback: originalCallback,
2554
+ * description: 'Hidden tool',
2555
+ * visibility: { hide: true }
2556
+ * });
2557
+ *
2558
+ * // Make tool globally available
2559
+ * server.configTool('myTool', {
2560
+ * callback: originalCallback,
2561
+ * description: 'Global tool',
2562
+ * visibility: { global: true }
2563
+ * });
2564
+ * ```
2565
+ */
2566
+ configTool(toolName, config2) {
2567
+ this.toolConfigs.set(toolName, config2);
2568
+ }
2569
+ /**
2570
+ * Get tool configuration
2571
+ */
2572
+ getToolConfig(toolName) {
2573
+ return this.toolConfigs.get(toolName);
2574
+ }
2575
+ /**
2576
+ * Remove tool configuration
2577
+ */
2578
+ removeToolConfig(toolName) {
2579
+ return this.toolConfigs.delete(toolName);
2580
+ }
2581
+ /**
2582
+ * Register a tool plugin
2583
+ * @example
2584
+ * ```typescript
2585
+ * // Global plugin for all tools
2586
+ * server.addPlugin({
2587
+ * name: 'logger',
2588
+ * transformTool: (tool, context) => {
2589
+ * const originalExecute = tool.execute;
2590
+ * tool.execute = async (args, extra) => {
2591
+ * console.log(`Calling ${tool.name} with:`, args);
2592
+ * const result = await originalExecute(args, extra);
2593
+ * console.log(`Result:`, result);
2594
+ * return result;
2595
+ * };
2596
+ * return tool;
2597
+ * }
2598
+ * });
2599
+ * ```
2600
+ */
2601
+ async addPlugin(plugin) {
2602
+ if (plugin.configureServer) {
2603
+ await plugin.configureServer(this);
2604
+ }
2605
+ this.globalPlugins.push(plugin);
2606
+ }
2607
+ /**
2608
+ * Load and register a plugin from a file path with optional parameters
2609
+ *
2610
+ * Supports parameter passing via query string syntax:
2611
+ * loadPluginFromPath("path/to/plugin.ts?param1=value1&param2=value2")
2612
+ */
2613
+ async loadPluginFromPath(pluginPath) {
2614
+ const plugin = await loadPlugin(pluginPath);
2615
+ this.addPlugin(plugin);
2616
+ }
2617
+ /**
2618
+ * Apply transformTool hook to a tool during composition
2619
+ */
2620
+ async applyTransformToolHooks(tool, toolName, mode) {
2621
+ const transformPlugins = this.globalPlugins.filter((p2) => p2.transformTool && shouldApplyPlugin(p2, mode));
2622
+ if (transformPlugins.length === 0) {
2623
+ return tool;
2624
+ }
2625
+ const sortedPlugins = [
2626
+ ...transformPlugins.filter((p2) => p2.enforce === "pre"),
2627
+ ...transformPlugins.filter((p2) => !p2.enforce),
2628
+ ...transformPlugins.filter((p2) => p2.enforce === "post")
2629
+ ];
2630
+ const context = {
2631
+ toolName,
2632
+ server: this,
2633
+ mode
2634
+ };
2635
+ let currentTool = tool;
2636
+ for (const plugin of sortedPlugins) {
2637
+ if (plugin.transformTool) {
2638
+ const result = await plugin.transformTool(currentTool, context);
2639
+ if (result) {
2640
+ currentTool = result;
2641
+ }
2642
+ }
2643
+ }
2644
+ return currentTool;
2645
+ }
2646
+ /**
2647
+ * Apply plugins to all tools in registry and handle visibility configurations
2648
+ */
2649
+ async processToolsWithPlugins(externalTools, mode) {
2650
+ for (const [toolId, toolData] of this.toolRegistry.entries()) {
2651
+ const defaultSchema = {
2652
+ type: "object",
2653
+ properties: {},
2654
+ additionalProperties: true
2655
+ };
2656
+ const tempTool = {
2657
+ name: toolId,
2658
+ description: toolData.description,
2659
+ inputSchema: toolData.schema || defaultSchema,
2660
+ execute: toolData.callback
2661
+ };
2662
+ const processedTool = await this.applyTransformToolHooks(tempTool, toolId, mode);
2663
+ this.toolRegistry.set(toolId, {
2664
+ callback: processedTool.execute,
2665
+ description: processedTool.description || toolData.description,
2666
+ schema: processedTool.inputSchema
2667
+ });
2668
+ if (externalTools[toolId]) {
2669
+ try {
2670
+ const builtIn = await Promise.resolve().then(() => (init_built_in(), built_in_exports));
2671
+ if (builtIn && typeof builtIn.processToolVisibility === "function") {
2672
+ builtIn.processToolVisibility(toolId, processedTool, this, externalTools);
2673
+ }
2674
+ } catch {
2675
+ }
2676
+ externalTools[toolId] = processedTool;
2677
+ }
2678
+ }
2679
+ }
2680
+ /**
2681
+ * Trigger composeEnd hooks for all plugins
2682
+ */
2683
+ async triggerComposeEndHooks(context) {
2684
+ const endPlugins = this.globalPlugins.filter((p2) => p2.composeEnd && shouldApplyPlugin(p2, context.mode));
2685
+ for (const plugin of endPlugins) {
2686
+ if (plugin.composeEnd) {
2687
+ await plugin.composeEnd(context);
2688
+ }
2689
+ }
2690
+ }
2691
+ async compose(name, description, depsConfig = {
2692
+ mcpServers: {}
2693
+ }, options = {
2694
+ mode: "agentic"
2695
+ }) {
2696
+ const refDesc = options.refs?.join("") ?? "";
2697
+ const { tagToResults } = parseTags(description + refDesc, [
2698
+ "tool",
2699
+ "fn"
2700
+ ]);
2701
+ tagToResults.tool.forEach((toolEl) => {
2702
+ const toolName = toolEl.attribs.name;
2703
+ const toolDescription = toolEl.attribs.description;
2704
+ const isHidden = toolEl.attribs.hide !== void 0;
2705
+ const isGlobal = toolEl.attribs.global !== void 0;
2706
+ if (toolName) {
2707
+ this.toolConfigs.set(toolName, {
2708
+ description: toolDescription,
2709
+ visibility: {
2710
+ hide: isHidden,
2711
+ global: isGlobal
2712
+ }
2713
+ });
2714
+ }
2715
+ });
2716
+ const toolNameToIdMapping = /* @__PURE__ */ new Map();
2717
+ const requestedToolNames = /* @__PURE__ */ new Set();
2718
+ const availableToolNames = /* @__PURE__ */ new Set();
2719
+ tagToResults.tool.forEach((tool) => {
2720
+ if (tool.attribs.name) {
2721
+ requestedToolNames.add(tool.attribs.name);
2722
+ }
2723
+ });
2724
+ const { tools, cleanupClients } = await composeMcpDepTools(depsConfig, ({ mcpName, toolNameWithScope, toolId }) => {
2725
+ toolNameToIdMapping.set(toolNameWithScope, toolId);
2726
+ availableToolNames.add(toolNameWithScope);
2727
+ availableToolNames.add(toolId);
2728
+ availableToolNames.add(`${mcpName}.${ALL_TOOLS_PLACEHOLDER2}`);
2729
+ availableToolNames.add(mcpName);
2730
+ this.toolNameMapping.set(toolNameWithScope, toolId);
2731
+ const internalName = toolNameWithScope.includes(".") ? toolNameWithScope.split(".").slice(1).join(".") : toolNameWithScope;
2732
+ if (!this.toolNameMapping.has(internalName)) {
2733
+ this.toolNameMapping.set(internalName, toolId);
2734
+ }
2735
+ const matchingStep = options.steps?.find((step) => step.actions.includes(toolNameWithScope));
2736
+ if (matchingStep) {
2737
+ const actionIndex = matchingStep.actions.indexOf(toolNameWithScope);
2738
+ if (actionIndex !== -1) {
2739
+ matchingStep.actions[actionIndex] = toolId;
2740
+ }
2741
+ return true;
2742
+ }
2743
+ return tagToResults.tool.find((tool) => {
2744
+ const selectAll = tool.attribs.name === `${mcpName}.${ALL_TOOLS_PLACEHOLDER2}` || tool.attribs.name === `${mcpName}`;
2745
+ if (selectAll) {
2746
+ return true;
2747
+ }
2748
+ return tool.attribs.name === toolNameWithScope || tool.attribs.name === toolId;
2749
+ });
2750
+ });
2751
+ const unmatchedTools = Array.from(requestedToolNames).filter((toolName) => !availableToolNames.has(toolName));
2752
+ if (unmatchedTools.length > 0) {
2753
+ console.warn(`\u26A0\uFE0F Tool matching warnings for agent "${name}":`);
2754
+ unmatchedTools.forEach((toolName) => {
2755
+ console.warn(` \u2022 Tool not found: "${toolName}"`);
2756
+ });
2757
+ console.warn(` Available tools: ${Array.from(availableToolNames).sort().join(", ")}`);
2758
+ }
2759
+ Object.entries(tools).forEach(([toolId, tool]) => {
2760
+ this.toolRegistry.set(toolId, {
2761
+ callback: tool.execute,
2762
+ description: tool.description || "No description available",
2763
+ schema: tool.inputSchema
2764
+ });
2765
+ });
2766
+ await this.processToolsWithPlugins(tools, options.mode ?? "agentic");
2767
+ this.onclose = async () => {
2768
+ await cleanupClients();
2769
+ console.log(`\u{1F9E9} [${name}]`);
2770
+ console.log(` \u251C\u2500 Event: closed`);
2771
+ console.log(` \u2514\u2500 Action: cleaned up dependent clients`);
2772
+ };
2773
+ this.onerror = async (error) => {
2774
+ console.log(`\u{1F9E9} [${name}]`);
2775
+ console.log(` \u251C\u2500 Event: error, ${error?.stack ?? String(error)}`);
2776
+ await cleanupClients();
2777
+ console.log(` \u2514\u2500 Action: cleaned up dependent clients`);
2778
+ };
2779
+ const toolNameToDetailList = Object.entries(tools);
2780
+ const globalToolNames = this.getPublicToolNames();
2781
+ const hideToolNames = this.getHiddenToolNames();
2782
+ const internalToolNames = this.getInternalToolNames();
2783
+ const contextToolNames = toolNameToDetailList.map(([name2]) => name2).filter((n) => !globalToolNames.includes(n) && !hideToolNames.includes(n));
2784
+ const allToolNames = [
2785
+ ...contextToolNames,
2786
+ ...internalToolNames
2787
+ ];
2788
+ globalToolNames.forEach((toolId) => {
2789
+ const tool = tools[toolId];
2790
+ if (!tool) {
2791
+ throw new Error(`Global tool ${toolId} not found in registry, available: ${Object.keys(tools).join(", ")}`);
2792
+ }
2793
+ this.tool(toolId, tool.description || "No description available", jsonSchema3(tool.inputSchema), tool.execute);
2794
+ });
2795
+ await this.triggerComposeEndHooks({
2796
+ toolName: name,
2797
+ pluginNames: this.globalPlugins.map((p2) => p2.name),
2798
+ mode: options.mode ?? "agentic",
2799
+ server: this
2800
+ });
2801
+ if (!name) {
2802
+ return;
2803
+ }
2804
+ const desTags = parseTags(description, [
2805
+ "tool",
2806
+ "fn"
2807
+ ]);
2808
+ description = processToolTags({
2809
+ ...desTags,
2810
+ description,
2811
+ tools,
2812
+ toolOverrides: this.toolConfigs,
2813
+ toolNameMapping: toolNameToIdMapping
2814
+ });
2815
+ const depGroups = {};
2816
+ toolNameToDetailList.forEach(([toolName, tool]) => {
2817
+ if (hideToolNames.includes(this.resolveToolName(toolName) ?? "") || globalToolNames.includes(this.resolveToolName(toolName) ?? "")) {
2818
+ return;
2819
+ }
2820
+ if (!tool) {
2821
+ throw new Error(`Action ${toolName} not found, available action list: ${allToolNames.join(", ")}`);
2822
+ }
2823
+ const baseSchema = (
2824
+ // Compatiable with ComposiableleMCPServer.tool() definition
2825
+ tool.inputSchema.jsonSchema ?? // Standard definition
2826
+ tool.inputSchema ?? {
2827
+ type: "object",
2828
+ properties: {},
2829
+ required: []
2830
+ }
2831
+ );
2832
+ const baseProperties = baseSchema.type === "object" && baseSchema.properties ? baseSchema.properties : {};
2833
+ const baseRequired = baseSchema.type === "object" && Array.isArray(baseSchema.required) ? baseSchema.required : [];
2834
+ const updatedProperties = updateRefPaths(baseProperties, toolName);
2835
+ depGroups[toolName] = {
2836
+ type: "object",
2837
+ description: tool.description,
2838
+ properties: updatedProperties,
2839
+ required: [
2840
+ ...baseRequired
2841
+ ],
2842
+ additionalProperties: false
2843
+ };
2844
+ });
2845
+ internalToolNames.forEach((toolName) => {
2846
+ const toolSchema = this.getInternalToolSchema(toolName);
2847
+ if (toolSchema) {
2848
+ depGroups[toolName] = {
2849
+ ...toolSchema.schema,
2850
+ description: toolSchema.description
2851
+ };
2852
+ } else {
2853
+ throw new Error(`Internal tool schema not found for: ${toolName}`);
2854
+ }
2855
+ });
2856
+ switch (options.mode ?? "agentic") {
2857
+ case "agentic":
2858
+ registerAgenticTool(this, {
2859
+ description,
2860
+ name,
2861
+ allToolNames,
2862
+ depGroups,
2863
+ toolNameToDetailList,
2864
+ sampling: options.sampling
2865
+ });
2866
+ break;
2867
+ case "agentic_workflow":
2868
+ registerAgenticWorkflowTool(this, {
2869
+ description,
2870
+ name,
2871
+ allToolNames,
2872
+ depGroups,
2873
+ toolNameToDetailList,
2874
+ predefinedSteps: options.steps,
2875
+ sampling: options.sampling,
2876
+ ensureStepActions: options.ensureStepActions,
2877
+ toolNameToIdMapping
2878
+ });
2879
+ break;
2880
+ }
2881
+ }
2882
+ };
2883
+
2884
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/mcpc__core/src/utils/common/env.js
2885
+ import process4 from "node:process";
2886
+ var isSCF = () => Boolean(process4.env.SCF_RUNTIME || process4.env.PROD_SCF);
2887
+ if (isSCF()) {
2888
+ console.log({
2889
+ isSCF: isSCF(),
2890
+ SCF_RUNTIME: process4.env.SCF_RUNTIME
2891
+ });
2892
+ }
2893
+
2894
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@jsr/mcpc__core/src/set-up-mcp-compose.js
2895
+ function parseMcpcConfigs(conf) {
2896
+ const mcpcConfigs = conf ?? [];
2897
+ const newMcpcConfigs = [];
2898
+ for (const mcpcConfig of mcpcConfigs) {
2899
+ if (mcpcConfig?.deps?.mcpServers) {
2900
+ for (const [name, config2] of Object.entries(mcpcConfig.deps.mcpServers)) {
2901
+ if (config2.smitheryConfig) {
2902
+ const streamConfig = connectToSmitheryServer(config2.smitheryConfig);
2903
+ mcpcConfig.deps.mcpServers[name] = streamConfig;
2904
+ }
2905
+ }
2906
+ }
2907
+ newMcpcConfigs.push(mcpcConfig);
2908
+ }
2909
+ return newMcpcConfigs;
2910
+ }
2911
+ async function mcpc(serverConf, composeConf, setupCallback) {
2912
+ const server2 = new ComposableMCPServer(...serverConf);
2913
+ const parsed = parseMcpcConfigs(composeConf);
2914
+ await server2.initBuiltInPlugins();
2915
+ for (const mcpcConfig of parsed) {
2916
+ if (mcpcConfig.plugins) {
2917
+ for (const plugin of mcpcConfig.plugins) {
2918
+ if (typeof plugin === "string") {
2919
+ await server2.loadPluginFromPath(plugin);
2920
+ } else {
2921
+ await server2.addPlugin(plugin);
2922
+ }
2923
+ }
2924
+ }
2925
+ }
2926
+ if (setupCallback) {
2927
+ await setupCallback(server2);
2928
+ }
2929
+ for (const mcpcConfig of parsed) {
2930
+ await server2.compose(mcpcConfig.name, mcpcConfig.description ?? "", mcpcConfig.deps, mcpcConfig.options);
2931
+ }
2932
+ return server2;
2933
+ }
2934
+
2935
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@mcpc/cli/src/app.js
2936
+ var createServer = async (config2) => {
2937
+ const serverConfig = config2 || {
2938
+ name: "large-result-plugin-example",
2939
+ version: "0.1.0",
2940
+ agents: [
2941
+ {
2942
+ name: null,
2943
+ description: "",
2944
+ plugins: [
2945
+ "./plugins/large-result.ts?maxSize=8000&previewSize=4000"
2946
+ ]
2947
+ }
2948
+ ]
2949
+ };
2950
+ return await mcpc([
2951
+ {
2952
+ name: serverConfig.name || "mcpc-server",
2953
+ version: serverConfig.version || "0.1.0"
2954
+ },
2955
+ {
2956
+ capabilities: serverConfig.capabilities || {
2957
+ tools: {},
2958
+ sampling: {}
2959
+ }
2960
+ }
2961
+ ], serverConfig.agents);
2962
+ };
2963
+
2964
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@mcpc/cli/src/config/loader.js
2965
+ import { readFile } from "node:fs/promises";
2966
+ import { resolve } from "node:path";
2967
+ import process5 from "node:process";
2968
+ function parseArgs() {
2969
+ const args = process5.argv.slice(2);
2970
+ const result = {};
2971
+ for (let i = 0; i < args.length; i++) {
2972
+ const arg = args[i];
2973
+ if (arg === "--config" && i + 1 < args.length) {
2974
+ result.config = args[++i];
2975
+ } else if (arg === "--config-url" && i + 1 < args.length) {
2976
+ result.configUrl = args[++i];
2977
+ } else if (arg === "--config-file" && i + 1 < args.length) {
2978
+ result.configFile = args[++i];
2979
+ }
2980
+ }
2981
+ return result;
2982
+ }
2983
+ async function loadConfig() {
2984
+ const args = parseArgs();
2985
+ if (args.config) {
2986
+ try {
2987
+ const parsed = JSON.parse(args.config);
2988
+ return normalizeConfig(parsed);
2989
+ } catch (error) {
2990
+ console.error("Failed to parse --config argument:", error);
2991
+ throw error;
2992
+ }
2993
+ }
2994
+ if (args.configUrl) {
2995
+ try {
2996
+ const response = await fetch(args.configUrl);
2997
+ if (!response.ok) {
2998
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
2999
+ }
3000
+ const content = await response.text();
3001
+ const parsed = JSON.parse(content);
3002
+ return normalizeConfig(parsed);
3003
+ } catch (error) {
3004
+ console.error(`Failed to fetch config from ${args.configUrl}:`, error);
3005
+ throw error;
3006
+ }
3007
+ }
3008
+ if (args.configFile) {
3009
+ try {
3010
+ const content = await readFile(args.configFile, "utf-8");
3011
+ const parsed = JSON.parse(content);
3012
+ return normalizeConfig(parsed);
3013
+ } catch (error) {
3014
+ if (error.code === "ENOENT") {
3015
+ console.error(`Config file not found: ${args.configFile}`);
3016
+ throw error;
3017
+ } else {
3018
+ console.error(`Failed to load config from ${args.configFile}:`, error);
3019
+ throw error;
3020
+ }
3021
+ }
3022
+ }
3023
+ const defaultConfigPath = resolve(process5.cwd(), "mcpc.config.json");
3024
+ try {
3025
+ const content = await readFile(defaultConfigPath, "utf-8");
3026
+ const parsed = JSON.parse(content);
3027
+ return normalizeConfig(parsed);
3028
+ } catch (error) {
3029
+ if (error.code === "ENOENT") {
3030
+ return null;
3031
+ } else {
3032
+ console.error(`Failed to load config from ${defaultConfigPath}:`, error);
3033
+ throw error;
3034
+ }
3035
+ }
3036
+ }
3037
+ function replaceEnvVars(str) {
3038
+ return str.replace(/\$([A-Z_][A-Z0-9_]*)/g, (_match, varName) => {
3039
+ return process5.env[varName] || "";
3040
+ });
3041
+ }
3042
+ function replaceEnvVarsInConfig(obj) {
3043
+ if (typeof obj === "string") {
3044
+ return replaceEnvVars(obj);
3045
+ }
3046
+ if (Array.isArray(obj)) {
3047
+ return obj.map((item) => replaceEnvVarsInConfig(item));
3048
+ }
3049
+ if (obj && typeof obj === "object") {
3050
+ const result = {};
3051
+ for (const [key, value] of Object.entries(obj)) {
3052
+ result[key] = replaceEnvVarsInConfig(value);
3053
+ }
3054
+ return result;
3055
+ }
3056
+ return obj;
3057
+ }
3058
+ function normalizeConfig(config2) {
3059
+ config2 = replaceEnvVarsInConfig(config2);
3060
+ if (Array.isArray(config2)) {
3061
+ return {
3062
+ name: "mcpc-server",
3063
+ version: "0.1.0",
3064
+ agents: normalizeAgents(config2)
3065
+ };
3066
+ }
3067
+ if (config2 && typeof config2 === "object") {
3068
+ const cfg = config2;
3069
+ return {
3070
+ name: cfg.name || "mcpc-server",
3071
+ version: cfg.version || "0.1.0",
3072
+ capabilities: cfg.capabilities,
3073
+ agents: normalizeAgents(cfg.agents || [])
3074
+ };
3075
+ }
3076
+ throw new Error("Invalid configuration format");
3077
+ }
3078
+ function normalizeAgents(agents) {
3079
+ return agents.map((agent) => {
3080
+ if (agent.deps && !agent.deps.mcpServers) {
3081
+ agent.deps.mcpServers = {};
3082
+ }
3083
+ return agent;
3084
+ });
3085
+ }
3086
+
3087
+ // ../__mcpc__cli_0.1.1-beta.1/node_modules/@mcpc/cli/src/bin.ts
3088
+ var config = await loadConfig();
3089
+ if (config) {
3090
+ console.error(`Loaded configuration with ${config.agents.length} agent(s)`);
3091
+ } else {
3092
+ console.error("No configuration found, using default example configuration");
3093
+ }
3094
+ var server = await createServer(config || void 0);
3095
+ var transport = new StdioServerTransport();
3096
+ await server.connect(transport);