@mcpc-tech/cli 0.1.2 → 0.1.3

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