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