@mcpc-tech/cli 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (6) hide show
  1. package/bin/mcpc.mjs +97017 -0
  2. package/package.json +7 -19
  3. package/app.mjs +0 -4269
  4. package/bin.mjs +0 -4171
  5. package/index.mjs +0 -4483
  6. package/server.mjs +0 -4470
package/index.mjs DELETED
@@ -1,4483 +0,0 @@
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_latest/node_modules/@jsr/mcpc__core/src/utils/schema.js
13
- function jsonSchema(schema, options = {}) {
14
- if (isWrappedSchema(schema)) {
15
- return schema;
16
- }
17
- return {
18
- [schemaSymbol]: true,
19
- [validatorSymbol]: true,
20
- _type: void 0,
21
- jsonSchema: schema,
22
- validate: options.validate
23
- };
24
- }
25
- function isWrappedSchema(value) {
26
- return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true;
27
- }
28
- function extractJsonSchema(schema) {
29
- if (isWrappedSchema(schema)) {
30
- return schema.jsonSchema;
31
- }
32
- return schema;
33
- }
34
- var schemaSymbol, validatorSymbol;
35
- var init_schema = __esm({
36
- "../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/schema.js"() {
37
- schemaSymbol = Symbol.for("mcpc.schema");
38
- validatorSymbol = Symbol.for("mcpc.validator");
39
- }
40
- });
41
-
42
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/logger.js
43
- function createLogger(name, server) {
44
- return new MCPLogger(name, server);
45
- }
46
- var LOG_LEVELS, MCPLogger, logger;
47
- var init_logger = __esm({
48
- "../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/logger.js"() {
49
- LOG_LEVELS = {
50
- debug: 0,
51
- info: 1,
52
- notice: 2,
53
- warning: 3,
54
- error: 4,
55
- critical: 5,
56
- alert: 6,
57
- emergency: 7
58
- };
59
- MCPLogger = class _MCPLogger {
60
- server;
61
- loggerName;
62
- minLevel = "debug";
63
- constructor(loggerName = "mcpc", server) {
64
- this.loggerName = loggerName;
65
- this.server = server;
66
- }
67
- setServer(server) {
68
- this.server = server;
69
- }
70
- setLevel(level) {
71
- this.minLevel = level;
72
- }
73
- async log(level, data) {
74
- if (LOG_LEVELS[level] < LOG_LEVELS[this.minLevel]) {
75
- return;
76
- }
77
- this.logToConsole(level, data);
78
- if (this.server) {
79
- try {
80
- await this.server.sendLoggingMessage({
81
- level,
82
- logger: this.loggerName,
83
- data
84
- });
85
- } catch {
86
- }
87
- }
88
- }
89
- logToConsole(level, data) {
90
- const message = typeof data === "string" ? data : JSON.stringify(data);
91
- const prefix = `[${this.loggerName}]`;
92
- if (level === "debug") {
93
- console.debug(prefix, message);
94
- } else if (level === "info" || level === "notice") {
95
- console.info(prefix, message);
96
- } else if (level === "warning") {
97
- console.warn(prefix, message);
98
- } else {
99
- console.error(prefix, message);
100
- }
101
- }
102
- debug(data) {
103
- return this.log("debug", data);
104
- }
105
- info(data) {
106
- return this.log("info", data);
107
- }
108
- notice(data) {
109
- return this.log("notice", data);
110
- }
111
- warning(data) {
112
- return this.log("warning", data);
113
- }
114
- error(data) {
115
- return this.log("error", data);
116
- }
117
- critical(data) {
118
- return this.log("critical", data);
119
- }
120
- alert(data) {
121
- return this.log("alert", data);
122
- }
123
- emergency(data) {
124
- return this.log("emergency", data);
125
- }
126
- child(name) {
127
- const child = new _MCPLogger(`${this.loggerName}.${name}`, this.server);
128
- child.setLevel(this.minLevel);
129
- return child;
130
- }
131
- };
132
- logger = new MCPLogger("mcpc");
133
- }
134
- });
135
-
136
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/config-plugin.js
137
- var createConfigPlugin, config_plugin_default;
138
- var init_config_plugin = __esm({
139
- "../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/config-plugin.js"() {
140
- createConfigPlugin = () => ({
141
- name: "built-in-config",
142
- version: "1.0.0",
143
- enforce: "pre",
144
- transformTool: (tool, context2) => {
145
- const server = context2.server;
146
- const config2 = server.findToolConfig?.(context2.toolName);
147
- if (config2?.description) {
148
- tool.description = config2.description;
149
- }
150
- return tool;
151
- }
152
- });
153
- config_plugin_default = createConfigPlugin();
154
- }
155
- });
156
-
157
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/tool-name-mapping-plugin.js
158
- var createToolNameMappingPlugin, tool_name_mapping_plugin_default;
159
- var init_tool_name_mapping_plugin = __esm({
160
- "../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/tool-name-mapping-plugin.js"() {
161
- createToolNameMappingPlugin = () => ({
162
- name: "built-in-tool-name-mapping",
163
- version: "1.0.0",
164
- enforce: "pre",
165
- transformTool: (tool, context2) => {
166
- const server = context2.server;
167
- const toolName = context2.toolName;
168
- const dotNotation = toolName.replace(/_/g, ".");
169
- const underscoreNotation = toolName.replace(/\./g, "_");
170
- if (dotNotation !== toolName && server.toolNameMapping) {
171
- server.toolNameMapping.set(dotNotation, toolName);
172
- server.toolNameMapping.set(toolName, dotNotation);
173
- }
174
- if (underscoreNotation !== toolName && server.toolNameMapping) {
175
- server.toolNameMapping.set(underscoreNotation, toolName);
176
- server.toolNameMapping.set(toolName, underscoreNotation);
177
- }
178
- return tool;
179
- }
180
- });
181
- tool_name_mapping_plugin_default = createToolNameMappingPlugin();
182
- }
183
- });
184
-
185
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/logging-plugin.js
186
- var createLoggingPlugin, logging_plugin_default;
187
- var init_logging_plugin = __esm({
188
- "../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/logging-plugin.js"() {
189
- init_logger();
190
- createLoggingPlugin = (options = {}) => {
191
- const { enabled = true, verbose = false, compact: compact2 = true } = options;
192
- return {
193
- name: "built-in-logging",
194
- version: "1.0.0",
195
- composeEnd: async (context2) => {
196
- if (!enabled) return;
197
- const logger2 = createLogger("mcpc.plugin.logging", context2.server);
198
- if (compact2) {
199
- const pluginCount = context2.pluginNames.length;
200
- const { stats } = context2;
201
- await logger2.info(`[${context2.toolName}] ${pluginCount} plugins \u2022 ${stats.publicTools} public \u2022 ${stats.hiddenTools} hidden`);
202
- } else if (verbose) {
203
- await logger2.info(`[${context2.toolName}] Composition complete`);
204
- await logger2.info(` \u251C\u2500 Plugins: ${context2.pluginNames.join(", ")}`);
205
- const { stats } = context2;
206
- const server = context2.server;
207
- const publicTools = Array.from(new Set(server.getPublicToolNames().map(String)));
208
- const hiddenTools = Array.from(new Set(server.getHiddenToolNames().map(String)));
209
- if (publicTools.length > 0) {
210
- await logger2.info(` \u251C\u2500 Public: ${publicTools.join(", ")}`);
211
- }
212
- if (hiddenTools.length > 0) {
213
- await logger2.info(` \u251C\u2500 Hidden: ${hiddenTools.join(", ")}`);
214
- }
215
- await logger2.info(` \u2514\u2500 Total: ${stats.totalTools} tools`);
216
- }
217
- }
218
- };
219
- };
220
- logging_plugin_default = createLoggingPlugin({
221
- verbose: true,
222
- compact: false
223
- });
224
- }
225
- });
226
-
227
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/index.js
228
- var built_in_exports = {};
229
- __export(built_in_exports, {
230
- createConfigPlugin: () => createConfigPlugin,
231
- createLoggingPlugin: () => createLoggingPlugin,
232
- createToolNameMappingPlugin: () => createToolNameMappingPlugin,
233
- getBuiltInPlugins: () => getBuiltInPlugins
234
- });
235
- function getBuiltInPlugins() {
236
- return [
237
- tool_name_mapping_plugin_default,
238
- config_plugin_default,
239
- logging_plugin_default
240
- ];
241
- }
242
- var init_built_in = __esm({
243
- "../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/index.js"() {
244
- init_config_plugin();
245
- init_tool_name_mapping_plugin();
246
- init_logging_plugin();
247
- init_config_plugin();
248
- init_tool_name_mapping_plugin();
249
- init_logging_plugin();
250
- }
251
- });
252
-
253
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugin-utils.js
254
- var plugin_utils_exports = {};
255
- __export(plugin_utils_exports, {
256
- checkCircularDependencies: () => checkCircularDependencies,
257
- clearPluginCache: () => clearPluginCache,
258
- getPluginsWithHook: () => getPluginsWithHook,
259
- isValidPlugin: () => isValidPlugin,
260
- loadPlugin: () => loadPlugin,
261
- shouldApplyPlugin: () => shouldApplyPlugin,
262
- sortPluginsByOrder: () => sortPluginsByOrder,
263
- validatePlugins: () => validatePlugins
264
- });
265
- function shouldApplyPlugin(plugin, mode) {
266
- if (!plugin.apply) return true;
267
- if (typeof plugin.apply === "string") {
268
- return mode.includes(plugin.apply);
269
- }
270
- if (typeof plugin.apply === "function") {
271
- try {
272
- return plugin.apply(mode);
273
- } catch (error) {
274
- console.warn(`Plugin "${plugin.name}" apply function failed: ${error}. Defaulting to true.`);
275
- return true;
276
- }
277
- }
278
- return true;
279
- }
280
- function sortPluginsByOrder(plugins) {
281
- const pluginMap = /* @__PURE__ */ new Map();
282
- for (const plugin of plugins) {
283
- pluginMap.set(plugin.name, plugin);
284
- }
285
- const visited = /* @__PURE__ */ new Set();
286
- const sorted = [];
287
- function visit(plugin) {
288
- if (visited.has(plugin.name)) return;
289
- visited.add(plugin.name);
290
- if (plugin.dependencies) {
291
- for (const depName of plugin.dependencies) {
292
- const dep = pluginMap.get(depName);
293
- if (dep) {
294
- visit(dep);
295
- } else {
296
- console.warn(`Plugin "${plugin.name}" depends on "${depName}" which is not loaded`);
297
- }
298
- }
299
- }
300
- sorted.push(plugin);
301
- }
302
- const prePlugins = plugins.filter((p2) => p2.enforce === "pre");
303
- const normalPlugins = plugins.filter((p2) => !p2.enforce);
304
- const postPlugins = plugins.filter((p2) => p2.enforce === "post");
305
- [
306
- ...prePlugins,
307
- ...normalPlugins,
308
- ...postPlugins
309
- ].forEach(visit);
310
- return sorted;
311
- }
312
- function getPluginsWithHook(plugins, hookName) {
313
- return plugins.filter((p2) => typeof p2[hookName] === "function");
314
- }
315
- function isValidPlugin(plugin) {
316
- if (!plugin || typeof plugin !== "object") return false;
317
- const p2 = plugin;
318
- if (!p2.name || typeof p2.name !== "string" || p2.name.trim() === "") {
319
- return false;
320
- }
321
- const hasHook = typeof p2.configureServer === "function" || typeof p2.composeStart === "function" || typeof p2.transformTool === "function" || typeof p2.finalizeComposition === "function" || typeof p2.composeEnd === "function" || typeof p2.transformInput === "function" || typeof p2.transformOutput === "function" || typeof p2.dispose === "function";
322
- if (!hasHook) return false;
323
- if (p2.enforce && p2.enforce !== "pre" && p2.enforce !== "post") {
324
- return false;
325
- }
326
- if (p2.apply && typeof p2.apply !== "string" && typeof p2.apply !== "function") {
327
- return false;
328
- }
329
- if (p2.dependencies && !Array.isArray(p2.dependencies)) {
330
- return false;
331
- }
332
- return true;
333
- }
334
- function parseQueryParams(params) {
335
- const typedParams = {};
336
- for (const [key, value] of Object.entries(params)) {
337
- const numValue = Number(value);
338
- if (!isNaN(numValue) && value.trim() !== "") {
339
- typedParams[key] = numValue;
340
- continue;
341
- }
342
- if (value === "true") {
343
- typedParams[key] = true;
344
- continue;
345
- }
346
- if (value === "false") {
347
- typedParams[key] = false;
348
- continue;
349
- }
350
- if (value.includes(",")) {
351
- typedParams[key] = value.split(",").map((v) => v.trim());
352
- continue;
353
- }
354
- typedParams[key] = value;
355
- }
356
- return typedParams;
357
- }
358
- async function loadPlugin(pluginPath, options = {
359
- cache: true
360
- }) {
361
- if (options.cache && pluginCache.has(pluginPath)) {
362
- return pluginCache.get(pluginPath);
363
- }
364
- try {
365
- const [rawPath, queryString] = pluginPath.split("?", 2);
366
- const searchParams = new URLSearchParams(queryString || "");
367
- const params = Object.fromEntries(searchParams.entries());
368
- const importPath = rawPath;
369
- const pluginModule = await import(importPath);
370
- const pluginFactory = pluginModule.createPlugin;
371
- const defaultPlugin = pluginModule.default;
372
- let plugin;
373
- if (Object.keys(params).length > 0) {
374
- if (typeof pluginFactory !== "function") {
375
- throw new Error(`Plugin "${rawPath}" has parameters but no createPlugin export function`);
376
- }
377
- const typedParams = parseQueryParams(params);
378
- plugin = pluginFactory(typedParams);
379
- } else {
380
- if (defaultPlugin) {
381
- plugin = defaultPlugin;
382
- } else if (typeof pluginFactory === "function") {
383
- plugin = pluginFactory();
384
- } else {
385
- throw new Error(`Plugin "${rawPath}" has no default export or createPlugin function`);
386
- }
387
- }
388
- if (!isValidPlugin(plugin)) {
389
- throw new Error(`Invalid plugin format in "${rawPath}": must have a unique name and at least one lifecycle hook`);
390
- }
391
- if (options.cache) {
392
- pluginCache.set(pluginPath, plugin);
393
- }
394
- return plugin;
395
- } catch (error) {
396
- const errorMsg = error instanceof Error ? error.message : String(error);
397
- throw new Error(`Failed to load plugin from "${pluginPath}": ${errorMsg}`);
398
- }
399
- }
400
- function clearPluginCache() {
401
- pluginCache.clear();
402
- }
403
- function checkCircularDependencies(plugins) {
404
- const errors = [];
405
- const pluginMap = /* @__PURE__ */ new Map();
406
- for (const plugin of plugins) {
407
- pluginMap.set(plugin.name, plugin);
408
- }
409
- function checkCircular(pluginName, visited, path) {
410
- if (visited.has(pluginName)) {
411
- const cycle = [
412
- ...path,
413
- pluginName
414
- ].join(" -> ");
415
- errors.push(`Circular dependency detected: ${cycle}`);
416
- return;
417
- }
418
- const plugin = pluginMap.get(pluginName);
419
- if (!plugin || !plugin.dependencies) return;
420
- visited.add(pluginName);
421
- path.push(pluginName);
422
- for (const dep of plugin.dependencies) {
423
- checkCircular(dep, new Set(visited), [
424
- ...path
425
- ]);
426
- }
427
- }
428
- for (const plugin of plugins) {
429
- checkCircular(plugin.name, /* @__PURE__ */ new Set(), []);
430
- }
431
- return errors;
432
- }
433
- function validatePlugins(plugins) {
434
- const errors = [];
435
- const names = /* @__PURE__ */ new Map();
436
- for (const plugin of plugins) {
437
- const count = names.get(plugin.name) || 0;
438
- names.set(plugin.name, count + 1);
439
- }
440
- for (const [name, count] of names.entries()) {
441
- if (count > 1) {
442
- errors.push(`Duplicate plugin name: "${name}" (${count} instances)`);
443
- }
444
- }
445
- const circularErrors = checkCircularDependencies(plugins);
446
- errors.push(...circularErrors);
447
- for (const plugin of plugins) {
448
- if (!isValidPlugin(plugin)) {
449
- const name = plugin.name || "unknown";
450
- errors.push(`Invalid plugin: "${name}"`);
451
- }
452
- }
453
- return {
454
- valid: errors.length === 0,
455
- errors
456
- };
457
- }
458
- var pluginCache;
459
- var init_plugin_utils = __esm({
460
- "../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugin-utils.js"() {
461
- pluginCache = /* @__PURE__ */ new Map();
462
- }
463
- });
464
-
465
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/schema.js
466
- import traverse from "json-schema-traverse";
467
- function updateRefPaths(schema, wrapperPath) {
468
- if (!schema || typeof schema !== "object") {
469
- return schema;
470
- }
471
- if (!wrapperPath || typeof wrapperPath !== "string") {
472
- throw new Error("wrapperPath must be a non-empty string");
473
- }
474
- const clonedSchema = JSON.parse(JSON.stringify(schema));
475
- try {
476
- traverse(clonedSchema, {
477
- allKeys: true,
478
- cb: function(schemaNode, _jsonPtr, _rootSchema, _parentJsonPtr, _parentKeyword, _parentSchema, _keyIndex) {
479
- if (schemaNode && typeof schemaNode === "object" && schemaNode.$ref) {
480
- const ref = schemaNode.$ref;
481
- if (ref.startsWith("#/properties/")) {
482
- const relativePath = ref.substring(13);
483
- schemaNode.$ref = `#/properties/${wrapperPath}/properties/${relativePath}`;
484
- } else if (ref === "#") {
485
- schemaNode.$ref = `#/properties/${wrapperPath}`;
486
- }
487
- }
488
- }
489
- });
490
- } catch (error) {
491
- console.warn(`Failed to traverse schema for path "${wrapperPath}":`, error);
492
- return clonedSchema;
493
- }
494
- return clonedSchema;
495
- }
496
- var init_schema2 = __esm({
497
- "../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/schema.js"() {
498
- }
499
- });
500
-
501
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/compose-helpers.js
502
- var compose_helpers_exports = {};
503
- __export(compose_helpers_exports, {
504
- buildDependencyGroups: () => buildDependencyGroups,
505
- processToolsWithPlugins: () => processToolsWithPlugins,
506
- registerGlobalTools: () => registerGlobalTools
507
- });
508
- async function processToolsWithPlugins(server, externalTools, mode) {
509
- const toolManager = server.toolManager;
510
- const pluginManager = server.pluginManager;
511
- for (const [toolId, toolData] of toolManager.getToolEntries()) {
512
- const defaultSchema = {
513
- type: "object",
514
- properties: {},
515
- additionalProperties: true
516
- };
517
- const tempTool = {
518
- name: toolId,
519
- description: toolData.description,
520
- inputSchema: toolData.schema || defaultSchema,
521
- execute: toolData.callback
522
- };
523
- const processedTool = await pluginManager.applyTransformToolHooks(tempTool, {
524
- toolName: toolId,
525
- server,
526
- mode,
527
- originalTool: {
528
- ...tempTool
529
- },
530
- transformationIndex: 0
531
- });
532
- toolManager.registerTool(toolId, processedTool.description || toolData.description, processedTool.inputSchema, processedTool.execute);
533
- if (externalTools[toolId]) {
534
- try {
535
- const builtIn = await Promise.resolve().then(() => (init_built_in(), built_in_exports));
536
- if (builtIn && typeof builtIn.processToolVisibility === "function") {
537
- builtIn.processToolVisibility(toolId, processedTool, server, externalTools);
538
- }
539
- } catch {
540
- }
541
- externalTools[toolId] = processedTool;
542
- }
543
- }
544
- }
545
- function buildDependencyGroups(toolNameToDetailList, hiddenToolNames, publicToolNames, server) {
546
- const depGroups = {};
547
- const toolManager = server.toolManager;
548
- toolNameToDetailList.forEach(([toolName, tool]) => {
549
- const resolvedName = toolManager.resolveToolName(toolName);
550
- if (hiddenToolNames.includes(resolvedName ?? "") || publicToolNames.includes(resolvedName ?? "")) {
551
- return;
552
- }
553
- if (!tool) {
554
- const allToolNames = [
555
- ...toolNameToDetailList.map(([n]) => n)
556
- ];
557
- throw new Error(`Action ${toolName} not found, available action list: ${allToolNames.join(", ")}`);
558
- }
559
- const baseSchema = tool.inputSchema.jsonSchema ?? tool.inputSchema ?? {
560
- type: "object",
561
- properties: {},
562
- required: []
563
- };
564
- const baseProperties = baseSchema.type === "object" && baseSchema.properties ? baseSchema.properties : {};
565
- const baseRequired = baseSchema.type === "object" && Array.isArray(baseSchema.required) ? baseSchema.required : [];
566
- const updatedProperties = updateRefPaths(baseProperties, toolName);
567
- depGroups[toolName] = {
568
- type: "object",
569
- description: tool.description,
570
- properties: updatedProperties,
571
- required: [
572
- ...baseRequired
573
- ],
574
- additionalProperties: false
575
- };
576
- });
577
- return depGroups;
578
- }
579
- function registerGlobalTools(globalToolNames, tools, server) {
580
- globalToolNames.forEach((toolId) => {
581
- const tool = tools[toolId];
582
- if (!tool) {
583
- throw new Error(`Global tool ${toolId} not found in registry, available: ${Object.keys(tools).join(", ")}`);
584
- }
585
- server.tool(toolId, tool.description || "No description available", jsonSchema(tool.inputSchema), tool.execute);
586
- });
587
- }
588
- var init_compose_helpers = __esm({
589
- "../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/compose-helpers.js"() {
590
- init_schema2();
591
- init_schema();
592
- }
593
- });
594
-
595
- // ../__mcpc__cli_latest/node_modules/@mcpc/cli/src/app.js
596
- import { OpenAPIHono } from "@hono/zod-openapi";
597
-
598
- // ../__mcpc__cli_latest/node_modules/@mcpc/cli/src/controllers/messages.controller.js
599
- import { createRoute } from "@hono/zod-openapi";
600
- import { z } from "zod";
601
-
602
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__utils/src/transport/sse.js
603
- import { JSONRPCMessageSchema } from "@modelcontextprotocol/sdk/types.js";
604
-
605
- // ../__mcpc__cli_latest/node_modules/@jsr/std__http/server_sent_event_stream.js
606
- var NEWLINE_REGEXP = /\r\n|\r|\n/;
607
- var encoder = new TextEncoder();
608
- function assertHasNoNewline(value, varName, errPrefix) {
609
- if (value.match(NEWLINE_REGEXP) !== null) {
610
- throw new SyntaxError(`${errPrefix}: ${varName} cannot contain a newline`);
611
- }
612
- }
613
- function stringify(message) {
614
- const lines = [];
615
- if (message.comment) {
616
- assertHasNoNewline(message.comment, "`message.comment`", "Cannot serialize message");
617
- lines.push(`:${message.comment}`);
618
- }
619
- if (message.event) {
620
- assertHasNoNewline(message.event, "`message.event`", "Cannot serialize message");
621
- lines.push(`event:${message.event}`);
622
- }
623
- if (message.data) {
624
- message.data.split(NEWLINE_REGEXP).forEach((line) => lines.push(`data:${line}`));
625
- }
626
- if (message.id) {
627
- assertHasNoNewline(message.id.toString(), "`message.id`", "Cannot serialize message");
628
- lines.push(`id:${message.id}`);
629
- }
630
- if (message.retry) lines.push(`retry:${message.retry}`);
631
- return encoder.encode(lines.join("\n") + "\n\n");
632
- }
633
- var ServerSentEventStream = class extends TransformStream {
634
- constructor() {
635
- super({
636
- transform: (message, controller) => {
637
- controller.enqueue(stringify(message));
638
- }
639
- });
640
- }
641
- };
642
-
643
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__utils/src/transport/sse.js
644
- var transports = /* @__PURE__ */ new Map();
645
- async function handleConnecting(request, createServer2, incomingMsgRoutePath) {
646
- const url = new URL(request.url);
647
- const sessionId = url.searchParams.get("sessionId");
648
- const endpoint = `${incomingMsgRoutePath}`;
649
- if (sessionId) {
650
- if (transports.has(sessionId)) {
651
- const transport2 = transports.get(sessionId);
652
- return Promise.resolve(transport2.sseResponse);
653
- } else {
654
- return Promise.resolve(new Response("Invalid or expired sessionId", {
655
- status: 404
656
- }));
657
- }
658
- }
659
- const server = await createServer2();
660
- const transport = new SSEServerTransport(endpoint);
661
- const newSessionId = transport.sessionId;
662
- transports.set(newSessionId, transport);
663
- server.connect(transport);
664
- request.signal.addEventListener("abort", () => {
665
- console.log(`HTTP connection aborted for session: ${transport.sessionId}`);
666
- transport.close();
667
- }, {
668
- once: true
669
- });
670
- return Promise.resolve(transport.sseResponse);
671
- }
672
- async function handleIncoming(request) {
673
- const url = new URL(request.url);
674
- const sessionId = url.searchParams.get("sessionId");
675
- if (!sessionId) {
676
- return new Response("Missing sessionId parameter", {
677
- status: 400
678
- });
679
- }
680
- const transport = transports.get(sessionId);
681
- if (!transport) {
682
- return new Response("Invalid or expired sessionId", {
683
- status: 404
684
- });
685
- }
686
- if (!transport.isConnected) {
687
- return new Response("SSE connection not established", {
688
- status: 500
689
- });
690
- }
691
- const contentTypeHeader = request.headers.get("content-type");
692
- if (!contentTypeHeader?.includes("application/json")) {
693
- return new Response("Unsupported content-type: Expected application/json", {
694
- status: 415
695
- });
696
- }
697
- try {
698
- return await transport.handlePostMessage(request);
699
- } catch (error) {
700
- const errorMessage = error instanceof Error ? error.message : String(error);
701
- return new Response(errorMessage, {
702
- status: 400
703
- });
704
- }
705
- }
706
- var SSEServerTransport = class {
707
- #sseResponse;
708
- #sessionId;
709
- #controller;
710
- #stream;
711
- #endpoint;
712
- onclose;
713
- onerror;
714
- onmessage;
715
- /**
716
- * Creates a new SSE server transport, which will direct the client to POST messages to the relative or absolute URL identified by `endpoint`.
717
- */
718
- constructor(endpoint) {
719
- this.#endpoint = endpoint;
720
- this.#sessionId = crypto.randomUUID();
721
- this.#stream = new ReadableStream({
722
- start: (controller) => {
723
- this.#controller = controller;
724
- },
725
- // Caveat: cancel() reliably fires on client disconnect in Deno only; use request.signal "abort" for cross-runtime cleanup.
726
- cancel: () => {
727
- this.#controller = void 0;
728
- this.close();
729
- }
730
- }).pipeThrough(
731
- // Support standard sse stream chunk syntax
732
- new ServerSentEventStream()
733
- );
734
- }
735
- /**
736
- * Handles the initial SSE connection request.
737
- *
738
- * This should be called when a GET request is made to establish the SSE stream.
739
- */
740
- async start() {
741
- if (this.#sseResponse) {
742
- throw new Error("SSEServerTransport already started! If using Server class, note that connect() calls start() automatically.");
743
- }
744
- this.#controller?.enqueue({
745
- event: "endpoint",
746
- data: `${this.#endpoint}?sessionId=${this.#sessionId}`,
747
- id: Date.now().toString()
748
- });
749
- this.#sseResponse = new Response(this.#stream, {
750
- status: 200,
751
- statusText: "OK",
752
- headers: {
753
- "Content-Type": "text/event-stream",
754
- "Cache-Control": "no-cache",
755
- Connection: "keep-alive"
756
- }
757
- });
758
- await Promise.resolve();
759
- }
760
- /**
761
- * Handles incoming POST messages.
762
- *
763
- * This should be called when a POST request is made to send a message to the server.
764
- */
765
- async handlePostMessage(request) {
766
- if (!this.#sseResponse) {
767
- const message = "SSE connection not established";
768
- return new Response(message, {
769
- status: 500
770
- });
771
- }
772
- try {
773
- const contentType = request.headers.get("content-type") || "";
774
- if (!contentType.includes("application/json")) {
775
- throw new Error(`Unsupported content-type: ${contentType}`);
776
- }
777
- const body = await request.json();
778
- await this.handleMessage(body);
779
- return new Response("Accepted", {
780
- status: 202
781
- });
782
- } catch (error) {
783
- console.log(error);
784
- this.onerror?.(error instanceof Error ? error : new Error(String(error)));
785
- return new Response(String(error), {
786
- status: 400
787
- });
788
- }
789
- }
790
- /**
791
- * Handle a client message, regardless of how it arrived. This can be used to inform the server of messages that arrive via a means different than HTTP POST.
792
- */
793
- async handleMessage(message) {
794
- let parsedMessage;
795
- try {
796
- parsedMessage = JSONRPCMessageSchema.parse(message);
797
- } catch (error) {
798
- this.onerror?.(error instanceof Error ? error : new Error(String(error)));
799
- throw error;
800
- }
801
- this.onmessage?.(parsedMessage);
802
- await Promise.resolve();
803
- }
804
- async close() {
805
- transports.delete(this.#sessionId);
806
- this.#controller?.close();
807
- this.#controller = void 0;
808
- this.onclose?.();
809
- await Promise.resolve();
810
- }
811
- async send(message) {
812
- if (!this.#controller) {
813
- throw new Error("Not connected");
814
- }
815
- this.#controller.enqueue({
816
- data: JSON.stringify(message),
817
- event: "message",
818
- id: Date.now().toString()
819
- });
820
- await Promise.resolve();
821
- }
822
- /**
823
- * Returns the session ID for this transport.
824
- *
825
- * This can be used to route incoming POST requests.
826
- */
827
- get sessionId() {
828
- return this.#sessionId;
829
- }
830
- get sseStream() {
831
- return this.#stream;
832
- }
833
- get sseResponse() {
834
- return this.#sseResponse;
835
- }
836
- get isConnected() {
837
- return this.#controller !== void 0;
838
- }
839
- };
840
-
841
- // ../__mcpc__cli_latest/node_modules/@mcpc/cli/src/controllers/messages.controller.js
842
- var messageHandler = (app2) => app2.openapi(createRoute({
843
- hide: true,
844
- method: "post",
845
- path: `/messages`,
846
- responses: {
847
- 200: {
848
- content: {
849
- "text/event-stream": {
850
- schema: z.any()
851
- }
852
- },
853
- description: "Returns the processed message"
854
- },
855
- 400: {
856
- content: {
857
- "application/json": {
858
- schema: z.any()
859
- }
860
- },
861
- description: "Returns an error"
862
- }
863
- }
864
- }), async (c) => {
865
- const response = await handleIncoming(c.req.raw);
866
- return response;
867
- }, (result, c) => {
868
- if (!result.success) {
869
- return c.json({
870
- code: 400,
871
- message: result.error.message
872
- }, 400);
873
- }
874
- });
875
-
876
- // ../__mcpc__cli_latest/node_modules/@mcpc/cli/src/controllers/sse.controller.js
877
- import { createRoute as createRoute2, z as z2 } from "@hono/zod-openapi";
878
- var sseHandler = (app2) => app2.openapi(createRoute2({
879
- hide: true,
880
- method: "get",
881
- path: "/sse",
882
- responses: {
883
- 200: {
884
- content: {
885
- "text/event-stream": {
886
- schema: z2.any()
887
- }
888
- },
889
- description: "Returns the processed message"
890
- },
891
- 400: {
892
- content: {
893
- "application/json": {
894
- schema: z2.any()
895
- }
896
- },
897
- description: "Returns an error"
898
- }
899
- }
900
- }), async (c) => {
901
- const response = await handleConnecting(c.req.raw, createServer, "/core/messages");
902
- return response;
903
- }, (result, c) => {
904
- if (!result.success) {
905
- return c.json({
906
- code: 400,
907
- message: result.error.message
908
- }, 400);
909
- }
910
- });
911
-
912
- // ../__mcpc__cli_latest/node_modules/@mcpc/cli/src/controllers/core.controller.js
913
- var coreHandler = (app2) => {
914
- app2.doc("/core-docs", {
915
- openapi: "3.0.0",
916
- info: {
917
- title: "tencentcloudapi openapi spec",
918
- version: "1.0.0",
919
- description: "openapi definition of tencentcloudapi"
920
- }
921
- });
922
- };
923
-
924
- // ../__mcpc__cli_latest/node_modules/@mcpc/cli/src/controllers/register.js
925
- var registerAgent = (app2) => {
926
- messageHandler(app2);
927
- sseHandler(app2);
928
- coreHandler(app2);
929
- };
930
-
931
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/compose.js
932
- init_schema();
933
- import { CallToolRequestSchema, ListToolsRequestSchema, SetLevelRequestSchema } from "@modelcontextprotocol/sdk/types.js";
934
- import { Server } from "@modelcontextprotocol/sdk/server/index.js";
935
-
936
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__utils/src/json.js
937
- import { jsonrepair } from "jsonrepair";
938
- function stripMarkdownAndText(text) {
939
- text = text.trim();
940
- text = text.replace(/^```(?:json)?\s*\n?/i, "");
941
- text = text.replace(/\n?```\s*$/, "");
942
- text = text.replace(/^(?:here is|here's|response|result|output|json):\s*/i, "");
943
- const jsonMatch = text.match(/(\{[\s\S]*\}|\[[\s\S]*\])/);
944
- if (jsonMatch) {
945
- text = jsonMatch[1];
946
- }
947
- return text.trim();
948
- }
949
- function parseJSON(text, throwError) {
950
- try {
951
- return JSON.parse(text);
952
- } catch (_error) {
953
- try {
954
- const cleanedText = stripMarkdownAndText(text);
955
- try {
956
- return JSON.parse(cleanedText);
957
- } catch {
958
- const repairedText = jsonrepair(cleanedText);
959
- console.warn(`Failed to parse JSON, cleaned and repaired. Original: ${text.slice(0, 100)}...`);
960
- return JSON.parse(repairedText);
961
- }
962
- } catch (_repairError) {
963
- if (throwError) {
964
- throw new Error(`Failed to parse JSON after cleanup and repair. Original error: ${_error instanceof Error ? _error.message : String(_error)}`);
965
- }
966
- return null;
967
- }
968
- }
969
- }
970
-
971
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__utils/src/ai.js
972
- var p = (template, options = {}) => {
973
- const { missingVariableHandling = "warn" } = options;
974
- const names = /* @__PURE__ */ new Set();
975
- const regex = /\{((\w|\.)+)\}/g;
976
- let match;
977
- while ((match = regex.exec(template)) !== null) {
978
- names.add(match[1]);
979
- }
980
- const required = Array.from(names);
981
- return (input) => {
982
- let result = template;
983
- for (const name of required) {
984
- const key = name;
985
- const value = input[key];
986
- const re = new RegExp(`\\{${String(name)}\\}`, "g");
987
- if (value !== void 0 && value !== null) {
988
- result = result.replace(re, String(value));
989
- } else {
990
- switch (missingVariableHandling) {
991
- case "error":
992
- throw new Error(`Missing variable "${String(name)}" in input for template.`);
993
- case "empty":
994
- result = result.replace(re, "");
995
- break;
996
- case "warn":
997
- case "ignore":
998
- default:
999
- break;
1000
- }
1001
- }
1002
- }
1003
- return result;
1004
- };
1005
- };
1006
-
1007
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__utils/src/tool-tags.js
1008
- import { load } from "cheerio";
1009
- function parseTags(htmlString, tags) {
1010
- const $ = load(htmlString, {
1011
- xml: {
1012
- decodeEntities: false
1013
- }
1014
- });
1015
- const tagToResults = {};
1016
- for (const tag of tags) {
1017
- const elements = $(tag);
1018
- tagToResults[tag] = elements.toArray();
1019
- }
1020
- return {
1021
- tagToResults,
1022
- $
1023
- };
1024
- }
1025
-
1026
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/mcp.js
1027
- import { Client } from "@modelcontextprotocol/sdk/client/index.js";
1028
- import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
1029
- import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
1030
- import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
1031
-
1032
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/registory.js
1033
- function connectToSmitheryServer(smitheryConfig) {
1034
- const serverUrl = new URL(smitheryConfig.deploymentUrl);
1035
- serverUrl.searchParams.set("config", btoa(JSON.stringify(smitheryConfig.config)));
1036
- serverUrl.searchParams.set("api_key", smitheryConfig?.smitheryApiKey ?? smitheryConfig?.config?.smitheryApiKey);
1037
- return {
1038
- url: serverUrl.toString()
1039
- };
1040
- }
1041
- function smitheryToolNameCompatibale(name, scope) {
1042
- if (!name.startsWith("toolbox_")) {
1043
- return {
1044
- toolNameWithScope: `${scope}.${name}`,
1045
- toolName: name
1046
- };
1047
- }
1048
- const [, ...toolNames] = name.split("_");
1049
- const toolName = toolNames.join("_");
1050
- const toolNameWithScope = `${scope}.${toolName}`;
1051
- return {
1052
- toolNameWithScope,
1053
- toolName
1054
- };
1055
- }
1056
-
1057
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/mcp.js
1058
- import { cwd } from "node:process";
1059
- import process2 from "node:process";
1060
- import { createHash } from "node:crypto";
1061
- var mcpClientPool = /* @__PURE__ */ new Map();
1062
- var mcpClientConnecting = /* @__PURE__ */ new Map();
1063
- var shortHash = (s) => createHash("sha256").update(s).digest("hex").slice(0, 8);
1064
- function defSignature(def) {
1065
- return JSON.stringify(def);
1066
- }
1067
- async function getOrCreateMcpClient(defKey, def) {
1068
- const pooled = mcpClientPool.get(defKey);
1069
- if (pooled) {
1070
- pooled.refCount += 1;
1071
- return pooled.client;
1072
- }
1073
- const existingConnecting = mcpClientConnecting.get(defKey);
1074
- if (existingConnecting) {
1075
- const client = await existingConnecting;
1076
- const entry = mcpClientPool.get(defKey);
1077
- if (entry) entry.refCount += 1;
1078
- return client;
1079
- }
1080
- let transport;
1081
- if (typeof def.transportType === "string" && def.transportType === "sse") {
1082
- const options = {};
1083
- if (def.headers) {
1084
- options.requestInit = {
1085
- headers: def.headers
1086
- };
1087
- options.eventSourceInit = {
1088
- headers: def.headers
1089
- };
1090
- }
1091
- transport = new SSEClientTransport(new URL(def.url), options);
1092
- } else if ("url" in def && typeof def.url === "string") {
1093
- const options = {};
1094
- if (def.headers) {
1095
- options.requestInit = {
1096
- headers: def.headers
1097
- };
1098
- }
1099
- transport = new StreamableHTTPClientTransport(new URL(def.url), options);
1100
- } else if (typeof def.transportType === "string" && def.transportType === "stdio" || "command" in def) {
1101
- transport = new StdioClientTransport({
1102
- command: def.command,
1103
- args: def.args,
1104
- env: {
1105
- ...process2.env,
1106
- ...def.env ?? {}
1107
- },
1108
- cwd: cwd()
1109
- });
1110
- } else {
1111
- throw new Error(`Unsupported transport type: ${JSON.stringify(def)}`);
1112
- }
1113
- const connecting = (async () => {
1114
- const client = new Client({
1115
- name: `mcp_${shortHash(defSignature(def))}`,
1116
- version: "1.0.0"
1117
- });
1118
- await client.connect(transport, {
1119
- timeout: 6e4 * 10
1120
- });
1121
- return client;
1122
- })();
1123
- mcpClientConnecting.set(defKey, connecting);
1124
- try {
1125
- const client = await connecting;
1126
- mcpClientPool.set(defKey, {
1127
- client,
1128
- refCount: 1
1129
- });
1130
- return client;
1131
- } finally {
1132
- mcpClientConnecting.delete(defKey);
1133
- }
1134
- }
1135
- async function releaseMcpClient(defKey) {
1136
- const entry = mcpClientPool.get(defKey);
1137
- if (!entry) return;
1138
- entry.refCount -= 1;
1139
- if (entry.refCount <= 0) {
1140
- mcpClientPool.delete(defKey);
1141
- try {
1142
- await entry.client.close();
1143
- } catch (err) {
1144
- console.error("Error closing MCP client:", err);
1145
- }
1146
- }
1147
- }
1148
- var cleanupAllPooledClients = async () => {
1149
- const entries = Array.from(mcpClientPool.entries());
1150
- mcpClientPool.clear();
1151
- await Promise.all(entries.map(async ([, { client }]) => {
1152
- try {
1153
- await client.close();
1154
- } catch (err) {
1155
- console.error("Error closing MCP client:", err);
1156
- }
1157
- }));
1158
- };
1159
- process2.once?.("exit", () => {
1160
- cleanupAllPooledClients();
1161
- });
1162
- process2.once?.("SIGINT", () => {
1163
- cleanupAllPooledClients().finally(() => process2.exit(0));
1164
- });
1165
- async function composeMcpDepTools(mcpConfig, filterIn) {
1166
- const allTools = {};
1167
- const allClients = {};
1168
- const acquiredKeys = [];
1169
- for (const [name, definition] of Object.entries(mcpConfig.mcpServers)) {
1170
- const def = definition;
1171
- if (def.disabled) continue;
1172
- const defKey = shortHash(defSignature(def));
1173
- const serverId = name;
1174
- try {
1175
- const client = await getOrCreateMcpClient(defKey, def);
1176
- acquiredKeys.push(defKey);
1177
- allClients[serverId] = client;
1178
- const { tools } = await client.listTools();
1179
- tools.forEach((tool) => {
1180
- const { toolNameWithScope, toolName: internalToolName } = smitheryToolNameCompatibale(tool.name, name);
1181
- const toolId = `${serverId}_${internalToolName}`;
1182
- if (filterIn && !filterIn({
1183
- action: internalToolName,
1184
- tool,
1185
- mcpName: name,
1186
- toolNameWithScope,
1187
- internalToolName,
1188
- toolId
1189
- })) {
1190
- return;
1191
- }
1192
- const execute = (args) => allClients[serverId].callTool({
1193
- name: internalToolName,
1194
- arguments: args
1195
- }, void 0, {
1196
- timeout: def.toolCallTimeout
1197
- });
1198
- allTools[toolId] = {
1199
- ...tool,
1200
- execute
1201
- };
1202
- });
1203
- } catch (error) {
1204
- console.error(`Error creating MCP client for ${name}:`, error);
1205
- }
1206
- }
1207
- const cleanupClients = async () => {
1208
- await Promise.all(acquiredKeys.map((k) => releaseMcpClient(k)));
1209
- acquiredKeys.length = 0;
1210
- Object.keys(allTools).forEach((key) => delete allTools[key]);
1211
- Object.keys(allClients).forEach((key) => delete allClients[key]);
1212
- };
1213
- return {
1214
- tools: allTools,
1215
- clients: allClients,
1216
- cleanupClients
1217
- };
1218
- }
1219
-
1220
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/agentic/agentic-tool-registrar.js
1221
- init_schema();
1222
-
1223
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/config.js
1224
- import process3 from "node:process";
1225
- var GEMINI_PREFERRED_FORMAT = process3.env.GEMINI_PREFERRED_FORMAT === "0" ? false : true;
1226
-
1227
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/json.js
1228
- import { jsonrepair as jsonrepair2 } from "jsonrepair";
1229
- import { inspect } from "node:util";
1230
-
1231
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/provider.js
1232
- var createGoogleCompatibleJSONSchema = (schema) => {
1233
- if (!GEMINI_PREFERRED_FORMAT) {
1234
- return schema;
1235
- }
1236
- const { oneOf: _oneOf, allOf: _allOf, anyOf: _anyOf, ...cleanSchema } = schema;
1237
- const removeAdditionalProperties = (obj) => {
1238
- if (Array.isArray(obj)) {
1239
- return obj.map(removeAdditionalProperties);
1240
- }
1241
- if (obj && typeof obj === "object") {
1242
- const result = {};
1243
- for (const [key, value] of Object.entries(obj)) {
1244
- if (key !== "additionalProperties") {
1245
- result[key] = removeAdditionalProperties(value);
1246
- }
1247
- }
1248
- return result;
1249
- }
1250
- return obj;
1251
- };
1252
- return removeAdditionalProperties(cleanSchema);
1253
- };
1254
-
1255
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/prompts/index.js
1256
- var SystemPrompts = {
1257
- /**
1258
- * Base system prompt for autonomous MCP execution
1259
- */
1260
- AUTONOMOUS_EXECUTION: `Autonomous AI Agent \`{toolName}\` that answers user questions through iterative self-invocation and collecting feedback.
1261
-
1262
- <instructions>{description}</instructions>
1263
-
1264
- ## Execution Rules
1265
- 1. **Follow instructions above** carefully
1266
- 2. **Answer user question** as primary goal
1267
- 3. **Execute** one action per call
1268
- 4. **Collect feedback** from each action result
1269
- 5. **Decide** next step:
1270
- - **proceed**: More work needed
1271
- - **complete**: Question answered
1272
- - **retry**: Current action failed
1273
- 6. **Provide** parameter object matching action name
1274
- 7. **Continue** until complete
1275
-
1276
- ## Call Format
1277
- \`\`\`json
1278
- {
1279
- "action": "tool_name",
1280
- "decision": "proceed|retry|complete",
1281
- "tool_name": { /* tool parameters */ }
1282
- }
1283
- \`\`\``,
1284
- /**
1285
- * Workflow execution system prompt
1286
- */
1287
- WORKFLOW_EXECUTION: `Agentic workflow execution tool \`{toolName}\` that processes requests through structured multi-step workflows.
1288
-
1289
- <instructions>{description}</instructions>
1290
-
1291
- ## Workflow Execution Protocol
1292
-
1293
- **\u{1F3AF} FIRST CALL (Planning):**
1294
- {planningInstructions}
1295
-
1296
- **\u26A1 SUBSEQUENT CALLS (Execution):**
1297
- - Provide ONLY current step parameters
1298
- - **ADVANCE STEP**: Set \`decision: "proceed"\` to move to next step
1299
- - **RETRY STEP**: Set \`decision: "retry"\`
1300
- - **COMPLETE WORKFLOW**: Set \`decision: "complete"\` when ready to finish
1301
-
1302
- **\u{1F6AB} Do NOT include \`steps\` parameter during normal execution**
1303
- **\u2705 Include \`steps\` parameter ONLY when restarting workflow with \`init: true\`**
1304
- **\u26A0\uFE0F CRITICAL: When retrying failed steps, MUST use \`decision: "retry"\`**`,
1305
- /**
1306
- * JSON-only execution system prompt
1307
- */
1308
- SAMPLING_EXECUTION: `Autonomous AI Agent \`{toolName}\` that answers user questions by iteratively collecting feedback and adapting your approach.
1309
-
1310
- <instructions>{description}</instructions>
1311
-
1312
- ## Execution Rules
1313
- - Respond with valid JSON only
1314
- - **Follow instructions above** carefully
1315
- - **Answer user question** as primary goal
1316
- - **Collect feedback** from each action result
1317
- - **Adapt approach** based on gathered information
1318
- - action = "X" \u2192 provide parameter "X"
1319
- - Continue until question answered
1320
-
1321
- ## JSON Response Format
1322
- \`\`\`json
1323
- {
1324
- "action": "tool_name",
1325
- "decision": "proceed|retry|complete",
1326
- "tool_name": { /* tool parameters */ }
1327
- }
1328
- \`\`\`
1329
-
1330
- ## Available Tools
1331
- {toolList}`,
1332
- /**
1333
- * Sampling workflow execution system prompt combining sampling with workflow capabilities
1334
- */
1335
- SAMPLING_WORKFLOW_EXECUTION: `You are an autonomous AI Agent named \`{toolName}\` that processes instructions through iterative sampling execution within structured workflows.
1336
-
1337
- <instructions>{description}</instructions>
1338
-
1339
- ## Agentic Sampling Workflow Protocol
1340
-
1341
- **\u{1F9E0} AGENTIC REASONING (First Call - Workflow Planning):**
1342
- 1. **Autonomous Analysis:** Independently analyze the user's instruction and identify the end goal
1343
- 2. **Workflow Design:** Autonomously design a structured workflow with clear steps
1344
- 3. **Tool Mapping:** Determine which tools are needed for each workflow step
1345
- 4. **Initialization:** Start the workflow with proper step definitions
1346
-
1347
- **\u26A1 AGENTIC EXECUTION RULES (Subsequent Calls):**
1348
- - Each response demonstrates autonomous reasoning and decision-making within workflow context
1349
- - Make self-directed choices about step execution, retry, or advancement
1350
- - Adapt your approach based on previous step results without external guidance
1351
- - Balance workflow structure with autonomous flexibility
1352
-
1353
- **\u{1F504} JSON Response Format (Agentic Workflow Decision Output):**
1354
- You MUST respond with a JSON object for workflow execution:
1355
-
1356
- **For Workflow Initialization (First Call):**
1357
- - action: "{toolName}"
1358
- - init: true
1359
- - steps: Autonomously designed workflow steps array
1360
- - [other workflow parameters]: As you autonomously determine
1361
-
1362
- **For Step Execution (Subsequent Calls):**
1363
- - action: "{toolName}"
1364
- - decision: "proceed" (advance), "retry" (retry), or "complete" (finish - sampling mode only)
1365
- - [step parameters]: Tool-specific parameters you autonomously determine for current step
1366
-
1367
- **\u{1F3AF} AGENTIC WORKFLOW CONSTRAINTS:**
1368
- - Response must be pure JSON demonstrating autonomous decision-making within workflow structure
1369
- - Invalid JSON indicates failure in agentic workflow reasoning
1370
- - Tool parameters must reflect your independent analysis and workflow planning
1371
- - Balance autonomous decision-making with structured workflow progression
1372
-
1373
- **\u{1F6AB} Do NOT include \`steps\` parameter during normal execution**
1374
- **\u2705 Include \`steps\` parameter ONLY when restarting workflow with \`init: true\`**
1375
- **\u26A0\uFE0F CRITICAL: When retrying failed steps, MUST use \`decision: "retry"\`**`
1376
- };
1377
- var WorkflowPrompts = {
1378
- /**
1379
- * Workflow initialization instructions
1380
- */
1381
- WORKFLOW_INIT: `Workflow initialized with {stepCount} steps. Agent MUST start the workflow with the first step to \`{currentStepDescription}\`.
1382
-
1383
- ## EXECUTE tool \`{toolName}\` with the following new parameter definition
1384
-
1385
- {schemaDefinition}
1386
-
1387
- ## Important Instructions
1388
- - **Include 'steps' parameter ONLY when restarting workflow (with 'init: true')**
1389
- - **Do NOT include 'steps' parameter during normal step execution**
1390
- - **MUST Use the provided JSON schema definition above for parameter generation and validation**
1391
- - **ADVANCE STEP: Set 'decision' to "proceed" to advance to next step**
1392
- - **RETRY STEP: Set 'decision' to "retry" to re-execute current step**
1393
- - **FINAL STEP: Execute normally for workflow completion, do NOT use 'decision: complete' unless workflow is truly finished**
1394
- - **\u26A0\uFE0F CRITICAL: When retrying failed steps, MUST set 'decision' to "retry"**
1395
- - **\u26A0\uFE0F CRITICAL: Only use 'decision: complete' when the entire workflow has been successfully executed**
1396
-
1397
- {workflowSteps}`,
1398
- /**
1399
- * Tool description enhancement for workflow mode
1400
- */
1401
- WORKFLOW_TOOL_DESCRIPTION: `{description}
1402
- {initTitle}
1403
- {ensureStepActions}
1404
- {schemaDefinition}`,
1405
- /**
1406
- * Planning instructions for predefined workflows
1407
- */
1408
- PREDEFINED_WORKFLOW_PLANNING: `- Set \`init: true\` (steps are predefined)`,
1409
- /**
1410
- * Planning instructions for dynamic workflows
1411
- */
1412
- DYNAMIC_WORKFLOW_PLANNING: `- Set \`init: true\` and define complete \`steps\` array`,
1413
- /**
1414
- * Next step decision prompt
1415
- */
1416
- NEXT_STEP_DECISION: `**Next Step Decision Required**
1417
-
1418
- Previous step completed. Choose your action:
1419
-
1420
- **\u{1F504} RETRY Current Step:**
1421
- - Call \`{toolName}\` with current parameters
1422
- - \u26A0\uFE0F CRITICAL: Set \`decision: "retry"\`
1423
-
1424
- **\u25B6\uFE0F PROCEED to Next Step:**
1425
- - Call \`{toolName}\` with parameters below
1426
- - Set \`decision: "proceed"\`
1427
-
1428
- Next step: \`{nextStepDescription}\`
1429
-
1430
- {nextStepSchema}
1431
-
1432
- **Important:** Exclude \`steps\` key from parameters`,
1433
- /**
1434
- * Final step completion prompt
1435
- */
1436
- FINAL_STEP_COMPLETION: `**Final Step Complete** {statusIcon}
1437
-
1438
- Step executed {statusText}. Choose action:
1439
-
1440
- **\u{1F504} RETRY:** Call \`{toolName}\` with \`decision: "retry"\`
1441
- **\u2705 COMPLETE:** Call \`{toolName}\` with \`decision: "complete"\`
1442
- **\u{1F195} NEW:** Call \`{toolName}\` with \`init: true\`{newWorkflowInstructions}`,
1443
- /**
1444
- * Workflow completion success message
1445
- */
1446
- WORKFLOW_COMPLETED: `**Workflow Completed Successfully** \u2705
1447
-
1448
- All workflow steps have been executed and the workflow is now complete.
1449
-
1450
- **Summary:**
1451
- - Total steps: {totalSteps}
1452
- - All steps executed successfully
1453
-
1454
- Agent can now start a new workflow if needed by calling \`{toolName}\` with \`init: true\`{newWorkflowInstructions}.`,
1455
- /**
1456
- * Error messages
1457
- */
1458
- ERRORS: {
1459
- NOT_INITIALIZED: {
1460
- WITH_PREDEFINED: "Error: Workflow not initialized. Please provide 'init' parameter to start a new workflow.",
1461
- WITHOUT_PREDEFINED: "Error: Workflow not initialized. Please provide 'init' and 'steps' parameter to start a new workflow."
1462
- },
1463
- ALREADY_AT_FINAL: "Error: Cannot proceed, already at the final step.",
1464
- 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.",
1465
- NO_STEPS_PROVIDED: "Error: No steps provided",
1466
- NO_CURRENT_STEP: "Error: No current step to execute"
1467
- }
1468
- };
1469
- var ResponseTemplates = {
1470
- /**
1471
- * Success response for action execution
1472
- */
1473
- ACTION_SUCCESS: `**Action Completed Successfully** \u2705
1474
-
1475
- Previous action (\`{currentAction}\`) executed successfully.
1476
-
1477
- **Next Action Required:** \`{nextAction}\`
1478
-
1479
- Agent MUST call tool \`{toolName}\` again with the \`{nextAction}\` action to continue the autonomous execution sequence.
1480
-
1481
- **Instructions:**
1482
- - Analyze the result from previous action: \`{currentAction}\`
1483
- - Execute the next planned action: \`{nextAction}\`
1484
- - Maintain execution context and progress toward the final goal`,
1485
- /**
1486
- * Planning prompt when no next action is specified
1487
- */
1488
- PLANNING_PROMPT: `**Action Evaluation & Planning Required** \u{1F3AF}
1489
-
1490
- Previous action (\`{currentAction}\`) completed. You need to determine the next step.
1491
-
1492
- **Evaluation & Planning Process:**
1493
- 1. **Analyze Results:** Review the outcome of \`{currentAction}\`
1494
- 2. **Assess Progress:** Determine how close you are to fulfilling the user request
1495
- 3. **Plan Next Action:** Identify the most appropriate next action (if needed)
1496
- 4. **Execute Decision:** Call \`{toolName}\` with the planned action
1497
-
1498
- **Options:**
1499
- - **Continue:** If more actions are needed to fulfill the request
1500
- - **Complete:** If the user request has been fully satisfied
1501
-
1502
- Choose the next action that best advances toward completing the user's request.`,
1503
- /**
1504
- * Error response template
1505
- */
1506
- ERROR_RESPONSE: `Action argument validation failed: {errorMessage}`,
1507
- WORKFLOW_ERROR_RESPONSE: `Action argument validation failed: {errorMessage}
1508
- Set \`decision: "retry"\` to retry the current step, or check your parameters and try again.`,
1509
- /**
1510
- * Completion message
1511
- */
1512
- COMPLETION_MESSAGE: `Completed, no dependent actions to execute`,
1513
- /**
1514
- * Security validation messages
1515
- */
1516
- SECURITY_VALIDATION: {
1517
- PASSED: `Security validation PASSED for {operation} on {path}`,
1518
- FAILED: `Security validation FAILED for {operation} on {path}`
1519
- },
1520
- /**
1521
- * Audit log messages
1522
- */
1523
- AUDIT_LOG: `Audit log entry created: [{timestamp}] {level}: {action} on {resource}{userInfo}`
1524
- };
1525
- var CompiledPrompts = {
1526
- autonomousExecution: p(SystemPrompts.AUTONOMOUS_EXECUTION),
1527
- workflowExecution: p(SystemPrompts.WORKFLOW_EXECUTION),
1528
- samplingExecution: p(SystemPrompts.SAMPLING_EXECUTION),
1529
- samplingWorkflowExecution: p(SystemPrompts.SAMPLING_WORKFLOW_EXECUTION),
1530
- workflowInit: p(WorkflowPrompts.WORKFLOW_INIT),
1531
- workflowToolDescription: p(WorkflowPrompts.WORKFLOW_TOOL_DESCRIPTION),
1532
- nextStepDecision: p(WorkflowPrompts.NEXT_STEP_DECISION),
1533
- finalStepCompletion: p(WorkflowPrompts.FINAL_STEP_COMPLETION),
1534
- workflowCompleted: p(WorkflowPrompts.WORKFLOW_COMPLETED),
1535
- actionSuccess: p(ResponseTemplates.ACTION_SUCCESS),
1536
- planningPrompt: p(ResponseTemplates.PLANNING_PROMPT),
1537
- errorResponse: p(ResponseTemplates.ERROR_RESPONSE),
1538
- workflowErrorResponse: p(ResponseTemplates.WORKFLOW_ERROR_RESPONSE),
1539
- securityPassed: p(ResponseTemplates.SECURITY_VALIDATION.PASSED),
1540
- securityFailed: p(ResponseTemplates.SECURITY_VALIDATION.FAILED),
1541
- auditLog: p(ResponseTemplates.AUDIT_LOG),
1542
- completionMessage: () => ResponseTemplates.COMPLETION_MESSAGE
1543
- };
1544
- var PromptUtils = {
1545
- /**
1546
- * Generate tool list for descriptions
1547
- */
1548
- generateToolList: (tools) => {
1549
- return tools.filter((tool) => !tool.hide).map((tool) => `<tool name="${tool.name}"${tool.description ? ` description="${tool.description}"` : ""}/>`).join("\n");
1550
- },
1551
- /**
1552
- * Generate hidden tool list for descriptions
1553
- */
1554
- generateHiddenToolList: (tools) => {
1555
- return tools.filter((tool) => tool.hide).map((tool) => `<tool name="${tool.name}" hide/>`).join("\n");
1556
- },
1557
- /**
1558
- * Format workflow steps for display
1559
- */
1560
- formatWorkflowSteps: (steps) => {
1561
- if (!steps.length) return "";
1562
- return `## Workflow Steps
1563
- ${JSON.stringify(steps, null, 2)}`;
1564
- },
1565
- /**
1566
- * Format workflow progress display with status icons
1567
- */
1568
- formatWorkflowProgress: (progressData) => {
1569
- const statusIcons = {
1570
- pending: "\u23F3",
1571
- running: "\u{1F504}",
1572
- completed: "\u2705",
1573
- failed: "\u274C"
1574
- };
1575
- return progressData.steps.map((step, index) => {
1576
- const status = progressData.statuses[index] || "pending";
1577
- const icon = statusIcons[status] || "\u23F3";
1578
- const current = index === progressData.currentStepIndex ? " **[CURRENT]**" : "";
1579
- const actions = step.actions.length > 0 ? ` | Action: ${step.actions.join(", ")}` : "";
1580
- return `${icon} **Step ${index + 1}:** ${step.description}${actions}${current}`;
1581
- }).join("\n");
1582
- },
1583
- /**
1584
- * Generate user info for audit logs
1585
- */
1586
- formatUserInfo: (user) => {
1587
- return user ? ` by ${user}` : "";
1588
- },
1589
- /**
1590
- * Format timestamp for logs
1591
- */
1592
- formatTimestamp: () => {
1593
- return (/* @__PURE__ */ new Date()).toISOString();
1594
- }
1595
- };
1596
-
1597
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/agentic/agentic-executor.js
1598
- import { Ajv } from "ajv";
1599
- import { AggregateAjvError } from "@segment/ajv-human-errors";
1600
- import addFormats from "ajv-formats";
1601
- init_logger();
1602
-
1603
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/tracing.js
1604
- import { context, SpanStatusCode, trace } from "@opentelemetry/api";
1605
- import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
1606
- import { BatchSpanProcessor, ConsoleSpanExporter, SimpleSpanProcessor } from "@opentelemetry/sdk-trace-base";
1607
- import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
1608
- import { Resource } from "@opentelemetry/resources";
1609
- import { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION } from "@opentelemetry/semantic-conventions";
1610
- var tracerProvider = null;
1611
- var tracer = null;
1612
- var isInitialized = false;
1613
- function initializeTracing(config2 = {}) {
1614
- if (isInitialized) {
1615
- return;
1616
- }
1617
- const { enabled = true, serviceName = "mcpc-sampling", serviceVersion = "0.2.0", exportTo = "console", otlpEndpoint = "http://localhost:4318/v1/traces", otlpHeaders = {} } = config2;
1618
- if (!enabled) {
1619
- isInitialized = true;
1620
- return;
1621
- }
1622
- const resource = Resource.default().merge(new Resource({
1623
- [ATTR_SERVICE_NAME]: serviceName,
1624
- [ATTR_SERVICE_VERSION]: serviceVersion
1625
- }));
1626
- tracerProvider = new NodeTracerProvider({
1627
- resource
1628
- });
1629
- if (exportTo === "console") {
1630
- tracerProvider.addSpanProcessor(new SimpleSpanProcessor(new ConsoleSpanExporter()));
1631
- } else if (exportTo === "otlp") {
1632
- const otlpExporter = new OTLPTraceExporter({
1633
- url: otlpEndpoint,
1634
- headers: otlpHeaders
1635
- });
1636
- tracerProvider.addSpanProcessor(new BatchSpanProcessor(otlpExporter));
1637
- }
1638
- tracerProvider.register();
1639
- tracer = trace.getTracer(serviceName, serviceVersion);
1640
- isInitialized = true;
1641
- }
1642
- function getTracer() {
1643
- if (!isInitialized) {
1644
- initializeTracing();
1645
- }
1646
- return tracer;
1647
- }
1648
- function startSpan(name, attributes, parent) {
1649
- const tracer2 = getTracer();
1650
- const ctx = parent ? trace.setSpan(context.active(), parent) : void 0;
1651
- return tracer2.startSpan(name, {
1652
- attributes
1653
- }, ctx);
1654
- }
1655
- function endSpan(span, error) {
1656
- if (error) {
1657
- span.setStatus({
1658
- code: SpanStatusCode.ERROR,
1659
- message: error.message
1660
- });
1661
- span.recordException(error);
1662
- } else {
1663
- span.setStatus({
1664
- code: SpanStatusCode.OK
1665
- });
1666
- }
1667
- span.end();
1668
- }
1669
-
1670
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/agentic/agentic-executor.js
1671
- import process4 from "node:process";
1672
- var ajv = new Ajv({
1673
- allErrors: true,
1674
- verbose: true
1675
- });
1676
- addFormats(ajv);
1677
- var AgenticExecutor = class {
1678
- name;
1679
- allToolNames;
1680
- toolNameToDetailList;
1681
- server;
1682
- ACTION_KEY;
1683
- NEXT_ACTION_KEY;
1684
- logger;
1685
- tracingEnabled;
1686
- constructor(name, allToolNames, toolNameToDetailList, server, ACTION_KEY = "action", NEXT_ACTION_KEY = "nextAction") {
1687
- this.name = name;
1688
- this.allToolNames = allToolNames;
1689
- this.toolNameToDetailList = toolNameToDetailList;
1690
- this.server = server;
1691
- this.ACTION_KEY = ACTION_KEY;
1692
- this.NEXT_ACTION_KEY = NEXT_ACTION_KEY;
1693
- this.tracingEnabled = false;
1694
- this.logger = createLogger(`mcpc.agentic.${name}`, server);
1695
- try {
1696
- this.tracingEnabled = process4.env.MCPC_TRACING_ENABLED === "true";
1697
- if (this.tracingEnabled) {
1698
- initializeTracing({
1699
- enabled: true,
1700
- serviceName: `mcpc-agentic-${name}`,
1701
- exportTo: process4.env.MCPC_TRACING_EXPORT ?? "otlp",
1702
- otlpEndpoint: process4.env.MCPC_TRACING_OTLP_ENDPOINT ?? "http://localhost:4318/v1/traces"
1703
- });
1704
- }
1705
- } catch {
1706
- this.tracingEnabled = false;
1707
- }
1708
- }
1709
- async execute(args, schema) {
1710
- const executeSpan = this.tracingEnabled ? startSpan("mcpc.agentic_execute", {
1711
- agent: this.name,
1712
- action: String(args[this.ACTION_KEY] ?? "unknown"),
1713
- nextAction: String(args[this.NEXT_ACTION_KEY] ?? "none"),
1714
- args: JSON.stringify(args)
1715
- }) : null;
1716
- try {
1717
- const validationResult = this.validate(args, schema);
1718
- if (!validationResult.valid) {
1719
- if (executeSpan) {
1720
- executeSpan.setAttributes({
1721
- validationError: true,
1722
- errorMessage: validationResult.error || "Validation failed"
1723
- });
1724
- endSpan(executeSpan);
1725
- }
1726
- this.logger.warning({
1727
- message: "Validation failed",
1728
- action: args[this.ACTION_KEY],
1729
- error: validationResult.error
1730
- });
1731
- return {
1732
- content: [
1733
- {
1734
- type: "text",
1735
- text: CompiledPrompts.errorResponse({
1736
- errorMessage: validationResult.error || "Validation failed"
1737
- })
1738
- }
1739
- ],
1740
- isError: true
1741
- };
1742
- }
1743
- const actionName = args[this.ACTION_KEY];
1744
- if (executeSpan && actionName) {
1745
- try {
1746
- const safeAction = String(actionName).replace(/\s+/g, "_");
1747
- if (typeof executeSpan.updateName === "function") {
1748
- executeSpan.updateName(`mcpc.agentic_execute.${safeAction}`);
1749
- }
1750
- } catch {
1751
- }
1752
- }
1753
- const currentTool = this.toolNameToDetailList.find(([name, _detail]) => name === actionName)?.[1];
1754
- if (currentTool) {
1755
- const nextAction = args[this.NEXT_ACTION_KEY];
1756
- if (executeSpan) {
1757
- executeSpan.setAttributes({
1758
- toolType: "external",
1759
- actionName,
1760
- nextAction: nextAction || "none"
1761
- });
1762
- }
1763
- this.logger.debug({
1764
- message: "Executing external tool",
1765
- action: actionName,
1766
- nextAction
1767
- });
1768
- const currentResult = await currentTool.execute({
1769
- ...args[actionName]
1770
- });
1771
- if (args[nextAction]) {
1772
- currentResult?.content?.push({
1773
- type: "text",
1774
- text: CompiledPrompts.actionSuccess({
1775
- toolName: this.name,
1776
- nextAction,
1777
- currentAction: actionName
1778
- })
1779
- });
1780
- } else {
1781
- currentResult?.content?.push({
1782
- type: "text",
1783
- text: CompiledPrompts.planningPrompt({
1784
- currentAction: actionName
1785
- })
1786
- });
1787
- }
1788
- if (executeSpan) {
1789
- executeSpan.setAttributes({
1790
- success: true,
1791
- isError: !!currentResult.isError,
1792
- resultContentLength: currentResult.content?.length || 0,
1793
- hasNextAction: !!args[nextAction],
1794
- toolResult: JSON.stringify(currentResult)
1795
- });
1796
- endSpan(executeSpan);
1797
- }
1798
- return currentResult;
1799
- }
1800
- if (this.allToolNames.includes(actionName)) {
1801
- if (executeSpan) {
1802
- executeSpan.setAttributes({
1803
- toolType: "internal",
1804
- actionName
1805
- });
1806
- }
1807
- this.logger.debug({
1808
- message: "Executing internal tool",
1809
- action: actionName
1810
- });
1811
- try {
1812
- const result = await this.server.callTool(actionName, args[actionName]);
1813
- const nextAction = args[this.NEXT_ACTION_KEY];
1814
- const callToolResult = result ?? {
1815
- content: []
1816
- };
1817
- if (nextAction && this.allToolNames.includes(nextAction)) {
1818
- callToolResult.content.push({
1819
- type: "text",
1820
- text: CompiledPrompts.actionSuccess({
1821
- toolName: this.name,
1822
- nextAction,
1823
- currentAction: actionName
1824
- })
1825
- });
1826
- } else {
1827
- callToolResult.content.push({
1828
- type: "text",
1829
- text: CompiledPrompts.planningPrompt({
1830
- currentAction: actionName
1831
- })
1832
- });
1833
- }
1834
- if (executeSpan) {
1835
- executeSpan.setAttributes({
1836
- success: true,
1837
- isError: !!callToolResult.isError,
1838
- resultContentLength: callToolResult.content?.length || 0,
1839
- hasNextAction: !!(nextAction && this.allToolNames.includes(nextAction)),
1840
- toolResult: JSON.stringify(callToolResult)
1841
- });
1842
- endSpan(executeSpan);
1843
- }
1844
- return callToolResult;
1845
- } catch (error) {
1846
- if (executeSpan) {
1847
- endSpan(executeSpan, error);
1848
- }
1849
- this.logger.error({
1850
- message: "Error executing internal tool",
1851
- action: actionName,
1852
- error: String(error)
1853
- });
1854
- return {
1855
- content: [
1856
- {
1857
- type: "text",
1858
- text: `Error executing internal tool ${actionName}: ${error instanceof Error ? error.message : String(error)}`
1859
- }
1860
- ],
1861
- isError: true
1862
- };
1863
- }
1864
- }
1865
- if (executeSpan) {
1866
- executeSpan.setAttributes({
1867
- toolType: "not_found",
1868
- actionName: actionName || "unknown",
1869
- completion: true
1870
- });
1871
- endSpan(executeSpan);
1872
- }
1873
- this.logger.debug({
1874
- message: "Tool not found, returning completion message",
1875
- action: actionName
1876
- });
1877
- return {
1878
- content: [
1879
- {
1880
- type: "text",
1881
- text: CompiledPrompts.completionMessage()
1882
- }
1883
- ]
1884
- };
1885
- } catch (error) {
1886
- if (executeSpan) {
1887
- endSpan(executeSpan, error);
1888
- }
1889
- this.logger.error({
1890
- message: "Unexpected error in execute",
1891
- error: String(error)
1892
- });
1893
- return {
1894
- content: [
1895
- {
1896
- type: "text",
1897
- text: `Unexpected error: ${error instanceof Error ? error.message : String(error)}`
1898
- }
1899
- ],
1900
- isError: true
1901
- };
1902
- }
1903
- }
1904
- // Validate arguments using JSON schema
1905
- validate(args, schema) {
1906
- if (args.decision === "complete") {
1907
- return {
1908
- valid: true
1909
- };
1910
- }
1911
- const validate = ajv.compile(schema);
1912
- if (!validate(args)) {
1913
- const errors = new AggregateAjvError(validate.errors);
1914
- return {
1915
- valid: false,
1916
- error: errors.message
1917
- };
1918
- }
1919
- return {
1920
- valid: true
1921
- };
1922
- }
1923
- };
1924
-
1925
- // ../__mcpc__cli_latest/node_modules/@jsr/es-toolkit__es-toolkit/src/function/partial.js
1926
- function partial(func, ...partialArgs) {
1927
- return partialImpl(func, placeholderSymbol, ...partialArgs);
1928
- }
1929
- function partialImpl(func, placeholder, ...partialArgs) {
1930
- const partialed = function(...providedArgs) {
1931
- let providedArgsIndex = 0;
1932
- const substitutedArgs = partialArgs.slice().map((arg) => arg === placeholder ? providedArgs[providedArgsIndex++] : arg);
1933
- const remainingArgs = providedArgs.slice(providedArgsIndex);
1934
- return func.apply(this, substitutedArgs.concat(remainingArgs));
1935
- };
1936
- if (func.prototype) {
1937
- partialed.prototype = Object.create(func.prototype);
1938
- }
1939
- return partialed;
1940
- }
1941
- var placeholderSymbol = Symbol("partial.placeholder");
1942
- partial.placeholder = placeholderSymbol;
1943
-
1944
- // ../__mcpc__cli_latest/node_modules/@jsr/es-toolkit__es-toolkit/src/function/partialRight.js
1945
- function partialRight(func, ...partialArgs) {
1946
- return partialRightImpl(func, placeholderSymbol2, ...partialArgs);
1947
- }
1948
- function partialRightImpl(func, placeholder, ...partialArgs) {
1949
- const partialedRight = function(...providedArgs) {
1950
- const placeholderLength = partialArgs.filter((arg) => arg === placeholder).length;
1951
- const rangeLength = Math.max(providedArgs.length - placeholderLength, 0);
1952
- const remainingArgs = providedArgs.slice(0, rangeLength);
1953
- let providedArgsIndex = rangeLength;
1954
- const substitutedArgs = partialArgs.slice().map((arg) => arg === placeholder ? providedArgs[providedArgsIndex++] : arg);
1955
- return func.apply(this, remainingArgs.concat(substitutedArgs));
1956
- };
1957
- if (func.prototype) {
1958
- partialedRight.prototype = Object.create(func.prototype);
1959
- }
1960
- return partialedRight;
1961
- }
1962
- var placeholderSymbol2 = Symbol("partialRight.placeholder");
1963
- partialRight.placeholder = placeholderSymbol2;
1964
-
1965
- // ../__mcpc__cli_latest/node_modules/@jsr/es-toolkit__es-toolkit/src/function/retry.js
1966
- var DEFAULT_RETRIES = Number.POSITIVE_INFINITY;
1967
-
1968
- // ../__mcpc__cli_latest/node_modules/@jsr/es-toolkit__es-toolkit/src/object/pick.js
1969
- function pick(obj, keys) {
1970
- const result = {};
1971
- for (let i = 0; i < keys.length; i++) {
1972
- const key = keys[i];
1973
- if (Object.hasOwn(obj, key)) {
1974
- result[key] = obj[key];
1975
- }
1976
- }
1977
- return result;
1978
- }
1979
-
1980
- // ../__mcpc__cli_latest/node_modules/@jsr/es-toolkit__es-toolkit/src/string/deburr.js
1981
- var deburrMap = new Map(
1982
- // eslint-disable-next-line no-restricted-syntax
1983
- Object.entries({
1984
- \u00C6: "Ae",
1985
- \u00D0: "D",
1986
- \u00D8: "O",
1987
- \u00DE: "Th",
1988
- \u00DF: "ss",
1989
- \u00E6: "ae",
1990
- \u00F0: "d",
1991
- \u00F8: "o",
1992
- \u00FE: "th",
1993
- \u0110: "D",
1994
- \u0111: "d",
1995
- \u0126: "H",
1996
- \u0127: "h",
1997
- \u0131: "i",
1998
- \u0132: "IJ",
1999
- \u0133: "ij",
2000
- \u0138: "k",
2001
- \u013F: "L",
2002
- \u0140: "l",
2003
- \u0141: "L",
2004
- \u0142: "l",
2005
- \u0149: "'n",
2006
- \u014A: "N",
2007
- \u014B: "n",
2008
- \u0152: "Oe",
2009
- \u0153: "oe",
2010
- \u0166: "T",
2011
- \u0167: "t",
2012
- \u017F: "s"
2013
- })
2014
- );
2015
-
2016
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/factories/args-def-factory.js
2017
- var DECISION_OPTIONS = {
2018
- RETRY: "retry",
2019
- PROCEED: "proceed",
2020
- COMPLETE: "complete"
2021
- };
2022
- function createArgsDefFactory(name, allToolNames, depGroups, predefinedSteps, ensureStepActions) {
2023
- const formatEnsureStepActions = () => {
2024
- if (!ensureStepActions || ensureStepActions.length === 0) {
2025
- return "";
2026
- }
2027
- return `
2028
-
2029
- ## Required Actions
2030
- The workflow MUST include at least one of these actions:
2031
- ${ensureStepActions.map((action) => `- \`${action}\``).join("\n")}`;
2032
- };
2033
- return {
2034
- common: (extra, optionalFields = []) => {
2035
- const requiredFields = Object.keys(extra).filter((key) => !optionalFields.includes(key));
2036
- return {
2037
- type: "object",
2038
- description: `**Tool parameters dynamically update per workflow step**`,
2039
- properties: {
2040
- ...extra
2041
- },
2042
- required: requiredFields
2043
- };
2044
- },
2045
- steps: () => ({
2046
- type: "array",
2047
- description: `
2048
- Workflow step definitions - provide ONLY on initial call.
2049
-
2050
- **CRITICAL RULES:**
2051
- - **Sequential Dependency:** If Action B depends on Action A's result \u2192 separate steps
2052
- - **Concurrent Actions:** Independent actions can share one step
2053
- - **Complete Mapping:** Include ALL requested operations
2054
- - **Predefined Steps:** Leave unspecified if predefined steps exist
2055
-
2056
- **BEST PRACTICES:**
2057
- - Atomic, focused steps
2058
- - Idempotent actions for safe retries
2059
- - Clear step descriptions with input/output context`,
2060
- items: {
2061
- type: "object",
2062
- description: `A single step containing actions that execute concurrently. All actions in this step run simultaneously with no guaranteed order.`,
2063
- properties: {
2064
- description: {
2065
- type: "string",
2066
- description: `**Step purpose, required inputs, and expected outputs**`
2067
- },
2068
- actions: {
2069
- type: "array",
2070
- 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.`,
2071
- items: {
2072
- ...{
2073
- enum: allToolNames
2074
- },
2075
- type: "string",
2076
- description: `Individual action name from available tools. Must be exactly one of the allowed tool names.`
2077
- },
2078
- uniqueItems: true,
2079
- minItems: 0,
2080
- // TODO: remove this restriction when workflow planning is good enough
2081
- maxItems: 1
2082
- }
2083
- },
2084
- required: [
2085
- "description",
2086
- "actions"
2087
- ],
2088
- additionalProperties: false
2089
- },
2090
- default: predefinedSteps ? predefinedSteps : void 0,
2091
- minItems: 1
2092
- }),
2093
- init: () => ({
2094
- type: "boolean",
2095
- description: `Init a new workflow`,
2096
- enum: [
2097
- true
2098
- ]
2099
- }),
2100
- decision: () => ({
2101
- type: "string",
2102
- enum: Object.values(DECISION_OPTIONS),
2103
- description: `**Step control: \`${DECISION_OPTIONS.PROCEED}\` = next step, \`${DECISION_OPTIONS.RETRY}\` = retry/repeat current, \`${DECISION_OPTIONS.COMPLETE}\` = finish workflow**`
2104
- }),
2105
- action: () => ({
2106
- type: "string",
2107
- description: "Define the current workflow action to be performed",
2108
- enum: allToolNames,
2109
- required: [
2110
- "action"
2111
- ]
2112
- }),
2113
- forTool: function() {
2114
- return this.common({});
2115
- },
2116
- forCurrentState: function(state) {
2117
- const currentStep = state.getCurrentStep();
2118
- if (!state.isWorkflowInitialized() || !currentStep) {
2119
- state.reset();
2120
- const initSchema = {
2121
- init: this.init()
2122
- };
2123
- if (!predefinedSteps) {
2124
- initSchema.steps = this.steps();
2125
- }
2126
- return this.common(initSchema);
2127
- }
2128
- const stepDependencies = {
2129
- ...pick(depGroups, currentStep.actions)
2130
- };
2131
- stepDependencies["decision"] = this.decision();
2132
- stepDependencies["action"] = this.action();
2133
- return this.common(stepDependencies);
2134
- },
2135
- forSampling: function() {
2136
- return {
2137
- type: "object",
2138
- description: "Provide user request for autonomous tool execution",
2139
- properties: {
2140
- userRequest: {
2141
- type: "string",
2142
- description: "The task or request that should be completed autonomously by the agentic system using available tools"
2143
- },
2144
- context: {
2145
- type: "object",
2146
- description: "Necessary context for the request, e.g., the absolute path of the current working directory. This is just an example; any relevant context fields are allowed.",
2147
- additionalProperties: true
2148
- }
2149
- },
2150
- required: [
2151
- "userRequest",
2152
- "context"
2153
- ]
2154
- };
2155
- },
2156
- forAgentic: function(toolNameToDetailList, _sampling = false, ACTION_KEY = "action", NEXT_ACTION_KEY = "nextAction") {
2157
- const allOf = toolNameToDetailList.map(([toolName, _toolDetail]) => {
2158
- return {
2159
- if: {
2160
- properties: {
2161
- [ACTION_KEY]: {
2162
- const: toolName
2163
- }
2164
- },
2165
- required: [
2166
- ACTION_KEY
2167
- ]
2168
- },
2169
- then: {
2170
- required: [
2171
- toolName
2172
- ]
2173
- }
2174
- };
2175
- });
2176
- const actionDescription = `Specifies the action to be performed from the enum. **\u26A0\uFE0F When setting \`action: "example_action"\`, you MUST also provide \`"example_action": { ... }\`**`;
2177
- const baseProperties = {
2178
- [ACTION_KEY]: {
2179
- type: "string",
2180
- enum: allToolNames,
2181
- description: actionDescription
2182
- },
2183
- [NEXT_ACTION_KEY]: {
2184
- type: "string",
2185
- enum: allToolNames,
2186
- description: "Optional: Specify the next action to execute. Only include this when you know additional actions are needed after the current one completes."
2187
- },
2188
- decision: this.decision(),
2189
- ...depGroups
2190
- };
2191
- const requiredFields = [
2192
- ACTION_KEY,
2193
- "decision"
2194
- ];
2195
- const schema = {
2196
- additionalProperties: false,
2197
- type: "object",
2198
- properties: baseProperties,
2199
- required: requiredFields
2200
- };
2201
- if (allOf.length > 0) {
2202
- schema.allOf = allOf;
2203
- }
2204
- return schema;
2205
- },
2206
- forNextState: function(state) {
2207
- if (!state.isWorkflowInitialized() || !state.hasNextStep()) {
2208
- throw new Error(`Cannot get next state schema: no next step available`);
2209
- }
2210
- const currentStepIndex = state.getCurrentStepIndex();
2211
- const allSteps = state.getSteps();
2212
- const nextStep = allSteps[currentStepIndex + 1];
2213
- if (!nextStep) {
2214
- throw new Error(`Next step not found`);
2215
- }
2216
- const stepDependencies = {
2217
- ...pick(depGroups, nextStep.actions)
2218
- };
2219
- stepDependencies["decision"] = this.decision();
2220
- stepDependencies["action"] = this.action();
2221
- return this.common(stepDependencies);
2222
- },
2223
- forToolDescription: function(description, state) {
2224
- const enforceToolArgs = this.forCurrentState(state);
2225
- const initTitle = predefinedSteps ? `**YOU MUST execute this tool with following tool arguments to init the workflow**
2226
- NOTE: The \`steps\` has been predefined` : `**You MUST execute this tool with following tool arguments to plan and init the workflow**`;
2227
- return CompiledPrompts.workflowToolDescription({
2228
- description,
2229
- initTitle,
2230
- ensureStepActions: formatEnsureStepActions(),
2231
- schemaDefinition: JSON.stringify(enforceToolArgs, null, 2)
2232
- });
2233
- },
2234
- forInitialStepDescription: function(steps, state) {
2235
- return CompiledPrompts.workflowInit({
2236
- stepCount: steps.length.toString(),
2237
- currentStepDescription: state.getCurrentStep()?.description || "",
2238
- toolName: name,
2239
- schemaDefinition: JSON.stringify(this.forCurrentState(state), null, 2),
2240
- // Remove redundant workflow steps display
2241
- workflowSteps: ""
2242
- });
2243
- }
2244
- };
2245
- }
2246
-
2247
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/sampling/base-sampling-executor.js
2248
- import { Ajv as Ajv2 } from "ajv";
2249
- import { AggregateAjvError as AggregateAjvError2 } from "@segment/ajv-human-errors";
2250
- import addFormats2 from "ajv-formats";
2251
- init_logger();
2252
- import process5 from "node:process";
2253
- var ajv2 = new Ajv2({
2254
- allErrors: true,
2255
- verbose: true
2256
- });
2257
- addFormats2(ajv2);
2258
- var BaseSamplingExecutor = class {
2259
- name;
2260
- description;
2261
- allToolNames;
2262
- toolNameToDetailList;
2263
- server;
2264
- conversationHistory;
2265
- maxIterations;
2266
- currentIteration;
2267
- logger;
2268
- tracingEnabled;
2269
- summarize;
2270
- constructor(name, description, allToolNames, toolNameToDetailList, server, config2) {
2271
- this.name = name;
2272
- this.description = description;
2273
- this.allToolNames = allToolNames;
2274
- this.toolNameToDetailList = toolNameToDetailList;
2275
- this.server = server;
2276
- this.conversationHistory = [];
2277
- this.maxIterations = 55;
2278
- this.currentIteration = 0;
2279
- this.tracingEnabled = false;
2280
- this.summarize = true;
2281
- if (config2?.maxIterations) {
2282
- this.maxIterations = config2.maxIterations;
2283
- }
2284
- if (config2?.summarize !== void 0) {
2285
- this.summarize = config2.summarize;
2286
- }
2287
- this.logger = createLogger(`mcpc.sampling.${name}`, server);
2288
- try {
2289
- const tracingConfig = {
2290
- enabled: process5.env.MCPC_TRACING_ENABLED === "true",
2291
- serviceName: `mcpc-sampling-${name}`,
2292
- exportTo: process5.env.MCPC_TRACING_EXPORT ?? "otlp",
2293
- otlpEndpoint: process5.env.MCPC_TRACING_OTLP_ENDPOINT ?? "http://localhost:4318/v1/traces"
2294
- };
2295
- this.tracingEnabled = tracingConfig.enabled;
2296
- if (this.tracingEnabled) {
2297
- initializeTracing(tracingConfig);
2298
- }
2299
- } catch {
2300
- this.tracingEnabled = false;
2301
- }
2302
- }
2303
- async runSamplingLoop(systemPrompt, schema, state) {
2304
- this.conversationHistory = [
2305
- {
2306
- role: "user",
2307
- content: {
2308
- type: "text",
2309
- text: 'Return ONLY raw JSON (no code fences or explanations). The JSON MUST include action and decision. Example: {"action":"<tool>","decision":"proceed|complete","<tool>":{}}'
2310
- }
2311
- }
2312
- ];
2313
- const loopSpan = this.tracingEnabled ? startSpan("mcpc.sampling_loop", {
2314
- agent: this.name,
2315
- maxIterations: this.maxIterations,
2316
- systemPrompt: systemPrompt()
2317
- }) : null;
2318
- try {
2319
- for (this.currentIteration = 0; this.currentIteration < this.maxIterations; this.currentIteration++) {
2320
- let iterationSpan = null;
2321
- try {
2322
- const response = await this.server.createMessage({
2323
- systemPrompt: systemPrompt(),
2324
- messages: this.conversationHistory,
2325
- maxTokens: 55e3
2326
- });
2327
- const responseContent = response.content.text || "{}";
2328
- const model = response.model;
2329
- const stopReason = response.stopReason;
2330
- const role = response.role;
2331
- let parsedData;
2332
- try {
2333
- parsedData = parseJSON(responseContent.trim(), true);
2334
- } catch (parseError) {
2335
- iterationSpan = this.tracingEnabled ? startSpan("mcpc.sampling_iteration.parse_error", {
2336
- iteration: this.currentIteration + 1,
2337
- agent: this.name,
2338
- error: String(parseError),
2339
- maxIterations: this.maxIterations
2340
- }, loopSpan ?? void 0) : null;
2341
- this.addParsingErrorToHistory(responseContent, parseError);
2342
- if (iterationSpan) endSpan(iterationSpan);
2343
- continue;
2344
- }
2345
- if (parsedData) {
2346
- this.conversationHistory.push({
2347
- role: "assistant",
2348
- content: {
2349
- type: "text",
2350
- text: JSON.stringify(parsedData, null, 2)
2351
- }
2352
- });
2353
- }
2354
- const action = parsedData["action"];
2355
- const actionStr = action && typeof action === "string" ? String(action) : "unknown_action";
2356
- const spanName = `mcpc.sampling_iteration.${actionStr}`;
2357
- iterationSpan = this.tracingEnabled ? startSpan(spanName, {
2358
- iteration: this.currentIteration + 1,
2359
- agent: this.name,
2360
- action: actionStr,
2361
- systemPrompt: systemPrompt(),
2362
- maxTokens: String(Number.MAX_SAFE_INTEGER),
2363
- maxIterations: this.maxIterations,
2364
- messages: JSON.stringify(this.conversationHistory)
2365
- }, loopSpan ?? void 0) : null;
2366
- if (!action || typeof parsedData["decision"] !== "string") {
2367
- this.conversationHistory.push({
2368
- role: "user",
2369
- content: {
2370
- type: "text",
2371
- text: 'Required fields missing: action or decision. Return ONLY raw JSON, no code fences or explanations. Example: {"action":"<tool>","decision":"proceed|complete","<tool>":{}}'
2372
- }
2373
- });
2374
- if (iterationSpan) endSpan(iterationSpan);
2375
- continue;
2376
- }
2377
- const result = await this.processAction(parsedData, schema, state, loopSpan);
2378
- this.logIterationProgress(parsedData, result, model, stopReason, role);
2379
- if (iterationSpan) {
2380
- let rawJson = "{}";
2381
- try {
2382
- rawJson = parsedData ? JSON.stringify(parsedData) : "{}";
2383
- } catch {
2384
- }
2385
- const attr = {
2386
- isError: !!result.isError,
2387
- isComplete: !!result.isComplete,
2388
- iteration: this.currentIteration + 1,
2389
- maxIterations: this.maxIterations,
2390
- parsed: rawJson,
2391
- action: typeof action === "string" ? action : String(action),
2392
- samplingResponse: responseContent,
2393
- toolResult: JSON.stringify(result),
2394
- model,
2395
- role
2396
- };
2397
- if (stopReason) {
2398
- attr.stopReason = stopReason;
2399
- }
2400
- iterationSpan.setAttributes(attr);
2401
- }
2402
- if (result.isError) {
2403
- this.conversationHistory.push({
2404
- role: "user",
2405
- content: {
2406
- type: "text",
2407
- text: result.content[0].text
2408
- }
2409
- });
2410
- if (iterationSpan) endSpan(iterationSpan);
2411
- continue;
2412
- }
2413
- if (result.isComplete) {
2414
- if (iterationSpan) endSpan(iterationSpan);
2415
- if (loopSpan) endSpan(loopSpan);
2416
- return result;
2417
- }
2418
- if (iterationSpan) endSpan(iterationSpan);
2419
- } catch (iterError) {
2420
- if (iterationSpan) endSpan(iterationSpan, iterError);
2421
- throw iterError;
2422
- }
2423
- }
2424
- if (loopSpan) endSpan(loopSpan);
2425
- return await this.createMaxIterationsError(loopSpan);
2426
- } catch (error) {
2427
- if (loopSpan) endSpan(loopSpan, error);
2428
- return await this.createExecutionError(error, loopSpan);
2429
- }
2430
- }
2431
- addParsingErrorToHistory(responseText, parseError) {
2432
- this.conversationHistory.push({
2433
- role: "assistant",
2434
- content: {
2435
- type: "text",
2436
- text: `JSON parsing failed. Response was: ${responseText}`
2437
- }
2438
- });
2439
- this.conversationHistory.push({
2440
- role: "user",
2441
- content: {
2442
- type: "text",
2443
- text: CompiledPrompts.errorResponse({
2444
- errorMessage: `JSON parsing failed: ${parseError instanceof Error ? parseError.message : String(parseError)}
2445
-
2446
- Please respond with valid JSON.`
2447
- })
2448
- }
2449
- });
2450
- }
2451
- async createMaxIterationsError(parentSpan) {
2452
- const result = await this.createCompletionResult(`Reached max iterations (${this.maxIterations}). Try a more specific request.`, parentSpan);
2453
- result.isError = true;
2454
- result.isComplete = false;
2455
- return result;
2456
- }
2457
- async createExecutionError(error, parentSpan) {
2458
- const result = await this.createCompletionResult(`Execution error: ${error instanceof Error ? error.message : String(error)}`, parentSpan);
2459
- result.isError = true;
2460
- result.isComplete = false;
2461
- return result;
2462
- }
2463
- async createCompletionResult(text, parentSpan) {
2464
- const summary = this.summarize ? await this.summarizeConversation(parentSpan) : this.formatConversation();
2465
- return {
2466
- content: [
2467
- {
2468
- type: "text",
2469
- text: `${text}
2470
-
2471
- **Execution Summary:**
2472
- - Iterations used: ${this.currentIteration + 1}/${this.maxIterations}
2473
- - Agent: ${this.name}
2474
- ${summary}`
2475
- }
2476
- ],
2477
- isError: false,
2478
- isComplete: true
2479
- };
2480
- }
2481
- // Use LLM to create high-signal summary for parent agent
2482
- async summarizeConversation(parentSpan) {
2483
- if (this.conversationHistory.length === 0) {
2484
- return "\n\n**No conversation history**";
2485
- }
2486
- if (this.conversationHistory.length <= 3) {
2487
- return this.formatConversation();
2488
- }
2489
- const summarizeSpan = this.tracingEnabled ? startSpan("mcpc.sampling_summarize", {
2490
- agent: this.name,
2491
- messageCount: this.conversationHistory.length
2492
- }, parentSpan ?? void 0) : null;
2493
- try {
2494
- this.logger.debug({
2495
- message: "Starting conversation summarization",
2496
- messageCount: this.conversationHistory.length
2497
- });
2498
- const history = this.conversationHistory.map((msg, i) => {
2499
- const prefix = `[${i + 1}] ${msg.role.toUpperCase()}`;
2500
- return `${prefix}:
2501
- ${msg.content.text}`;
2502
- }).join("\n\n---\n\n");
2503
- const response = await this.server.createMessage({
2504
- systemPrompt: `Summarize this agent execution:
2505
-
2506
- Final Decision: (include complete JSON if present)
2507
- Key Findings: (most important)
2508
- Actions Taken: (high-level flow)
2509
- Errors/Warnings: (if any)
2510
-
2511
- ${history}`,
2512
- messages: [
2513
- {
2514
- role: "user",
2515
- content: {
2516
- type: "text",
2517
- text: "Please provide a concise summary."
2518
- }
2519
- }
2520
- ],
2521
- maxTokens: 3e3
2522
- });
2523
- const summary = "\n\n" + response.content.text;
2524
- this.logger.debug({
2525
- message: "Summarization completed",
2526
- summaryLength: summary.length
2527
- });
2528
- if (summarizeSpan) {
2529
- summarizeSpan.setAttributes({
2530
- summaryLength: summary.length,
2531
- summary,
2532
- success: true
2533
- });
2534
- endSpan(summarizeSpan);
2535
- }
2536
- return summary;
2537
- } catch (error) {
2538
- this.logger.warning({
2539
- message: "Summarization failed, falling back to full history",
2540
- error: String(error)
2541
- });
2542
- if (summarizeSpan) {
2543
- endSpan(summarizeSpan, error);
2544
- }
2545
- return this.formatConversation();
2546
- }
2547
- }
2548
- // Format full conversation history (for debugging)
2549
- formatConversation() {
2550
- if (this.conversationHistory.length === 0) {
2551
- return "\n\n**No conversation history**";
2552
- }
2553
- const messages = this.conversationHistory.map((msg, i) => {
2554
- const header = `### Message ${i + 1}: ${msg.role}`;
2555
- try {
2556
- const parsed = JSON.parse(msg.content.text);
2557
- if (JSON.stringify(parsed).length < 100) {
2558
- return `${header}
2559
- ${JSON.stringify(parsed)}`;
2560
- }
2561
- return `${header}
2562
- \`\`\`json
2563
- ${JSON.stringify(parsed, null, 2)}
2564
- \`\`\``;
2565
- } catch {
2566
- return `${header}
2567
- ${msg.content.text}`;
2568
- }
2569
- });
2570
- return "\n\n**Conversation History:**\n" + messages.join("\n\n");
2571
- }
2572
- logIterationProgress(parsedData, result, model, stopReason, role) {
2573
- this.logger.debug({
2574
- iteration: `${this.currentIteration + 1}/${this.maxIterations}`,
2575
- parsedData,
2576
- isError: result.isError,
2577
- isComplete: result.isComplete,
2578
- model,
2579
- stopReason,
2580
- role,
2581
- result
2582
- });
2583
- }
2584
- injectJsonInstruction({ prompt, schema, schemaPrefix = "JSON schema:", schemaSuffix = `STRICT REQUIREMENTS:
2585
- 1. Return ONLY raw JSON that passes JSON.parse() - no markdown, code blocks, explanatory text, or extra characters
2586
- 2. Include ALL required fields with correct data types and satisfy ALL schema constraints (anyOf, oneOf, allOf, not, enum, pattern, min/max, conditionals)
2587
- 3. Your response must be the JSON object itself, nothing else
2588
-
2589
- INVALID: \`\`\`json{"key":"value"}\`\`\` or "Here is: {"key":"value"}"
2590
- VALID: {"key":"value"}` }) {
2591
- return [
2592
- prompt != null && prompt.length > 0 ? prompt : void 0,
2593
- prompt != null && prompt.length > 0 ? "" : void 0,
2594
- schemaPrefix,
2595
- schema != null ? JSON.stringify(schema, null, 2) : void 0,
2596
- schemaSuffix
2597
- ].filter((line) => line != null).join("\n");
2598
- }
2599
- // Validate arguments using JSON schema
2600
- validateSchema(args, schema) {
2601
- const validate = ajv2.compile(schema);
2602
- if (!validate(args)) {
2603
- const errors = new AggregateAjvError2(validate.errors);
2604
- return {
2605
- valid: false,
2606
- error: errors.message
2607
- };
2608
- }
2609
- return {
2610
- valid: true
2611
- };
2612
- }
2613
- };
2614
-
2615
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/sampling/agentic-sampling-executor.js
2616
- var SamplingExecutor = class extends BaseSamplingExecutor {
2617
- agenticExecutor;
2618
- constructor(name, description, allToolNames, toolNameToDetailList, server, config2) {
2619
- super(name, description, allToolNames, toolNameToDetailList, server, config2);
2620
- this.agenticExecutor = new AgenticExecutor(name, allToolNames, toolNameToDetailList, server);
2621
- }
2622
- buildDepGroups() {
2623
- const depGroups = {};
2624
- this.toolNameToDetailList.forEach(([toolName, tool]) => {
2625
- if (tool?.inputSchema) {
2626
- depGroups[toolName] = {
2627
- type: "object",
2628
- description: tool.description || `Tool: ${toolName}`,
2629
- ...tool.inputSchema
2630
- };
2631
- } else {
2632
- const toolSchema = this.server.getHiddenToolSchema(toolName);
2633
- if (toolSchema) {
2634
- depGroups[toolName] = {
2635
- ...toolSchema.schema,
2636
- description: toolSchema.description
2637
- };
2638
- }
2639
- }
2640
- });
2641
- return depGroups;
2642
- }
2643
- executeSampling(args, schema) {
2644
- const validationResult = this.validateSchema(args, schema);
2645
- if (!validationResult.valid) {
2646
- return {
2647
- content: [
2648
- {
2649
- type: "text",
2650
- text: CompiledPrompts.errorResponse({
2651
- errorMessage: validationResult.error || "Validation failed"
2652
- })
2653
- }
2654
- ],
2655
- isError: true
2656
- };
2657
- }
2658
- const createArgsDef = createArgsDefFactory(this.name, this.allToolNames, this.buildDepGroups(), void 0, void 0);
2659
- const agenticSchema = createArgsDef.forAgentic(this.toolNameToDetailList, true);
2660
- const systemPrompt = this.buildSystemPrompt(args.userRequest, agenticSchema, args.context && typeof args.context === "object" ? args.context : void 0);
2661
- return this.runSamplingLoop(() => systemPrompt, agenticSchema);
2662
- }
2663
- async processAction(parsedData, schema, _state, parentSpan) {
2664
- const toolCallData = parsedData;
2665
- if (toolCallData.decision === "complete") {
2666
- return await this.createCompletionResult("Task completed", parentSpan);
2667
- }
2668
- try {
2669
- const { action: _action, decision: _decision, ..._toolArgs } = toolCallData;
2670
- const toolResult = await this.agenticExecutor.execute(toolCallData, schema);
2671
- const resultText = toolResult.content?.filter((content) => content.type === "text")?.map((content) => content.text)?.join("\n") || "No result";
2672
- this.conversationHistory.push({
2673
- role: "assistant",
2674
- content: {
2675
- type: "text",
2676
- text: resultText
2677
- }
2678
- });
2679
- return toolResult;
2680
- } catch (error) {
2681
- return this.createExecutionError(error, parentSpan);
2682
- }
2683
- }
2684
- buildSystemPrompt(userRequest, agenticSchema, context2) {
2685
- const toolList = this.allToolNames.map((name) => {
2686
- const tool = this.toolNameToDetailList.find(([toolName]) => toolName === name);
2687
- const toolSchema = this.server.getHiddenToolSchema(name);
2688
- if (tool && tool[1]) {
2689
- return `- ${name}: ${tool[1].description || `Tool: ${name}`}`;
2690
- } else if (toolSchema) {
2691
- return `- ${name}: ${toolSchema.description}`;
2692
- }
2693
- return `- ${name}`;
2694
- }).join("\n");
2695
- let contextInfo = "";
2696
- if (context2 && typeof context2 === "object" && Object.keys(context2).length > 0) {
2697
- contextInfo = `
2698
-
2699
- Context:
2700
- ${JSON.stringify(context2, null, 2)}`;
2701
- }
2702
- const basePrompt = CompiledPrompts.samplingExecution({
2703
- toolName: this.name,
2704
- description: this.description,
2705
- toolList
2706
- });
2707
- const taskPrompt = `
2708
-
2709
- ## Current Task
2710
- I will now use agentic sampling to complete the following task: "${userRequest}"${contextInfo}
2711
-
2712
- When I need to use a tool, I should specify the tool name in 'action' and provide tool-specific parameters as additional properties.
2713
- When the task is complete, I should use "action": "complete".`;
2714
- return this.injectJsonInstruction({
2715
- prompt: basePrompt + taskPrompt,
2716
- schema: agenticSchema
2717
- });
2718
- }
2719
- };
2720
-
2721
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/agentic/agentic-tool-registrar.js
2722
- function registerAgenticTool(server, { description, name, allToolNames, depGroups, toolNameToDetailList, sampling = false }) {
2723
- const createArgsDef = createArgsDefFactory(name, allToolNames, depGroups, void 0, void 0);
2724
- const isSamplingMode = sampling === true || typeof sampling === "object";
2725
- const samplingConfig = typeof sampling === "object" ? sampling : void 0;
2726
- const agenticExecutor = new AgenticExecutor(name, allToolNames, toolNameToDetailList, server);
2727
- const samplingExecutor = new SamplingExecutor(name, description, allToolNames, toolNameToDetailList, server, samplingConfig);
2728
- description = isSamplingMode ? CompiledPrompts.samplingExecution({
2729
- toolName: name,
2730
- description,
2731
- toolList: allToolNames.map((name2) => `- ${name2}`).join("\n")
2732
- }) : CompiledPrompts.autonomousExecution({
2733
- toolName: name,
2734
- description
2735
- });
2736
- const agenticArgsDef = createArgsDef.forAgentic(toolNameToDetailList, false);
2737
- const argsDef = isSamplingMode ? createArgsDef.forSampling() : agenticArgsDef;
2738
- const schema = allToolNames.length > 0 ? argsDef : {
2739
- type: "object",
2740
- properties: {}
2741
- };
2742
- server.tool(name, description, jsonSchema(createGoogleCompatibleJSONSchema(schema)), async (args) => {
2743
- if (isSamplingMode) {
2744
- return await samplingExecutor.executeSampling(args, schema);
2745
- } else {
2746
- return await agenticExecutor.execute(args, schema);
2747
- }
2748
- });
2749
- }
2750
-
2751
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/workflow/workflow-tool-registrar.js
2752
- init_schema();
2753
-
2754
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/state.js
2755
- var WorkflowState = class {
2756
- currentStepIndex = -1;
2757
- steps = [];
2758
- stepStatuses = [];
2759
- stepResults = [];
2760
- stepErrors = [];
2761
- isInitialized = false;
2762
- isStarted = false;
2763
- constructor(steps) {
2764
- if (steps) {
2765
- this.initialize(steps);
2766
- }
2767
- }
2768
- getCurrentStepIndex() {
2769
- return this.currentStepIndex;
2770
- }
2771
- getSteps() {
2772
- return this.steps;
2773
- }
2774
- isWorkflowInitialized() {
2775
- return this.isInitialized;
2776
- }
2777
- getCurrentStep() {
2778
- if (!this.isInitialized || this.currentStepIndex < 0) {
2779
- return null;
2780
- }
2781
- return this.steps[this.currentStepIndex] || null;
2782
- }
2783
- getNextStep() {
2784
- if (!this.isInitialized) return null;
2785
- const nextIndex = this.currentStepIndex + 1;
2786
- return this.steps[nextIndex] || null;
2787
- }
2788
- // Get the previous step in the workflow
2789
- getPreviousStep() {
2790
- if (!this.isInitialized) return null;
2791
- const prevIndex = this.currentStepIndex - 1;
2792
- return this.steps[prevIndex] || null;
2793
- }
2794
- hasNextStep() {
2795
- return this.getNextStep() !== null;
2796
- }
2797
- // Check if there is a previous step available
2798
- hasPreviousStep() {
2799
- return this.getPreviousStep() !== null;
2800
- }
2801
- // Check if currently at the first step
2802
- isAtFirstStep() {
2803
- return this.isInitialized && this.currentStepIndex === 0;
2804
- }
2805
- // Check if currently at the last step
2806
- isAtLastStep() {
2807
- return this.isInitialized && this.currentStepIndex >= this.steps.length - 1;
2808
- }
2809
- isWorkflowStarted() {
2810
- return this.isStarted;
2811
- }
2812
- isCompleted() {
2813
- return this.isInitialized && this.currentStepIndex > this.steps.length - 1;
2814
- }
2815
- // Mark workflow as completed by moving beyond the last step
2816
- markCompleted() {
2817
- if (this.isInitialized) {
2818
- this.currentStepIndex = this.steps.length;
2819
- }
2820
- }
2821
- initialize(steps) {
2822
- this.steps = steps;
2823
- this.stepStatuses = new Array(steps.length).fill("pending");
2824
- this.stepResults = new Array(steps.length).fill("");
2825
- this.stepErrors = new Array(steps.length).fill("");
2826
- this.currentStepIndex = 0;
2827
- this.isInitialized = true;
2828
- this.isStarted = false;
2829
- }
2830
- // Mark current step as running
2831
- markCurrentStepRunning() {
2832
- if (this.isInitialized && this.currentStepIndex >= 0 && this.currentStepIndex < this.steps.length) {
2833
- this.stepStatuses[this.currentStepIndex] = "running";
2834
- }
2835
- }
2836
- // Mark current step as completed
2837
- markCurrentStepCompleted(result) {
2838
- if (this.isInitialized && this.currentStepIndex >= 0 && this.currentStepIndex < this.steps.length) {
2839
- this.stepStatuses[this.currentStepIndex] = "completed";
2840
- if (result) {
2841
- this.stepResults[this.currentStepIndex] = result;
2842
- }
2843
- }
2844
- }
2845
- // Mark current step as failed
2846
- markCurrentStepFailed(error) {
2847
- if (this.isInitialized && this.currentStepIndex >= 0 && this.currentStepIndex < this.steps.length) {
2848
- this.stepStatuses[this.currentStepIndex] = "failed";
2849
- if (error) {
2850
- this.stepErrors[this.currentStepIndex] = error;
2851
- }
2852
- }
2853
- }
2854
- // Get steps with their status
2855
- getStepsWithStatus() {
2856
- return this.steps.map((step, index) => ({
2857
- ...step,
2858
- status: this.stepStatuses[index] || "pending",
2859
- result: this.stepResults[index] || void 0,
2860
- error: this.stepErrors[index] || void 0
2861
- }));
2862
- }
2863
- // Get basic workflow progress data for template rendering
2864
- getProgressData() {
2865
- return {
2866
- steps: this.steps,
2867
- statuses: this.stepStatuses,
2868
- results: this.stepResults,
2869
- errors: this.stepErrors,
2870
- currentStepIndex: this.currentStepIndex,
2871
- totalSteps: this.steps.length
2872
- };
2873
- }
2874
- start() {
2875
- this.isStarted = true;
2876
- }
2877
- moveToNextStep() {
2878
- if (!this.hasNextStep()) {
2879
- return false;
2880
- }
2881
- this.currentStepIndex++;
2882
- return true;
2883
- }
2884
- // Move to the previous step in the workflow
2885
- moveToPreviousStep() {
2886
- if (!this.hasPreviousStep()) {
2887
- return false;
2888
- }
2889
- this.currentStepIndex--;
2890
- return true;
2891
- }
2892
- // Move to a specific step by index (optional feature)
2893
- moveToStep(stepIndex) {
2894
- if (!this.isInitialized || stepIndex < 0 || stepIndex >= this.steps.length) {
2895
- return false;
2896
- }
2897
- this.currentStepIndex = stepIndex;
2898
- return true;
2899
- }
2900
- reset() {
2901
- this.currentStepIndex = -1;
2902
- this.steps = [];
2903
- this.stepStatuses = [];
2904
- this.stepResults = [];
2905
- this.stepErrors = [];
2906
- this.isInitialized = false;
2907
- this.isStarted = false;
2908
- }
2909
- getDebugInfo() {
2910
- return {
2911
- currentStepIndex: this.currentStepIndex,
2912
- totalSteps: this.steps.length,
2913
- isInitialized: this.isInitialized,
2914
- currentStep: this.getCurrentStep()?.description,
2915
- nextStep: this.getNextStep()?.description,
2916
- previousStep: this.getPreviousStep()?.description,
2917
- isAtFirstStep: this.isAtFirstStep(),
2918
- hasPreviousStep: this.hasPreviousStep()
2919
- };
2920
- }
2921
- };
2922
-
2923
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/workflow/workflow-executor.js
2924
- import { Ajv as Ajv3 } from "ajv";
2925
- import { AggregateAjvError as AggregateAjvError3 } from "@segment/ajv-human-errors";
2926
- import addFormats3 from "ajv-formats";
2927
- var ajv3 = new Ajv3({
2928
- allErrors: true,
2929
- verbose: true
2930
- });
2931
- addFormats3(ajv3);
2932
- var WorkflowExecutor = class {
2933
- name;
2934
- allToolNames;
2935
- toolNameToDetailList;
2936
- createArgsDef;
2937
- server;
2938
- predefinedSteps;
2939
- ensureStepActions;
2940
- toolNameToIdMapping;
2941
- constructor(name, allToolNames, toolNameToDetailList, createArgsDef, server, predefinedSteps, ensureStepActions, toolNameToIdMapping) {
2942
- this.name = name;
2943
- this.allToolNames = allToolNames;
2944
- this.toolNameToDetailList = toolNameToDetailList;
2945
- this.createArgsDef = createArgsDef;
2946
- this.server = server;
2947
- this.predefinedSteps = predefinedSteps;
2948
- this.ensureStepActions = ensureStepActions;
2949
- this.toolNameToIdMapping = toolNameToIdMapping;
2950
- }
2951
- // Helper method to validate required actions are present in workflow steps
2952
- validateRequiredActions(steps) {
2953
- if (!this.ensureStepActions || this.ensureStepActions.length === 0) {
2954
- return {
2955
- valid: true,
2956
- missing: []
2957
- };
2958
- }
2959
- const allStepActions = /* @__PURE__ */ new Set();
2960
- steps.forEach((step) => {
2961
- step.actions.forEach((action) => allStepActions.add(action));
2962
- });
2963
- const missing = [];
2964
- for (const requiredAction of this.ensureStepActions) {
2965
- if (allStepActions.has(requiredAction)) {
2966
- continue;
2967
- }
2968
- if (this.toolNameToIdMapping) {
2969
- const mappedToolId = this.toolNameToIdMapping.get(requiredAction);
2970
- if (mappedToolId && allStepActions.has(mappedToolId)) {
2971
- continue;
2972
- }
2973
- }
2974
- missing.push(requiredAction);
2975
- }
2976
- return {
2977
- valid: missing.length === 0,
2978
- missing
2979
- };
2980
- }
2981
- // Helper method to format workflow progress
2982
- formatProgress(state) {
2983
- const progressData = state.getProgressData();
2984
- return PromptUtils.formatWorkflowProgress(progressData);
2985
- }
2986
- async execute(args, state) {
2987
- if (args.init) {
2988
- state.reset();
2989
- } else {
2990
- if (!state.isWorkflowInitialized() && !args.init) {
2991
- return {
2992
- content: [
2993
- {
2994
- type: "text",
2995
- text: this.predefinedSteps ? WorkflowPrompts.ERRORS.NOT_INITIALIZED.WITH_PREDEFINED : WorkflowPrompts.ERRORS.NOT_INITIALIZED.WITHOUT_PREDEFINED
2996
- }
2997
- ],
2998
- isError: true
2999
- };
3000
- }
3001
- const decision2 = args.decision;
3002
- if (decision2 === "proceed") {
3003
- if (state.isAtLastStep() && state.isWorkflowStarted()) {
3004
- state.markCompleted();
3005
- return {
3006
- content: [
3007
- {
3008
- type: "text",
3009
- text: `## Workflow Completed!
3010
-
3011
- ${this.formatProgress(state)}
3012
-
3013
- ${CompiledPrompts.workflowCompleted({
3014
- totalSteps: state.getSteps().length,
3015
- toolName: this.name,
3016
- newWorkflowInstructions: this.predefinedSteps ? "" : " and new `steps` array"
3017
- })}`
3018
- }
3019
- ],
3020
- isError: false
3021
- };
3022
- }
3023
- if (state.isCompleted()) {
3024
- return {
3025
- content: [
3026
- {
3027
- type: "text",
3028
- text: WorkflowPrompts.ERRORS.ALREADY_AT_FINAL
3029
- }
3030
- ],
3031
- isError: true
3032
- };
3033
- }
3034
- const currentStepIndex = state.getCurrentStepIndex();
3035
- const wasStarted = state.isWorkflowStarted();
3036
- if (state.isWorkflowStarted()) {
3037
- state.moveToNextStep();
3038
- } else {
3039
- state.start();
3040
- }
3041
- const nextStepValidationSchema = this.createArgsDef.forCurrentState(state);
3042
- const nextStepValidationResult = this.validate(args, nextStepValidationSchema);
3043
- if (!nextStepValidationResult.valid) {
3044
- if (wasStarted) {
3045
- state.moveToStep(currentStepIndex);
3046
- } else {
3047
- state.moveToStep(currentStepIndex);
3048
- }
3049
- return {
3050
- content: [
3051
- {
3052
- type: "text",
3053
- text: CompiledPrompts.workflowErrorResponse({
3054
- errorMessage: `Cannot proceed to next step: ${nextStepValidationResult.error || "Arguments validation failed"}`
3055
- })
3056
- }
3057
- ],
3058
- isError: true
3059
- };
3060
- }
3061
- } else if (decision2 === "complete") {
3062
- if (state.isAtLastStep() && state.isWorkflowStarted()) {
3063
- state.markCompleted();
3064
- return {
3065
- content: [
3066
- {
3067
- type: "text",
3068
- text: `## Workflow Completed!
3069
-
3070
- ${this.formatProgress(state)}
3071
-
3072
- ${CompiledPrompts.workflowCompleted({
3073
- totalSteps: state.getSteps().length,
3074
- toolName: this.name,
3075
- newWorkflowInstructions: this.predefinedSteps ? "" : " and new `steps` array"
3076
- })}`
3077
- }
3078
- ],
3079
- isError: false
3080
- };
3081
- } else {
3082
- return {
3083
- content: [
3084
- {
3085
- type: "text",
3086
- text: WorkflowPrompts.ERRORS.CANNOT_COMPLETE_NOT_AT_FINAL
3087
- }
3088
- ],
3089
- isError: true
3090
- };
3091
- }
3092
- }
3093
- }
3094
- const decision = args.decision;
3095
- if (decision !== "proceed") {
3096
- const validationSchema = this.createArgsDef.forCurrentState(state);
3097
- const validationResult = this.validate(args, validationSchema);
3098
- if (!validationResult.valid) {
3099
- return {
3100
- content: [
3101
- {
3102
- type: "text",
3103
- text: CompiledPrompts.workflowErrorResponse({
3104
- errorMessage: validationResult.error || "Arguments validation failed"
3105
- })
3106
- }
3107
- ],
3108
- isError: true
3109
- };
3110
- }
3111
- }
3112
- if (args.init) {
3113
- return this.initialize(args, state);
3114
- }
3115
- return await this.executeStep(args, state);
3116
- }
3117
- initialize(args, state) {
3118
- const steps = args.steps ?? this.predefinedSteps;
3119
- if (!steps || steps.length === 0) {
3120
- return {
3121
- content: [
3122
- {
3123
- type: "text",
3124
- text: WorkflowPrompts.ERRORS.NO_STEPS_PROVIDED
3125
- }
3126
- ],
3127
- isError: true
3128
- };
3129
- }
3130
- const validation = this.validateRequiredActions(steps);
3131
- if (!validation.valid) {
3132
- return {
3133
- content: [
3134
- {
3135
- type: "text",
3136
- text: `## Workflow Validation Failed \u274C
3137
-
3138
- **Missing Required Actions:** The following actions must be included in the workflow steps:
3139
-
3140
- ${validation.missing.map((action) => `- \`${this.toolNameToIdMapping?.get(action) ?? action}\``).join("\n")}`
3141
- }
3142
- ],
3143
- isError: true
3144
- };
3145
- }
3146
- state.initialize(steps);
3147
- return {
3148
- content: [
3149
- {
3150
- type: "text",
3151
- text: `## Workflow Initialized
3152
- ${this.formatProgress(state)}
3153
- ${this.createArgsDef.forInitialStepDescription(steps, state)}`
3154
- }
3155
- ],
3156
- isError: false
3157
- };
3158
- }
3159
- async executeStep(args, state) {
3160
- const currentStep = state.getCurrentStep();
3161
- if (!currentStep) {
3162
- return {
3163
- content: [
3164
- {
3165
- type: "text",
3166
- text: WorkflowPrompts.ERRORS.NO_CURRENT_STEP
3167
- }
3168
- ],
3169
- isError: true
3170
- };
3171
- }
3172
- state.markCurrentStepRunning();
3173
- const results = {
3174
- content: [],
3175
- isError: false
3176
- };
3177
- for (const action of currentStep.actions) {
3178
- try {
3179
- const actionArgs = args[action] || {};
3180
- const actionResult = await this.server.callTool(action, actionArgs);
3181
- if (!results.isError) {
3182
- results.isError = actionResult.isError;
3183
- }
3184
- results.content = results.content.concat(actionResult.content ?? []);
3185
- results.content.push({
3186
- type: "text",
3187
- text: `Action \`${action}\` executed ${actionResult.isError ? "\u274C **FAILED**" : "\u2705 **SUCCESS**"}:`
3188
- });
3189
- } catch (error) {
3190
- results.content.push({
3191
- type: "text",
3192
- text: `${error.message}`
3193
- });
3194
- results.content.push({
3195
- type: "text",
3196
- text: `Action \`${action}\` \u274C **FAILED** with error: `
3197
- });
3198
- results.isError = true;
3199
- }
3200
- }
3201
- if (results.isError) {
3202
- state.markCurrentStepFailed("Step execution failed");
3203
- } else {
3204
- state.markCurrentStepCompleted("Step completed successfully");
3205
- }
3206
- if (state.hasNextStep()) {
3207
- const nextStepArgsDef = this.createArgsDef.forNextState(state);
3208
- results.content.push({
3209
- type: "text",
3210
- text: CompiledPrompts.nextStepDecision({
3211
- toolName: this.name,
3212
- nextStepDescription: state.getNextStep()?.description || "Unknown step",
3213
- nextStepSchema: JSON.stringify(nextStepArgsDef, null, 2)
3214
- })
3215
- });
3216
- } else {
3217
- results.content.push({
3218
- type: "text",
3219
- text: CompiledPrompts.finalStepCompletion({
3220
- statusIcon: results.isError ? "\u274C" : "\u2705",
3221
- statusText: results.isError ? "with errors" : "successfully",
3222
- toolName: this.name,
3223
- newWorkflowInstructions: this.predefinedSteps ? "" : " and new `steps` array"
3224
- })
3225
- });
3226
- }
3227
- results.content.push({
3228
- type: "text",
3229
- text: `## Workflow Progress
3230
- ${this.formatProgress(state)}`
3231
- });
3232
- return results;
3233
- }
3234
- // Validate arguments using JSON schema
3235
- validate(args, schema) {
3236
- const validate = ajv3.compile(schema);
3237
- if (!validate(args)) {
3238
- const errors = new AggregateAjvError3(validate.errors);
3239
- return {
3240
- valid: false,
3241
- error: errors.message
3242
- };
3243
- }
3244
- return {
3245
- valid: true
3246
- };
3247
- }
3248
- };
3249
-
3250
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/sampling/workflow-sampling-executor.js
3251
- var WorkflowSamplingExecutor = class extends BaseSamplingExecutor {
3252
- createArgsDef;
3253
- predefinedSteps;
3254
- workflowExecutor;
3255
- constructor(name, description, allToolNames, toolNameToDetailList, createArgsDef, server, predefinedSteps, config2) {
3256
- super(name, description, allToolNames, toolNameToDetailList, server, config2), this.createArgsDef = createArgsDef, this.predefinedSteps = predefinedSteps;
3257
- this.workflowExecutor = new WorkflowExecutor(name, allToolNames, toolNameToDetailList, createArgsDef, server, predefinedSteps);
3258
- }
3259
- async executeWorkflowSampling(args, schema, state) {
3260
- const validationResult = this.validateSchema(args, schema);
3261
- if (!validationResult.valid) {
3262
- return {
3263
- content: [
3264
- {
3265
- type: "text",
3266
- text: CompiledPrompts.workflowErrorResponse({
3267
- errorMessage: validationResult.error || "Validation failed"
3268
- })
3269
- }
3270
- ],
3271
- isError: true
3272
- };
3273
- }
3274
- return await this.runSamplingLoop(() => this.buildWorkflowSystemPrompt(args, state), schema, state);
3275
- }
3276
- async processAction(parsedData, _schema, state, parentSpan) {
3277
- const workflowState = state;
3278
- if (!workflowState) {
3279
- throw new Error("WorkflowState is required for workflow");
3280
- }
3281
- const toolCallData = parsedData;
3282
- if (toolCallData.decision === "complete") {
3283
- return await this.createCompletionResult("Task completed", parentSpan);
3284
- }
3285
- try {
3286
- const workflowResult = await this.workflowExecutor.execute(parsedData, workflowState);
3287
- const resultText = workflowResult.content?.filter((content) => content.type === "text")?.map((content) => content.text)?.join("\n") || "No result";
3288
- this.conversationHistory.push({
3289
- role: "assistant",
3290
- content: {
3291
- type: "text",
3292
- text: resultText
3293
- }
3294
- });
3295
- return workflowResult;
3296
- } catch (error) {
3297
- return this.createExecutionError(error, parentSpan);
3298
- }
3299
- }
3300
- buildWorkflowSystemPrompt(args, state) {
3301
- const workflowSchema = this.createArgsDef.forCurrentState(state);
3302
- const basePrompt = CompiledPrompts.samplingWorkflowExecution({
3303
- toolName: this.name,
3304
- description: this.description,
3305
- workflowSchema: `${JSON.stringify(workflowSchema, null, 2)}`
3306
- });
3307
- let contextInfo = "";
3308
- if (args.context && typeof args.context === "object" && Object.keys(args.context).length > 0) {
3309
- contextInfo = `
3310
-
3311
- Context:
3312
- ${JSON.stringify(args.context, null, 2)}`;
3313
- }
3314
- const workflowPrompt = `
3315
-
3316
- Current Task: <user_request>${args.userRequest}</user_request>${contextInfo}`;
3317
- return this.injectJsonInstruction({
3318
- prompt: basePrompt + workflowPrompt,
3319
- schema: workflowSchema
3320
- });
3321
- }
3322
- };
3323
-
3324
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/workflow/workflow-tool-registrar.js
3325
- function registerAgenticWorkflowTool(server, { description, name, allToolNames, depGroups, toolNameToDetailList, predefinedSteps, sampling = false, ensureStepActions, toolNameToIdMapping }) {
3326
- const createArgsDef = createArgsDefFactory(name, allToolNames, depGroups, predefinedSteps, ensureStepActions);
3327
- const isSamplingMode = sampling === true || typeof sampling === "object";
3328
- const samplingConfig = typeof sampling === "object" ? sampling : void 0;
3329
- const workflowExecutor = new WorkflowExecutor(name, allToolNames, toolNameToDetailList, createArgsDef, server, predefinedSteps, ensureStepActions, toolNameToIdMapping);
3330
- const workflowSamplingExecutor = new WorkflowSamplingExecutor(name, description, allToolNames, toolNameToDetailList, createArgsDef, server, predefinedSteps, samplingConfig);
3331
- const workflowState = new WorkflowState();
3332
- const planningInstructions = predefinedSteps ? "- Set `init: true` (steps are predefined)" : "- Set `init: true` and define complete `steps` array";
3333
- const baseDescription = isSamplingMode ? CompiledPrompts.samplingExecution({
3334
- toolName: name,
3335
- description,
3336
- toolList: allToolNames.map((name2) => `- ${name2}`).join("\n")
3337
- }) : CompiledPrompts.workflowExecution({
3338
- toolName: name,
3339
- description,
3340
- planningInstructions
3341
- });
3342
- const argsDef = isSamplingMode ? createArgsDef.forSampling() : createArgsDef.forTool();
3343
- const toolDescription = isSamplingMode ? baseDescription : createArgsDef.forToolDescription(baseDescription, workflowState);
3344
- server.tool(name, toolDescription, jsonSchema(createGoogleCompatibleJSONSchema(argsDef)), async (args) => {
3345
- try {
3346
- if (isSamplingMode) {
3347
- return await workflowSamplingExecutor.executeWorkflowSampling(args, argsDef, workflowState);
3348
- } else {
3349
- return await workflowExecutor.execute(args, workflowState);
3350
- }
3351
- } catch (error) {
3352
- workflowState.reset();
3353
- return {
3354
- content: [
3355
- {
3356
- type: "text",
3357
- text: `Workflow execution error: ${error.message}`
3358
- }
3359
- ],
3360
- isError: true
3361
- };
3362
- }
3363
- });
3364
- }
3365
-
3366
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/tool-tag-processor.js
3367
- var ALL_TOOLS_PLACEHOLDER = "__ALL__";
3368
- function findToolId(toolName, tools, toolNameMapping) {
3369
- const mappedId = toolNameMapping?.get(toolName);
3370
- if (mappedId) {
3371
- return mappedId;
3372
- }
3373
- return Object.keys(tools).find((id) => {
3374
- const dotNotation = id.replace(/_/g, ".");
3375
- return toolName === id || toolName === dotNotation;
3376
- });
3377
- }
3378
- function processToolTags({ description, tagToResults, $, tools, toolOverrides, toolNameMapping }) {
3379
- tagToResults.tool.forEach((toolEl) => {
3380
- const toolName = toolEl.attribs.name;
3381
- if (!toolName || toolName.includes(ALL_TOOLS_PLACEHOLDER)) {
3382
- $(toolEl).remove();
3383
- return;
3384
- }
3385
- const override = toolOverrides.get(toolName);
3386
- if (override?.visibility?.hidden) {
3387
- $(toolEl).remove();
3388
- } else if (override?.visibility?.public) {
3389
- $(toolEl).replaceWith(`<tool name="${toolName}"/>`);
3390
- } else {
3391
- const toolId = findToolId(toolName, tools, toolNameMapping);
3392
- if (toolId) {
3393
- $(toolEl).replaceWith(`<action action="${toolId}"/>`);
3394
- }
3395
- }
3396
- });
3397
- return $.root().html() ?? description;
3398
- }
3399
-
3400
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/compose.js
3401
- init_built_in();
3402
- init_logger();
3403
- init_plugin_utils();
3404
-
3405
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/plugin-manager.js
3406
- init_plugin_utils();
3407
- init_logger();
3408
- var PluginManager = class {
3409
- server;
3410
- plugins;
3411
- logger;
3412
- constructor(server) {
3413
- this.server = server;
3414
- this.plugins = [];
3415
- this.logger = createLogger("mcpc.plugin-manager");
3416
- this.logger.setServer(server);
3417
- }
3418
- /**
3419
- * Get all registered plugins
3420
- */
3421
- getPlugins() {
3422
- return [
3423
- ...this.plugins
3424
- ];
3425
- }
3426
- /**
3427
- * Get plugin names
3428
- */
3429
- getPluginNames() {
3430
- return this.plugins.map((p2) => p2.name);
3431
- }
3432
- /**
3433
- * Check if a plugin is registered
3434
- */
3435
- hasPlugin(name) {
3436
- return this.plugins.some((p2) => p2.name === name);
3437
- }
3438
- /**
3439
- * Add a plugin with validation and error handling
3440
- */
3441
- async addPlugin(plugin) {
3442
- const validation = validatePlugins([
3443
- plugin
3444
- ]);
3445
- if (!validation.valid) {
3446
- const errorMsg = validation.errors.join(", ");
3447
- throw new Error(`Invalid plugin "${plugin.name}": ${errorMsg}`);
3448
- }
3449
- if (this.plugins.some((p2) => p2.name === plugin.name)) {
3450
- await this.logger.warning(`Plugin "${plugin.name}" already registered, skipping`);
3451
- return;
3452
- }
3453
- if (plugin.dependencies) {
3454
- const missingDeps = plugin.dependencies.filter((dep) => !this.plugins.some((p2) => p2.name === dep));
3455
- if (missingDeps.length > 0) {
3456
- throw new Error(`Plugin "${plugin.name}" has missing dependencies: ${missingDeps.join(", ")}`);
3457
- }
3458
- }
3459
- this.plugins.push(plugin);
3460
- if (plugin.configureServer) {
3461
- try {
3462
- await plugin.configureServer(this.server);
3463
- } catch (error) {
3464
- this.plugins = this.plugins.filter((p2) => p2.name !== plugin.name);
3465
- const errorMsg = error instanceof Error ? error.message : String(error);
3466
- throw new Error(`Plugin "${plugin.name}" configuration failed: ${errorMsg}`);
3467
- }
3468
- }
3469
- }
3470
- /**
3471
- * Load and register a plugin from a file path
3472
- */
3473
- async loadPluginFromPath(pluginPath, options = {
3474
- cache: true
3475
- }) {
3476
- const plugin = await loadPlugin(pluginPath, options);
3477
- await this.addPlugin(plugin);
3478
- }
3479
- /**
3480
- * Trigger composeStart hooks for all applicable plugins
3481
- */
3482
- async triggerComposeStart(context2) {
3483
- const startPlugins = this.plugins.filter((p2) => p2.composeStart && shouldApplyPlugin(p2, context2.mode));
3484
- const sortedPlugins = sortPluginsByOrder(startPlugins);
3485
- for (const plugin of sortedPlugins) {
3486
- if (plugin.composeStart) {
3487
- try {
3488
- await plugin.composeStart(context2);
3489
- } catch (error) {
3490
- const errorMsg = error instanceof Error ? error.message : String(error);
3491
- await this.logger.error(`Plugin "${plugin.name}" composeStart failed: ${errorMsg}`);
3492
- }
3493
- }
3494
- }
3495
- }
3496
- /**
3497
- * Apply transformTool hooks to a tool during composition
3498
- */
3499
- async applyTransformToolHooks(tool, context2) {
3500
- const transformPlugins = this.plugins.filter((p2) => p2.transformTool && shouldApplyPlugin(p2, context2.mode));
3501
- if (transformPlugins.length === 0) {
3502
- return tool;
3503
- }
3504
- const sortedPlugins = sortPluginsByOrder(transformPlugins);
3505
- let currentTool = tool;
3506
- for (const plugin of sortedPlugins) {
3507
- if (plugin.transformTool) {
3508
- try {
3509
- const result = await plugin.transformTool(currentTool, context2);
3510
- if (result) {
3511
- currentTool = result;
3512
- }
3513
- } catch (error) {
3514
- const errorMsg = error instanceof Error ? error.message : String(error);
3515
- await this.logger.error(`Plugin "${plugin.name}" transformTool failed for "${context2.toolName}": ${errorMsg}`);
3516
- }
3517
- }
3518
- }
3519
- return currentTool;
3520
- }
3521
- /**
3522
- * Trigger finalizeComposition hooks for all applicable plugins
3523
- */
3524
- async triggerFinalizeComposition(tools, context2) {
3525
- const finalizePlugins = this.plugins.filter((p2) => p2.finalizeComposition && shouldApplyPlugin(p2, context2.mode));
3526
- const sortedPlugins = sortPluginsByOrder(finalizePlugins);
3527
- for (const plugin of sortedPlugins) {
3528
- if (plugin.finalizeComposition) {
3529
- try {
3530
- await plugin.finalizeComposition(tools, context2);
3531
- } catch (error) {
3532
- const errorMsg = error instanceof Error ? error.message : String(error);
3533
- await this.logger.error(`Plugin "${plugin.name}" finalizeComposition failed: ${errorMsg}`);
3534
- }
3535
- }
3536
- }
3537
- }
3538
- /**
3539
- * Trigger composeEnd hooks for all applicable plugins
3540
- */
3541
- async triggerComposeEnd(context2) {
3542
- const endPlugins = this.plugins.filter((p2) => p2.composeEnd && shouldApplyPlugin(p2, context2.mode));
3543
- const sortedPlugins = sortPluginsByOrder(endPlugins);
3544
- for (const plugin of sortedPlugins) {
3545
- if (plugin.composeEnd) {
3546
- try {
3547
- await plugin.composeEnd(context2);
3548
- } catch (error) {
3549
- const errorMsg = error instanceof Error ? error.message : String(error);
3550
- await this.logger.error(`Plugin "${plugin.name}" composeEnd failed: ${errorMsg}`);
3551
- }
3552
- }
3553
- }
3554
- }
3555
- /**
3556
- * Dispose all plugins and cleanup resources
3557
- */
3558
- async dispose() {
3559
- for (const plugin of this.plugins) {
3560
- if (plugin.dispose) {
3561
- try {
3562
- await plugin.dispose();
3563
- } catch (error) {
3564
- const errorMsg = error instanceof Error ? error.message : String(error);
3565
- await this.logger.error(`Plugin "${plugin.name}" dispose failed: ${errorMsg}`);
3566
- }
3567
- }
3568
- }
3569
- this.plugins = [];
3570
- }
3571
- };
3572
-
3573
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/tool-manager.js
3574
- var ToolManager = class {
3575
- toolRegistry = /* @__PURE__ */ new Map();
3576
- toolConfigs = /* @__PURE__ */ new Map();
3577
- toolNameMapping = /* @__PURE__ */ new Map();
3578
- publicTools = [];
3579
- /**
3580
- * Get tool name mapping (for external access)
3581
- */
3582
- getToolNameMapping() {
3583
- return this.toolNameMapping;
3584
- }
3585
- /**
3586
- * Register a tool in the registry
3587
- */
3588
- registerTool(name, description, schema, callback, options = {}) {
3589
- this.toolRegistry.set(name, {
3590
- callback,
3591
- description,
3592
- schema
3593
- });
3594
- if (options.internal) {
3595
- this.toolConfigs.set(name, {
3596
- visibility: {
3597
- hidden: true
3598
- }
3599
- });
3600
- }
3601
- }
3602
- /**
3603
- * Explicitly mark a tool as public (exposed to MCP clients)
3604
- */
3605
- addPublicTool(name, description, schema) {
3606
- const existingTool = this.publicTools.find((t) => t.name === name);
3607
- if (!existingTool) {
3608
- this.publicTools.push({
3609
- name,
3610
- description,
3611
- inputSchema: schema
3612
- });
3613
- }
3614
- }
3615
- /**
3616
- * Check if a tool is public (exposed to MCP clients)
3617
- */
3618
- isPublic(name) {
3619
- const config2 = this.toolConfigs.get(name);
3620
- return config2?.visibility?.public === true;
3621
- }
3622
- /**
3623
- * Check if a tool is hidden from agent context
3624
- */
3625
- isHidden(name) {
3626
- const config2 = this.toolConfigs.get(name);
3627
- return config2?.visibility?.hidden === true;
3628
- }
3629
- /**
3630
- * Get all public tool names (exposed to MCP clients)
3631
- */
3632
- getPublicToolNames() {
3633
- return Array.from(this.toolConfigs.entries()).filter(([_name, config2]) => config2.visibility?.public === true).map(([name]) => this.resolveToolName(name) ?? name);
3634
- }
3635
- /**
3636
- * Get all hidden tool names
3637
- */
3638
- getHiddenToolNames() {
3639
- return Array.from(this.toolConfigs.entries()).filter(([_name, config2]) => config2.visibility?.hidden === true).map(([name]) => this.resolveToolName(name) ?? name);
3640
- }
3641
- /**
3642
- * Get all public tools
3643
- */
3644
- getPublicTools() {
3645
- return [
3646
- ...this.publicTools
3647
- ];
3648
- }
3649
- /**
3650
- * Set public tools list
3651
- */
3652
- setPublicTools(tools) {
3653
- this.publicTools = [
3654
- ...tools
3655
- ];
3656
- }
3657
- /**
3658
- * Get tool callback by name
3659
- */
3660
- getToolCallback(name) {
3661
- return this.toolRegistry.get(name)?.callback;
3662
- }
3663
- /**
3664
- * Check if tool exists in registry
3665
- */
3666
- hasToolNamed(name) {
3667
- return this.toolRegistry.has(name) || this.toolNameMapping.has(name) && this.toolRegistry.has(this.toolNameMapping.get(name));
3668
- }
3669
- /**
3670
- * Resolve a tool name to its internal format
3671
- */
3672
- resolveToolName(name) {
3673
- if (this.toolRegistry.has(name)) {
3674
- return name;
3675
- }
3676
- const mappedName = this.toolNameMapping.get(name);
3677
- if (mappedName && this.toolRegistry.has(mappedName)) {
3678
- return mappedName;
3679
- }
3680
- if (this.toolConfigs.has(name)) {
3681
- const cfgMapped = this.toolNameMapping.get(name);
3682
- if (cfgMapped && this.toolRegistry.has(cfgMapped)) {
3683
- return cfgMapped;
3684
- }
3685
- }
3686
- return void 0;
3687
- }
3688
- /**
3689
- * Configure tool behavior
3690
- */
3691
- configTool(toolName, config2) {
3692
- this.toolConfigs.set(toolName, config2);
3693
- }
3694
- /**
3695
- * Get tool configuration
3696
- */
3697
- getToolConfig(toolName) {
3698
- return this.toolConfigs.get(toolName);
3699
- }
3700
- /**
3701
- * Find tool configuration (with mapping fallback)
3702
- */
3703
- findToolConfig(toolId) {
3704
- const directConfig = this.toolConfigs.get(toolId);
3705
- if (directConfig) {
3706
- return directConfig;
3707
- }
3708
- const mappedName = this.toolNameMapping.get(toolId);
3709
- if (mappedName && this.toolConfigs.has(mappedName)) {
3710
- return this.toolConfigs.get(mappedName);
3711
- }
3712
- return void 0;
3713
- }
3714
- /**
3715
- * Remove tool configuration
3716
- */
3717
- removeToolConfig(toolName) {
3718
- return this.toolConfigs.delete(toolName);
3719
- }
3720
- /**
3721
- * Set tool name mapping
3722
- */
3723
- setToolNameMapping(from, to) {
3724
- this.toolNameMapping.set(from, to);
3725
- }
3726
- /**
3727
- * Get tool schema if it's hidden (for internal access)
3728
- */
3729
- getHiddenToolSchema(name) {
3730
- const tool = this.toolRegistry.get(name);
3731
- const config2 = this.toolConfigs.get(name);
3732
- if (tool && config2?.visibility?.hidden && tool.schema) {
3733
- return {
3734
- description: tool.description,
3735
- schema: tool.schema
3736
- };
3737
- }
3738
- return void 0;
3739
- }
3740
- /**
3741
- * Get total tool count
3742
- */
3743
- getTotalToolCount() {
3744
- return this.toolRegistry.size;
3745
- }
3746
- /**
3747
- * Get all tool entries
3748
- */
3749
- getToolEntries() {
3750
- return Array.from(this.toolRegistry.entries());
3751
- }
3752
- /**
3753
- * Get tool registry (for external access)
3754
- */
3755
- getToolRegistry() {
3756
- return this.toolRegistry;
3757
- }
3758
- };
3759
-
3760
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/compose.js
3761
- init_compose_helpers();
3762
- var ALL_TOOLS_PLACEHOLDER2 = "__ALL__";
3763
- var ComposableMCPServer = class extends Server {
3764
- pluginManager;
3765
- toolManager;
3766
- logger = createLogger("mcpc.compose");
3767
- // Legacy property for backward compatibility
3768
- get toolNameMapping() {
3769
- return this.toolManager.getToolNameMapping();
3770
- }
3771
- constructor(_serverInfo, options) {
3772
- const enhancedOptions = {
3773
- ...options,
3774
- capabilities: {
3775
- logging: {},
3776
- tools: {},
3777
- sampling: {},
3778
- ...options?.capabilities ?? {}
3779
- }
3780
- };
3781
- super(_serverInfo, enhancedOptions);
3782
- this.logger.setServer(this);
3783
- this.pluginManager = new PluginManager(this);
3784
- this.toolManager = new ToolManager();
3785
- }
3786
- /**
3787
- * Initialize built-in plugins - called during setup
3788
- */
3789
- async initBuiltInPlugins() {
3790
- const builtInPlugins = getBuiltInPlugins();
3791
- const validation = validatePlugins(builtInPlugins);
3792
- if (!validation.valid) {
3793
- await this.logger.warning("Built-in plugin validation issues:");
3794
- for (const error of validation.errors) {
3795
- await this.logger.warning(` - ${error}`);
3796
- }
3797
- }
3798
- for (const plugin of builtInPlugins) {
3799
- await this.pluginManager.addPlugin(plugin);
3800
- }
3801
- }
3802
- /**
3803
- * Apply plugin transformations to tool arguments/results
3804
- * Supports runtime transformation hooks for input/output processing
3805
- */
3806
- async applyPluginTransforms(toolName, data, direction, originalArgs) {
3807
- const hookName = direction === "input" ? "transformInput" : "transformOutput";
3808
- const plugins = this.pluginManager.getPlugins().filter((p2) => p2[hookName]);
3809
- if (plugins.length === 0) {
3810
- return data;
3811
- }
3812
- const { sortPluginsByOrder: sortPluginsByOrder2 } = await Promise.resolve().then(() => (init_plugin_utils(), plugin_utils_exports));
3813
- const sortedPlugins = sortPluginsByOrder2(plugins);
3814
- let currentData = data;
3815
- const context2 = {
3816
- toolName,
3817
- server: this,
3818
- direction,
3819
- originalArgs
3820
- };
3821
- for (const plugin of sortedPlugins) {
3822
- const hook = plugin[hookName];
3823
- if (hook) {
3824
- try {
3825
- const result = await hook(currentData, context2);
3826
- if (result !== void 0) {
3827
- currentData = result;
3828
- }
3829
- } catch (error) {
3830
- const errorMsg = error instanceof Error ? error.message : String(error);
3831
- await this.logger.error(`Plugin "${plugin.name}" ${hookName} failed for "${toolName}": ${errorMsg}`);
3832
- }
3833
- }
3834
- }
3835
- return currentData;
3836
- }
3837
- /**
3838
- * Resolve a tool name to its internal format
3839
- */
3840
- resolveToolName(name) {
3841
- return this.toolManager.resolveToolName(name);
3842
- }
3843
- tool(name, description, paramsSchema, cb, options = {}) {
3844
- const jsonSchemaObj = extractJsonSchema(paramsSchema);
3845
- this.toolManager.registerTool(name, description, jsonSchemaObj, cb, options);
3846
- if (!options.internal) {
3847
- this.toolManager.addPublicTool(name, description, jsonSchemaObj);
3848
- }
3849
- if (options.plugins) {
3850
- for (const plugin of options.plugins) {
3851
- this.pluginManager.addPlugin(plugin);
3852
- }
3853
- }
3854
- this.setRequestHandler(ListToolsRequestSchema, () => {
3855
- return {
3856
- tools: this.toolManager.getPublicTools()
3857
- };
3858
- });
3859
- this.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
3860
- const { name: toolName, arguments: args } = request.params;
3861
- const handler = this.getToolCallback(toolName);
3862
- if (!handler) {
3863
- throw new Error(`Tool ${toolName} not found`);
3864
- }
3865
- const processedArgs = await this.applyPluginTransforms(toolName, args, "input");
3866
- const result = await handler(processedArgs, extra);
3867
- return await this.applyPluginTransforms(toolName, result, "output", args);
3868
- });
3869
- this.setRequestHandler(SetLevelRequestSchema, (request) => {
3870
- const { level } = request.params;
3871
- this.logger.setLevel(level);
3872
- return {};
3873
- });
3874
- }
3875
- /**
3876
- * Get tool callback from registry
3877
- */
3878
- getToolCallback(name) {
3879
- return this.toolManager.getToolCallback(name);
3880
- }
3881
- /**
3882
- * Find tool configuration
3883
- */
3884
- findToolConfig(toolId) {
3885
- return this.toolManager.findToolConfig(toolId);
3886
- }
3887
- /**
3888
- * Call any registered tool directly, whether it's public or internal
3889
- */
3890
- async callTool(name, args) {
3891
- const resolvedName = this.resolveToolName(name);
3892
- if (!resolvedName) {
3893
- throw new Error(`Tool ${name} not found`);
3894
- }
3895
- const callback = this.getToolCallback(resolvedName);
3896
- if (!callback) {
3897
- throw new Error(`Tool ${name} not found`);
3898
- }
3899
- const processedArgs = await this.applyPluginTransforms(resolvedName, args, "input");
3900
- const result = await callback(processedArgs);
3901
- return await this.applyPluginTransforms(resolvedName, result, "output", args);
3902
- }
3903
- /**
3904
- * Get all public tool names (exposed to MCP clients)
3905
- */
3906
- getPublicToolNames() {
3907
- return this.toolManager.getPublicToolNames();
3908
- }
3909
- /**
3910
- * Get all public tools (for AI SDK integration)
3911
- */
3912
- getPublicTools() {
3913
- return this.toolManager.getPublicTools();
3914
- }
3915
- /**
3916
- * Get all hidden tool names
3917
- */
3918
- getHiddenToolNames() {
3919
- return this.toolManager.getHiddenToolNames();
3920
- }
3921
- /**
3922
- * Get hidden tool schema by name (for internal access)
3923
- */
3924
- getHiddenToolSchema(name) {
3925
- return this.toolManager.getHiddenToolSchema(name);
3926
- }
3927
- /**
3928
- * Check if a tool exists (visible or hidden)
3929
- */
3930
- hasToolNamed(name) {
3931
- return this.toolManager.hasToolNamed(name);
3932
- }
3933
- /**
3934
- * Configure tool behavior
3935
- */
3936
- configTool(toolName, config2) {
3937
- this.toolManager.configTool(toolName, config2);
3938
- }
3939
- /**
3940
- * Get tool configuration
3941
- */
3942
- getToolConfig(toolName) {
3943
- return this.toolManager.getToolConfig(toolName);
3944
- }
3945
- /**
3946
- * Remove tool configuration
3947
- */
3948
- removeToolConfig(toolName) {
3949
- return this.toolManager.removeToolConfig(toolName);
3950
- }
3951
- /**
3952
- * Register a tool plugin with validation and error handling
3953
- */
3954
- async addPlugin(plugin) {
3955
- await this.pluginManager.addPlugin(plugin);
3956
- }
3957
- /**
3958
- * Load and register a plugin from a file path with optional parameters
3959
- */
3960
- async loadPluginFromPath(pluginPath, options = {
3961
- cache: true
3962
- }) {
3963
- await this.pluginManager.loadPluginFromPath(pluginPath, options);
3964
- }
3965
- /**
3966
- * Apply plugins to all tools in registry and handle visibility configurations
3967
- */
3968
- async processToolsWithPlugins(externalTools, mode) {
3969
- const { processToolsWithPlugins: processTools } = await Promise.resolve().then(() => (init_compose_helpers(), compose_helpers_exports));
3970
- await processTools(this, externalTools, mode);
3971
- }
3972
- /**
3973
- * Dispose all plugins and cleanup resources
3974
- */
3975
- async disposePlugins() {
3976
- await this.pluginManager.dispose();
3977
- }
3978
- async compose(name, description, depsConfig = {
3979
- mcpServers: {}
3980
- }, options = {
3981
- mode: "agentic"
3982
- }) {
3983
- const refDesc = options.refs?.join("") ?? "";
3984
- const { tagToResults } = parseTags(description + refDesc, [
3985
- "tool",
3986
- "fn"
3987
- ]);
3988
- await this.pluginManager.triggerComposeStart({
3989
- serverName: name ?? "anonymous",
3990
- description,
3991
- mode: options.mode ?? "agentic",
3992
- server: this,
3993
- availableTools: []
3994
- });
3995
- tagToResults.tool.forEach((toolEl) => {
3996
- const toolName = toolEl.attribs.name;
3997
- const toolDescription = toolEl.attribs.description;
3998
- const isHidden = toolEl.attribs.hide !== void 0;
3999
- const isPublic = toolEl.attribs.global !== void 0;
4000
- if (toolName) {
4001
- this.toolManager.configTool(toolName, {
4002
- description: toolDescription,
4003
- visibility: {
4004
- hidden: isHidden,
4005
- public: isPublic
4006
- }
4007
- });
4008
- }
4009
- });
4010
- const toolNameToIdMapping = /* @__PURE__ */ new Map();
4011
- const requestedToolNames = /* @__PURE__ */ new Set();
4012
- const availableToolNames = /* @__PURE__ */ new Set();
4013
- tagToResults.tool.forEach((tool) => {
4014
- if (tool.attribs.name) {
4015
- requestedToolNames.add(tool.attribs.name);
4016
- }
4017
- });
4018
- const { tools, cleanupClients } = await composeMcpDepTools(depsConfig, ({ mcpName, toolNameWithScope, toolId }) => {
4019
- toolNameToIdMapping.set(toolNameWithScope, toolId);
4020
- availableToolNames.add(toolNameWithScope);
4021
- availableToolNames.add(toolId);
4022
- availableToolNames.add(`${mcpName}.${ALL_TOOLS_PLACEHOLDER2}`);
4023
- availableToolNames.add(mcpName);
4024
- this.toolManager.setToolNameMapping(toolNameWithScope, toolId);
4025
- const internalName = toolNameWithScope.includes(".") ? toolNameWithScope.split(".").slice(1).join(".") : toolNameWithScope;
4026
- if (!this.toolNameMapping.has(internalName)) {
4027
- this.toolManager.setToolNameMapping(internalName, toolId);
4028
- }
4029
- const matchingStep = options.steps?.find((step) => step.actions.includes(toolNameWithScope));
4030
- if (matchingStep) {
4031
- const actionIndex = matchingStep.actions.indexOf(toolNameWithScope);
4032
- if (actionIndex !== -1) {
4033
- matchingStep.actions[actionIndex] = toolId;
4034
- }
4035
- return true;
4036
- }
4037
- return tagToResults.tool.find((tool) => {
4038
- const selectAll = tool.attribs.name === `${mcpName}.${ALL_TOOLS_PLACEHOLDER2}` || tool.attribs.name === `${mcpName}`;
4039
- if (selectAll) {
4040
- return true;
4041
- }
4042
- return tool.attribs.name === toolNameWithScope || tool.attribs.name === toolId;
4043
- });
4044
- });
4045
- const unmatchedTools = Array.from(requestedToolNames).filter((toolName) => !availableToolNames.has(toolName));
4046
- if (unmatchedTools.length > 0) {
4047
- await this.logger.warning(`Tool matching warnings for agent "${name}":`);
4048
- for (const toolName of unmatchedTools) {
4049
- await this.logger.warning(` \u2022 Tool not found: "${toolName}"`);
4050
- }
4051
- await this.logger.warning(` Available tools: ${Array.from(availableToolNames).sort().join(", ")}`);
4052
- }
4053
- Object.entries(tools).forEach(([toolId, tool]) => {
4054
- this.toolManager.registerTool(toolId, tool.description || "No description available", tool.inputSchema, tool.execute);
4055
- });
4056
- await this.processToolsWithPlugins(tools, options.mode ?? "agentic");
4057
- await this.pluginManager.triggerFinalizeComposition(tools, {
4058
- serverName: name ?? "anonymous",
4059
- mode: options.mode ?? "agentic",
4060
- server: this,
4061
- toolNames: Object.keys(tools)
4062
- });
4063
- this.onclose = async () => {
4064
- await cleanupClients();
4065
- await this.disposePlugins();
4066
- await this.logger.info(`[${name}] Event: closed - cleaned up dependent clients and plugins`);
4067
- };
4068
- this.onerror = async (error) => {
4069
- await this.logger.error(`[${name}] Event: error - ${error?.stack ?? String(error)}`);
4070
- await cleanupClients();
4071
- await this.disposePlugins();
4072
- await this.logger.info(`[${name}] Action: cleaned up dependent clients and plugins`);
4073
- };
4074
- const toolNameToDetailList = Object.entries(tools);
4075
- const publicToolNames = this.getPublicToolNames();
4076
- const hiddenToolNames = this.getHiddenToolNames();
4077
- const contextToolNames = toolNameToDetailList.map(([name2]) => name2).filter((n) => !hiddenToolNames.includes(n));
4078
- publicToolNames.forEach((toolId) => {
4079
- const tool = tools[toolId];
4080
- if (!tool) {
4081
- throw new Error(`Public tool ${toolId} not found in registry, available: ${Object.keys(tools).join(", ")}`);
4082
- }
4083
- this.tool(toolId, tool.description || "No description available", jsonSchema(tool.inputSchema), tool.execute, {
4084
- internal: false
4085
- });
4086
- });
4087
- await this.pluginManager.triggerComposeEnd({
4088
- toolName: name,
4089
- pluginNames: this.pluginManager.getPluginNames(),
4090
- mode: options.mode ?? "agentic",
4091
- server: this,
4092
- stats: {
4093
- totalTools: this.toolManager.getTotalToolCount(),
4094
- publicTools: publicToolNames.length,
4095
- hiddenTools: hiddenToolNames.length
4096
- }
4097
- });
4098
- if (!name) {
4099
- return;
4100
- }
4101
- const desTags = parseTags(description, [
4102
- "tool",
4103
- "fn"
4104
- ]);
4105
- description = processToolTags({
4106
- ...desTags,
4107
- description,
4108
- tools,
4109
- toolOverrides: /* @__PURE__ */ new Map(),
4110
- toolNameMapping: toolNameToIdMapping
4111
- });
4112
- const allToolNames = contextToolNames;
4113
- const depGroups = buildDependencyGroups(toolNameToDetailList, hiddenToolNames, publicToolNames, this);
4114
- switch (options.mode ?? "agentic") {
4115
- case "agentic":
4116
- registerAgenticTool(this, {
4117
- description,
4118
- name,
4119
- allToolNames,
4120
- depGroups,
4121
- toolNameToDetailList,
4122
- sampling: options.sampling
4123
- });
4124
- break;
4125
- case "agentic_workflow":
4126
- registerAgenticWorkflowTool(this, {
4127
- description,
4128
- name,
4129
- allToolNames,
4130
- depGroups,
4131
- toolNameToDetailList,
4132
- predefinedSteps: options.steps,
4133
- sampling: options.sampling,
4134
- ensureStepActions: options.ensureStepActions,
4135
- toolNameToIdMapping
4136
- });
4137
- break;
4138
- }
4139
- }
4140
- };
4141
-
4142
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/env.js
4143
- import process6 from "node:process";
4144
- var isSCF = () => Boolean(process6.env.SCF_RUNTIME || process6.env.PROD_SCF);
4145
- if (isSCF()) {
4146
- console.log({
4147
- isSCF: isSCF(),
4148
- SCF_RUNTIME: process6.env.SCF_RUNTIME
4149
- });
4150
- }
4151
-
4152
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/set-up-mcp-compose.js
4153
- function parseMcpcConfigs(conf) {
4154
- const mcpcConfigs = conf ?? [];
4155
- const newMcpcConfigs = [];
4156
- for (const mcpcConfig of mcpcConfigs) {
4157
- if (mcpcConfig?.deps?.mcpServers) {
4158
- for (const [name, config2] of Object.entries(mcpcConfig.deps.mcpServers)) {
4159
- if (config2.smitheryConfig) {
4160
- const streamConfig = connectToSmitheryServer(config2.smitheryConfig);
4161
- mcpcConfig.deps.mcpServers[name] = streamConfig;
4162
- }
4163
- }
4164
- }
4165
- newMcpcConfigs.push(mcpcConfig);
4166
- }
4167
- return newMcpcConfigs;
4168
- }
4169
- async function mcpc(serverConf, composeConf, setupCallback) {
4170
- const server = new ComposableMCPServer(...serverConf);
4171
- const parsed = parseMcpcConfigs(composeConf);
4172
- await server.initBuiltInPlugins();
4173
- for (const mcpcConfig of parsed) {
4174
- if (mcpcConfig.plugins) {
4175
- for (const plugin of mcpcConfig.plugins) {
4176
- if (typeof plugin === "string") {
4177
- await server.loadPluginFromPath(plugin);
4178
- } else {
4179
- await server.addPlugin(plugin);
4180
- }
4181
- }
4182
- }
4183
- }
4184
- if (setupCallback) {
4185
- await setupCallback(server);
4186
- }
4187
- for (const mcpcConfig of parsed) {
4188
- await server.compose(mcpcConfig.name, mcpcConfig.description ?? "", mcpcConfig.deps, mcpcConfig.options);
4189
- }
4190
- return server;
4191
- }
4192
-
4193
- // ../__mcpc__cli_latest/node_modules/@jsr/mcpc__core/mod.js
4194
- init_schema();
4195
-
4196
- // ../__mcpc__cli_latest/node_modules/@mcpc/cli/src/app.js
4197
- var createServer = async (config2) => {
4198
- const serverConfig = config2 || {
4199
- name: "large-result-plugin-example",
4200
- version: "0.1.0",
4201
- agents: [
4202
- {
4203
- name: null,
4204
- description: "",
4205
- plugins: [
4206
- "./plugins/large-result.ts?maxSize=8000&previewSize=4000"
4207
- ]
4208
- }
4209
- ]
4210
- };
4211
- return await mcpc([
4212
- {
4213
- name: serverConfig.name || "mcpc-server",
4214
- version: serverConfig.version || "0.1.0"
4215
- },
4216
- {
4217
- capabilities: serverConfig?.capabilities || {
4218
- tools: {},
4219
- sampling: {},
4220
- logging: {}
4221
- }
4222
- }
4223
- ], serverConfig.agents);
4224
- };
4225
- var createApp = () => {
4226
- const app2 = new OpenAPIHono();
4227
- registerAgent(app2);
4228
- return app2;
4229
- };
4230
-
4231
- // ../__mcpc__cli_latest/node_modules/@mcpc/cli/src/server.js
4232
- import { OpenAPIHono as OpenAPIHono2 } from "@hono/zod-openapi";
4233
-
4234
- // ../__mcpc__cli_latest/node_modules/@mcpc/cli/src/config/loader.js
4235
- import { readFile } from "node:fs/promises";
4236
- import { resolve } from "node:path";
4237
- import process7 from "node:process";
4238
- function printHelp() {
4239
- console.log(`
4240
- MCPC CLI - Model Context Protocol Composer
4241
-
4242
- USAGE:
4243
- npx -y deno run -A jsr:@mcpc/cli/bin [OPTIONS]
4244
-
4245
- OPTIONS:
4246
- --help, -h Show this help message
4247
- --config <json> Inline JSON configuration string
4248
- --config-url <url> Fetch configuration from URL
4249
- --config-file <path> Load configuration from file path
4250
- --request-headers <header>, -H <header>
4251
- Add custom HTTP header for URL fetching
4252
- Format: "Key: Value" or "Key=Value"
4253
- Can be used multiple times
4254
-
4255
- ENVIRONMENT VARIABLES:
4256
- MCPC_CONFIG Inline JSON configuration (same as --config)
4257
- MCPC_CONFIG_URL URL to fetch config from (same as --config-url)
4258
- MCPC_CONFIG_FILE Path to config file (same as --config-file)
4259
-
4260
- EXAMPLES:
4261
- # Show help
4262
- npx -y deno run -A jsr:@mcpc/cli/bin --help
4263
-
4264
- # Load from URL
4265
- npx -y deno run -A jsr:@mcpc/cli/bin --config-url \\
4266
- "https://raw.githubusercontent.com/mcpc-tech/mcpc/main/packages/cli/examples/configs/codex-fork.json"
4267
-
4268
- # Load from URL with custom headers
4269
- npx -y deno run -A jsr:@mcpc/cli/bin \\
4270
- --config-url "https://api.example.com/config.json" \\
4271
- -H "Authorization: Bearer token123" \\
4272
- -H "X-Custom-Header: value"
4273
-
4274
- # Load from file
4275
- npx -y deno run -A jsr:@mcpc/cli/bin --config-file ./my-config.json
4276
-
4277
- # Using environment variable
4278
- export MCPC_CONFIG='[{"name":"agent","description":"..."}]'
4279
- npx -y deno run -A jsr:@mcpc/cli/bin
4280
-
4281
- # Use default configuration (./mcpc.config.json)
4282
- npx -y deno run -A jsr:@mcpc/cli/bin
4283
-
4284
- CONFIGURATION:
4285
- Configuration files support environment variable substitution using $VAR_NAME syntax.
4286
-
4287
- Priority order:
4288
- 1. --config (inline JSON)
4289
- 2. MCPC_CONFIG environment variable
4290
- 3. --config-url or MCPC_CONFIG_URL
4291
- 4. --config-file or MCPC_CONFIG_FILE
4292
- 5. ./mcpc.config.json (default)
4293
-
4294
- For more information, visit: https://github.com/mcpc-tech/mcpc
4295
- `);
4296
- }
4297
- function parseArgs() {
4298
- const args = process7.argv.slice(2);
4299
- const result = {};
4300
- for (let i = 0; i < args.length; i++) {
4301
- const arg = args[i];
4302
- if (arg === "--config" && i + 1 < args.length) {
4303
- result.config = args[++i];
4304
- } else if (arg === "--config-url" && i + 1 < args.length) {
4305
- result.configUrl = args[++i];
4306
- } else if (arg === "--config-file" && i + 1 < args.length) {
4307
- result.configFile = args[++i];
4308
- } else if ((arg === "--request-headers" || arg === "-H") && i + 1 < args.length) {
4309
- const headerStr = args[++i];
4310
- const colonIdx = headerStr.indexOf(":");
4311
- const equalIdx = headerStr.indexOf("=");
4312
- const separatorIdx = colonIdx !== -1 ? equalIdx !== -1 ? Math.min(colonIdx, equalIdx) : colonIdx : equalIdx;
4313
- if (separatorIdx !== -1) {
4314
- const key = headerStr.substring(0, separatorIdx).trim();
4315
- const value = headerStr.substring(separatorIdx + 1).trim();
4316
- if (!result.requestHeaders) {
4317
- result.requestHeaders = {};
4318
- }
4319
- result.requestHeaders[key] = value;
4320
- }
4321
- } else if (arg === "--help" || arg === "-h") {
4322
- result.help = true;
4323
- }
4324
- }
4325
- return result;
4326
- }
4327
- async function loadConfig() {
4328
- const args = parseArgs();
4329
- if (args.help) {
4330
- printHelp();
4331
- process7.exit(0);
4332
- }
4333
- if (args.config) {
4334
- try {
4335
- const parsed = JSON.parse(args.config);
4336
- return normalizeConfig(parsed);
4337
- } catch (error) {
4338
- console.error("Failed to parse --config argument:", error);
4339
- throw error;
4340
- }
4341
- }
4342
- if (process7.env.MCPC_CONFIG) {
4343
- try {
4344
- const parsed = JSON.parse(process7.env.MCPC_CONFIG);
4345
- return normalizeConfig(parsed);
4346
- } catch (error) {
4347
- console.error("Failed to parse MCPC_CONFIG environment variable:", error);
4348
- throw error;
4349
- }
4350
- }
4351
- const configUrl = args.configUrl || process7.env.MCPC_CONFIG_URL;
4352
- if (configUrl) {
4353
- try {
4354
- const headers = {
4355
- "User-Agent": "MCPC-CLI/0.1.0",
4356
- ...args.requestHeaders
4357
- };
4358
- const response = await fetch(configUrl, {
4359
- headers
4360
- });
4361
- if (!response.ok) {
4362
- throw new Error(`HTTP ${response.status}: ${response.statusText}`);
4363
- }
4364
- const content = await response.text();
4365
- const parsed = JSON.parse(content);
4366
- return normalizeConfig(parsed);
4367
- } catch (error) {
4368
- console.error(`Failed to fetch config from ${configUrl}:`, error);
4369
- throw error;
4370
- }
4371
- }
4372
- const configFile = args.configFile || process7.env.MCPC_CONFIG_FILE;
4373
- if (configFile) {
4374
- try {
4375
- const content = await readFile(configFile, "utf-8");
4376
- const parsed = JSON.parse(content);
4377
- return normalizeConfig(parsed);
4378
- } catch (error) {
4379
- if (error.code === "ENOENT") {
4380
- console.error(`Config file not found: ${configFile}`);
4381
- throw error;
4382
- } else {
4383
- console.error(`Failed to load config from ${configFile}:`, error);
4384
- throw error;
4385
- }
4386
- }
4387
- }
4388
- const defaultConfigPath = resolve(process7.cwd(), "mcpc.config.json");
4389
- try {
4390
- const content = await readFile(defaultConfigPath, "utf-8");
4391
- const parsed = JSON.parse(content);
4392
- return normalizeConfig(parsed);
4393
- } catch (error) {
4394
- if (error.code === "ENOENT") {
4395
- return null;
4396
- } else {
4397
- console.error(`Failed to load config from ${defaultConfigPath}:`, error);
4398
- throw error;
4399
- }
4400
- }
4401
- }
4402
- function replaceEnvVars(str) {
4403
- return str.replace(/\$([A-Z_][A-Z0-9_]*)/g, (_match, varName) => {
4404
- return process7.env[varName] || "";
4405
- });
4406
- }
4407
- function replaceEnvVarsInConfig(obj) {
4408
- if (typeof obj === "string") {
4409
- return replaceEnvVars(obj);
4410
- }
4411
- if (Array.isArray(obj)) {
4412
- return obj.map((item) => replaceEnvVarsInConfig(item));
4413
- }
4414
- if (obj && typeof obj === "object") {
4415
- const result = {};
4416
- for (const [key, value] of Object.entries(obj)) {
4417
- result[key] = replaceEnvVarsInConfig(value);
4418
- }
4419
- return result;
4420
- }
4421
- return obj;
4422
- }
4423
- function normalizeConfig(config2) {
4424
- config2 = replaceEnvVarsInConfig(config2);
4425
- if (Array.isArray(config2)) {
4426
- return {
4427
- name: "mcpc-server",
4428
- version: "0.1.0",
4429
- agents: normalizeAgents(config2)
4430
- };
4431
- }
4432
- if (config2 && typeof config2 === "object") {
4433
- const cfg = config2;
4434
- return {
4435
- name: cfg.name || "mcpc-server",
4436
- version: cfg.version || "0.1.0",
4437
- capabilities: cfg.capabilities,
4438
- agents: normalizeAgents(cfg.agents || [])
4439
- };
4440
- }
4441
- throw new Error("Invalid configuration format");
4442
- }
4443
- function normalizeAgents(agents) {
4444
- return agents.map((agent) => {
4445
- if (agent.deps && !agent.deps.mcpServers) {
4446
- agent.deps.mcpServers = {};
4447
- }
4448
- return agent;
4449
- });
4450
- }
4451
- function validateConfig(config2) {
4452
- if (!config2.agents || !Array.isArray(config2.agents)) {
4453
- throw new Error("Configuration must include an 'agents' array");
4454
- }
4455
- for (const agent of config2.agents) {
4456
- if (agent.name === void 0) {
4457
- throw new Error("Each agent must have a 'name' property");
4458
- }
4459
- }
4460
- }
4461
-
4462
- // ../__mcpc__cli_latest/node_modules/@mcpc/cli/src/server.js
4463
- import process8 from "node:process";
4464
- var port = Number(process8.env.PORT || "9000");
4465
- var hostname = "0.0.0.0";
4466
- var config = await loadConfig();
4467
- if (config) {
4468
- console.log(`Loaded configuration with ${config.agents.length} agent(s)`);
4469
- } else {
4470
- console.log("No configuration found, using default example configuration");
4471
- }
4472
- var app = new OpenAPIHono2();
4473
- app.route("core", createApp());
4474
- Deno.serve({
4475
- port,
4476
- hostname
4477
- }, app.fetch);
4478
- export {
4479
- createApp,
4480
- createServer,
4481
- loadConfig,
4482
- validateConfig
4483
- };