@mcpc-tech/cli 0.1.2 → 0.1.4

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