@mcpc-tech/cli 0.1.11 → 0.1.13

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 (2) hide show
  1. package/bin/mcpc.mjs +1624 -1607
  2. package/package.json +1 -1
package/bin/mcpc.mjs CHANGED
@@ -1,442 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire } from 'node:module';
3
3
  const require = createRequire(import.meta.url);
4
- var __defProp = Object.defineProperty;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __esm = (fn, res) => function __init() {
7
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
8
- };
9
- var __export = (target, all) => {
10
- for (var name in all)
11
- __defProp(target, name, { get: all[name], enumerable: true });
12
- };
13
-
14
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/schema.js
15
- function jsonSchema(schema, options = {}) {
16
- if (isWrappedSchema(schema)) {
17
- return schema;
18
- }
19
- return {
20
- [schemaSymbol]: true,
21
- [validatorSymbol]: true,
22
- _type: void 0,
23
- jsonSchema: schema,
24
- validate: options.validate
25
- };
26
- }
27
- function isWrappedSchema(value) {
28
- return typeof value === "object" && value !== null && (schemaSymbol in value && value[schemaSymbol] === true || vercelSchemaSymbol in value && value[vercelSchemaSymbol] === true);
29
- }
30
- function extractJsonSchema(schema) {
31
- if (isWrappedSchema(schema)) {
32
- return schema.jsonSchema;
33
- }
34
- return schema;
35
- }
36
- var schemaSymbol, vercelSchemaSymbol, validatorSymbol;
37
- var init_schema = __esm({
38
- "__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/schema.js"() {
39
- schemaSymbol = Symbol.for("mcpc.schema");
40
- vercelSchemaSymbol = Symbol.for("vercel.ai.schema");
41
- validatorSymbol = Symbol.for("mcpc.validator");
42
- }
43
- });
44
-
45
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/config.js
46
- import process2 from "node:process";
47
- var GEMINI_PREFERRED_FORMAT;
48
- var init_config = __esm({
49
- "__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/config.js"() {
50
- GEMINI_PREFERRED_FORMAT = process2.env.GEMINI_PREFERRED_FORMAT === "0" ? false : true;
51
- }
52
- });
53
-
54
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/json.js
55
- import { jsonrepair as jsonrepair2 } from "jsonrepair";
56
- var init_json = __esm({
57
- "__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/json.js"() {
58
- }
59
- });
60
-
61
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/provider.js
62
- function sanitizePropertyKey(name) {
63
- return name.replace(/[@.,/\\:;!?#$%^&*()[\]{}]/g, "_").substring(0, 64);
64
- }
65
- var createGoogleCompatibleJSONSchema;
66
- var init_provider = __esm({
67
- "__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/provider.js"() {
68
- init_config();
69
- init_json();
70
- createGoogleCompatibleJSONSchema = (schema) => {
71
- if (!GEMINI_PREFERRED_FORMAT) {
72
- return schema;
73
- }
74
- const { oneOf: _oneOf, allOf: _allOf, anyOf: _anyOf, ...cleanSchema } = schema;
75
- const removeAdditionalProperties = (obj) => {
76
- if (Array.isArray(obj)) {
77
- return obj.map(removeAdditionalProperties);
78
- }
79
- if (obj && typeof obj === "object") {
80
- const result = {};
81
- for (const [key, value] of Object.entries(obj)) {
82
- if (key !== "additionalProperties") {
83
- result[key] = removeAdditionalProperties(value);
84
- }
85
- }
86
- return result;
87
- }
88
- return obj;
89
- };
90
- return removeAdditionalProperties(cleanSchema);
91
- };
92
- }
93
- });
94
-
95
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/logger.js
96
- function createLogger(name, server2) {
97
- return new MCPLogger(name, server2);
98
- }
99
- var LOG_LEVELS, MCPLogger, logger;
100
- var init_logger = __esm({
101
- "__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/logger.js"() {
102
- LOG_LEVELS = {
103
- debug: 0,
104
- info: 1,
105
- notice: 2,
106
- warning: 3,
107
- error: 4,
108
- critical: 5,
109
- alert: 6,
110
- emergency: 7
111
- };
112
- MCPLogger = class _MCPLogger {
113
- server;
114
- loggerName;
115
- minLevel = "debug";
116
- constructor(loggerName = "mcpc", server2) {
117
- this.loggerName = loggerName;
118
- this.server = server2;
119
- }
120
- setServer(server2) {
121
- this.server = server2;
122
- }
123
- setLevel(level) {
124
- this.minLevel = level;
125
- }
126
- async log(level, data) {
127
- if (LOG_LEVELS[level] < LOG_LEVELS[this.minLevel]) {
128
- return;
129
- }
130
- this.logToConsole(level, data);
131
- if (this.server) {
132
- try {
133
- await this.server.sendLoggingMessage({
134
- level,
135
- logger: this.loggerName,
136
- data
137
- });
138
- } catch {
139
- }
140
- }
141
- }
142
- logToConsole(level, data) {
143
- const message = typeof data === "string" ? data : JSON.stringify(data);
144
- const prefix = `[${this.loggerName}:${level}]`;
145
- console.error(prefix, message);
146
- }
147
- debug(data) {
148
- return this.log("debug", data);
149
- }
150
- info(data) {
151
- return this.log("info", data);
152
- }
153
- notice(data) {
154
- return this.log("notice", data);
155
- }
156
- warning(data) {
157
- return this.log("warning", data);
158
- }
159
- error(data) {
160
- return this.log("error", data);
161
- }
162
- critical(data) {
163
- return this.log("critical", data);
164
- }
165
- alert(data) {
166
- return this.log("alert", data);
167
- }
168
- emergency(data) {
169
- return this.log("emergency", data);
170
- }
171
- child(name) {
172
- const child = new _MCPLogger(`${this.loggerName}.${name}`, this.server);
173
- child.setLevel(this.minLevel);
174
- return child;
175
- }
176
- };
177
- logger = new MCPLogger("mcpc");
178
- }
179
- });
180
-
181
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/config-plugin.js
182
- var createConfigPlugin, config_plugin_default;
183
- var init_config_plugin = __esm({
184
- "__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/config-plugin.js"() {
185
- createConfigPlugin = () => ({
186
- name: "built-in-config",
187
- version: "1.0.0",
188
- enforce: "pre",
189
- transformTool: (tool, context2) => {
190
- const server2 = context2.server;
191
- const config2 = server2.findToolConfig?.(context2.toolName);
192
- if (config2?.description) {
193
- tool.description = config2.description;
194
- }
195
- return tool;
196
- }
197
- });
198
- config_plugin_default = createConfigPlugin();
199
- }
200
- });
201
-
202
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/tool-name-mapping-plugin.js
203
- var createToolNameMappingPlugin, tool_name_mapping_plugin_default;
204
- var init_tool_name_mapping_plugin = __esm({
205
- "__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/tool-name-mapping-plugin.js"() {
206
- createToolNameMappingPlugin = () => ({
207
- name: "built-in-tool-name-mapping",
208
- version: "1.0.0",
209
- enforce: "pre",
210
- transformTool: (tool, context2) => {
211
- const server2 = context2.server;
212
- const toolName = context2.toolName;
213
- const originalName = tool._originalName || toolName;
214
- const dotNotation = originalName.replace(/_/g, ".");
215
- const underscoreNotation = originalName.replace(/\./g, "_");
216
- if (dotNotation !== originalName && server2.toolNameMapping) {
217
- server2.toolNameMapping.set(dotNotation, toolName);
218
- }
219
- if (underscoreNotation !== originalName && server2.toolNameMapping) {
220
- server2.toolNameMapping.set(underscoreNotation, toolName);
221
- }
222
- if (originalName !== toolName && server2.toolNameMapping) {
223
- server2.toolNameMapping.set(originalName, toolName);
224
- }
225
- return tool;
226
- }
227
- });
228
- tool_name_mapping_plugin_default = createToolNameMappingPlugin();
229
- }
230
- });
231
-
232
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/logging-plugin.js
233
- var createLoggingPlugin, logging_plugin_default;
234
- var init_logging_plugin = __esm({
235
- "__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/logging-plugin.js"() {
236
- init_logger();
237
- createLoggingPlugin = (options = {}) => {
238
- const { enabled = true, verbose = false, compact: compact2 = true } = options;
239
- return {
240
- name: "built-in-logging",
241
- version: "1.0.0",
242
- composeEnd: async (context2) => {
243
- if (!enabled) return;
244
- const logger2 = createLogger("mcpc.plugin.logging", context2.server);
245
- if (compact2) {
246
- const pluginCount = context2.pluginNames.length;
247
- const { stats } = context2;
248
- await logger2.info(`[${context2.toolName}] ${pluginCount} plugins \u2022 ${stats.publicTools} public \u2022 ${stats.hiddenTools} hidden`);
249
- } else if (verbose) {
250
- await logger2.info(`[${context2.toolName}] Composition complete`);
251
- await logger2.info(` \u251C\u2500 Plugins: ${context2.pluginNames.join(", ")}`);
252
- const { stats } = context2;
253
- const server2 = context2.server;
254
- const publicTools = Array.from(new Set(server2.getPublicToolNames().map(String)));
255
- const internalTools = Array.from(new Set(server2.getInternalToolNames().map(String)));
256
- const hiddenTools = Array.from(new Set(server2.getHiddenToolNames().map(String)));
257
- const normalInternal = internalTools.filter((name) => !hiddenTools.includes(name));
258
- if (publicTools.length > 0) {
259
- await logger2.info(` \u251C\u2500 Public: ${publicTools.join(", ")}`);
260
- }
261
- if (internalTools.length > 0) {
262
- const parts = [];
263
- if (normalInternal.length > 0) {
264
- parts.push(normalInternal.join(", "));
265
- }
266
- if (hiddenTools.length > 0) {
267
- parts.push(`(${hiddenTools.join(", ")})`);
268
- }
269
- await logger2.info(` \u251C\u2500 Internal: ${parts.join(", ")}`);
270
- }
271
- await logger2.info(` \u2514\u2500 Total: ${stats.totalTools} tools`);
272
- }
273
- }
274
- };
275
- };
276
- logging_plugin_default = createLoggingPlugin({
277
- verbose: true,
278
- compact: false
279
- });
280
- }
281
- });
282
-
283
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/index.js
284
- var built_in_exports = {};
285
- __export(built_in_exports, {
286
- createConfigPlugin: () => createConfigPlugin,
287
- createLoggingPlugin: () => createLoggingPlugin,
288
- createToolNameMappingPlugin: () => createToolNameMappingPlugin,
289
- getBuiltInPlugins: () => getBuiltInPlugins
290
- });
291
- function getBuiltInPlugins() {
292
- return [
293
- tool_name_mapping_plugin_default,
294
- config_plugin_default,
295
- logging_plugin_default
296
- ];
297
- }
298
- var init_built_in = __esm({
299
- "__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/index.js"() {
300
- init_config_plugin();
301
- init_tool_name_mapping_plugin();
302
- init_logging_plugin();
303
- init_config_plugin();
304
- init_tool_name_mapping_plugin();
305
- init_logging_plugin();
306
- }
307
- });
308
-
309
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/schema.js
310
- import traverse from "json-schema-traverse";
311
- function updateRefPaths(schema, wrapperPath) {
312
- if (!schema || typeof schema !== "object") {
313
- return schema;
314
- }
315
- if (!wrapperPath || typeof wrapperPath !== "string") {
316
- throw new Error("wrapperPath must be a non-empty string");
317
- }
318
- const clonedSchema = JSON.parse(JSON.stringify(schema));
319
- try {
320
- traverse(clonedSchema, {
321
- allKeys: true,
322
- cb: function(schemaNode, _jsonPtr, _rootSchema, _parentJsonPtr, _parentKeyword, _parentSchema, _keyIndex) {
323
- if (schemaNode && typeof schemaNode === "object" && schemaNode.$ref) {
324
- const ref = schemaNode.$ref;
325
- if (ref.startsWith("#/properties/")) {
326
- const relativePath = ref.substring(13);
327
- schemaNode.$ref = `#/properties/${wrapperPath}/properties/${relativePath}`;
328
- } else if (ref === "#") {
329
- schemaNode.$ref = `#/properties/${wrapperPath}`;
330
- }
331
- }
332
- }
333
- });
334
- } catch (error) {
335
- console.warn(`Failed to traverse schema for path "${wrapperPath}":`, error);
336
- return clonedSchema;
337
- }
338
- return clonedSchema;
339
- }
340
- var init_schema2 = __esm({
341
- "__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/schema.js"() {
342
- }
343
- });
344
-
345
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/compose-helpers.js
346
- var compose_helpers_exports = {};
347
- __export(compose_helpers_exports, {
348
- buildDependencyGroups: () => buildDependencyGroups,
349
- processToolsWithPlugins: () => processToolsWithPlugins,
350
- registerGlobalTools: () => registerGlobalTools
351
- });
352
- async function processToolsWithPlugins(server2, externalTools, mode) {
353
- const toolManager = server2.toolManager;
354
- const pluginManager = server2.pluginManager;
355
- for (const [toolId, toolData] of toolManager.getToolEntries()) {
356
- const defaultSchema = {
357
- type: "object",
358
- properties: {},
359
- additionalProperties: true
360
- };
361
- const tempTool = {
362
- name: toolId,
363
- description: toolData.description,
364
- inputSchema: toolData.schema || defaultSchema,
365
- execute: toolData.callback
366
- };
367
- const processedTool = await pluginManager.applyTransformToolHooks(tempTool, {
368
- toolName: toolId,
369
- server: server2,
370
- mode,
371
- originalTool: {
372
- ...tempTool
373
- },
374
- transformationIndex: 0
375
- });
376
- toolManager.registerTool(toolId, processedTool.description || toolData.description, processedTool.inputSchema, processedTool.execute);
377
- if (externalTools[toolId]) {
378
- try {
379
- const builtIn = await Promise.resolve().then(() => (init_built_in(), built_in_exports));
380
- if (builtIn && typeof builtIn.processToolVisibility === "function") {
381
- builtIn.processToolVisibility(toolId, processedTool, server2, externalTools);
382
- }
383
- } catch {
384
- }
385
- externalTools[toolId] = processedTool;
386
- }
387
- }
388
- }
389
- function buildDependencyGroups(toolNameToDetailList, hiddenToolNames, publicToolNames, server2) {
390
- const depGroups = {};
391
- const toolManager = server2.toolManager;
392
- toolNameToDetailList.forEach(([toolName, tool]) => {
393
- const resolvedName = toolManager.resolveToolName(toolName);
394
- if (hiddenToolNames.includes(resolvedName ?? "") || publicToolNames.includes(resolvedName ?? "")) {
395
- return;
396
- }
397
- if (!tool) {
398
- const allToolNames = [
399
- ...toolNameToDetailList.map(([n]) => n)
400
- ];
401
- throw new Error(`Action ${toolName} not found, available action list: ${allToolNames.join(", ")}`);
402
- }
403
- const baseSchema = tool.inputSchema.jsonSchema ?? tool.inputSchema ?? {
404
- type: "object",
405
- properties: {},
406
- required: []
407
- };
408
- const baseProperties = baseSchema.type === "object" && baseSchema.properties ? baseSchema.properties : {};
409
- const baseRequired = baseSchema.type === "object" && Array.isArray(baseSchema.required) ? baseSchema.required : [];
410
- const updatedProperties = updateRefPaths(baseProperties, toolName);
411
- const sanitizedKey = sanitizePropertyKey(toolName);
412
- depGroups[sanitizedKey] = {
413
- type: "object",
414
- description: tool.description,
415
- properties: updatedProperties,
416
- required: [
417
- ...baseRequired
418
- ],
419
- additionalProperties: false
420
- };
421
- });
422
- return depGroups;
423
- }
424
- function registerGlobalTools(globalToolNames, tools, server2) {
425
- globalToolNames.forEach((toolId) => {
426
- const tool = tools[toolId];
427
- if (!tool) {
428
- throw new Error(`Global tool ${toolId} not found in registry, available: ${Object.keys(tools).join(", ")}`);
429
- }
430
- server2.tool(toolId, tool.description || "No description available", jsonSchema(tool.inputSchema), tool.execute);
431
- });
432
- }
433
- var init_compose_helpers = __esm({
434
- "__mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/compose-helpers.js"() {
435
- init_schema2();
436
- init_schema();
437
- init_provider();
438
- }
439
- });
440
4
 
441
5
  // __mcpc__cli_latest/node_modules/@mcpc/cli/src/bin.ts
442
6
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
@@ -493,32 +57,59 @@ var ServerSentEventStream = class extends TransformStream {
493
57
  import { createRoute as createRoute2, z as z2 } from "@hono/zod-openapi";
494
58
 
495
59
  // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/compose.js
496
- init_schema();
497
60
  import { CallToolRequestSchema, ListToolsRequestSchema, SetLevelRequestSchema } from "@modelcontextprotocol/sdk/types.js";
498
- import { Server } from "@modelcontextprotocol/sdk/server/index.js";
499
61
 
500
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__utils/src/json.js
501
- import { jsonrepair } from "jsonrepair";
502
- function stripMarkdownAndText(text) {
503
- text = text.trim();
504
- text = text.replace(/^```(?:json)?\s*\n?/i, "");
505
- text = text.replace(/\n?```\s*$/, "");
506
- text = text.replace(/^(?:here is|here's|response|result|output|json):\s*/i, "");
507
- const firstJsonIndex = text.search(/[\{\[]/);
508
- if (firstJsonIndex >= 0) {
509
- text = text.slice(firstJsonIndex);
510
- let depth = 0;
511
- let inString = false;
512
- let escapeNext = false;
513
- const startChar = text[0];
514
- const endChar = startChar === "{" ? "}" : "]";
515
- for (let i = 0; i < text.length; i++) {
516
- const char = text[i];
517
- if (escapeNext) {
518
- escapeNext = false;
519
- continue;
520
- }
521
- if (char === "\\") {
62
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/schema.js
63
+ var schemaSymbol = Symbol.for("mcpc.schema");
64
+ var vercelSchemaSymbol = Symbol.for("vercel.ai.schema");
65
+ var validatorSymbol = Symbol.for("mcpc.validator");
66
+ function jsonSchema(schema, options = {}) {
67
+ if (isWrappedSchema(schema)) {
68
+ return schema;
69
+ }
70
+ return {
71
+ [schemaSymbol]: true,
72
+ [validatorSymbol]: true,
73
+ _type: void 0,
74
+ jsonSchema: schema,
75
+ validate: options.validate
76
+ };
77
+ }
78
+ function isWrappedSchema(value) {
79
+ return typeof value === "object" && value !== null && (schemaSymbol in value && value[schemaSymbol] === true || vercelSchemaSymbol in value && value[vercelSchemaSymbol] === true);
80
+ }
81
+ function extractJsonSchema(schema) {
82
+ if (isWrappedSchema(schema)) {
83
+ return schema.jsonSchema;
84
+ }
85
+ return schema;
86
+ }
87
+
88
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/compose.js
89
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
90
+
91
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__utils/src/json.js
92
+ import { jsonrepair } from "jsonrepair";
93
+ function stripMarkdownAndText(text) {
94
+ text = text.trim();
95
+ text = text.replace(/^```(?:json)?\s*\n?/i, "");
96
+ text = text.replace(/\n?```\s*$/, "");
97
+ text = text.replace(/^(?:here is|here's|response|result|output|json):\s*/i, "");
98
+ const firstJsonIndex = text.search(/[\{\[]/);
99
+ if (firstJsonIndex >= 0) {
100
+ text = text.slice(firstJsonIndex);
101
+ let depth = 0;
102
+ let inString = false;
103
+ let escapeNext = false;
104
+ const startChar = text[0];
105
+ const endChar = startChar === "{" ? "}" : "]";
106
+ for (let i = 0; i < text.length; i++) {
107
+ const char = text[i];
108
+ if (escapeNext) {
109
+ escapeNext = false;
110
+ continue;
111
+ }
112
+ if (char === "\\") {
522
113
  escapeNext = true;
523
114
  continue;
524
115
  }
@@ -652,8 +243,41 @@ function smitheryToolNameCompatibale(name, scope) {
652
243
  };
653
244
  }
654
245
 
246
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/config.js
247
+ import process2 from "node:process";
248
+ var GEMINI_PREFERRED_FORMAT = process2.env.GEMINI_PREFERRED_FORMAT === "0" ? false : true;
249
+
250
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/json.js
251
+ import { jsonrepair as jsonrepair2 } from "jsonrepair";
252
+
253
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/provider.js
254
+ function sanitizePropertyKey(name) {
255
+ return name.replace(/[@.,/\\:;!?#$%^&*()[\]{}]/g, "_").substring(0, 64);
256
+ }
257
+ var createGoogleCompatibleJSONSchema = (schema) => {
258
+ if (!GEMINI_PREFERRED_FORMAT) {
259
+ return schema;
260
+ }
261
+ const { oneOf: _oneOf, allOf: _allOf, anyOf: _anyOf, ...cleanSchema } = schema;
262
+ const removeAdditionalProperties = (obj) => {
263
+ if (Array.isArray(obj)) {
264
+ return obj.map(removeAdditionalProperties);
265
+ }
266
+ if (obj && typeof obj === "object") {
267
+ const result = {};
268
+ for (const [key, value] of Object.entries(obj)) {
269
+ if (key !== "additionalProperties") {
270
+ result[key] = removeAdditionalProperties(value);
271
+ }
272
+ }
273
+ return result;
274
+ }
275
+ return obj;
276
+ };
277
+ return removeAdditionalProperties(cleanSchema);
278
+ };
279
+
655
280
  // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/mcp.js
656
- init_provider();
657
281
  import { cwd } from "node:process";
658
282
  import process3 from "node:process";
659
283
  import { createHash } from "node:crypto";
@@ -839,16 +463,215 @@ async function composeMcpDepTools(mcpConfig, filterIn) {
839
463
  };
840
464
  }
841
465
 
842
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/agentic/agentic-tool-registrar.js
843
- init_schema();
844
- init_provider();
466
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/tool-tag-processor.js
467
+ var ALL_TOOLS_PLACEHOLDER = "__ALL__";
468
+ function findToolId(toolName, tools, toolNameMapping) {
469
+ const mappedId = toolNameMapping?.get(toolName);
470
+ if (mappedId) {
471
+ return mappedId;
472
+ }
473
+ return Object.keys(tools).find((id) => {
474
+ const dotNotation = id.replace(/_/g, ".");
475
+ return toolName === id || toolName === dotNotation;
476
+ });
477
+ }
478
+ function processToolTags({ description, tagToResults, $, tools, toolOverrides, toolNameMapping }) {
479
+ tagToResults.tool.forEach((toolEl) => {
480
+ const toolName = toolEl.attribs.name;
481
+ if (!toolName || toolName.includes(ALL_TOOLS_PLACEHOLDER)) {
482
+ $(toolEl).remove();
483
+ return;
484
+ }
485
+ const override = toolOverrides.get(toolName);
486
+ if (override?.visibility?.hidden) {
487
+ $(toolEl).remove();
488
+ } else if (override?.visibility?.public) {
489
+ $(toolEl).replaceWith(`<tool name="${toolName}"/>`);
490
+ } else {
491
+ const toolId = findToolId(toolName, tools, toolNameMapping);
492
+ if (toolId) {
493
+ $(toolEl).replaceWith(`<tool name="${toolId}"/>`);
494
+ } else {
495
+ $(toolEl).remove();
496
+ }
497
+ }
498
+ });
499
+ return $.root().html() ?? description;
500
+ }
501
+
502
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/config-plugin.js
503
+ var createConfigPlugin = () => ({
504
+ name: "built-in-config",
505
+ version: "1.0.0",
506
+ enforce: "pre",
507
+ transformTool: (tool, context2) => {
508
+ const server2 = context2.server;
509
+ const config2 = server2.findToolConfig?.(context2.toolName);
510
+ if (config2?.description) {
511
+ tool.description = config2.description;
512
+ }
513
+ return tool;
514
+ }
515
+ });
516
+ var config_plugin_default = createConfigPlugin();
517
+
518
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/tool-name-mapping-plugin.js
519
+ var createToolNameMappingPlugin = () => ({
520
+ name: "built-in-tool-name-mapping",
521
+ version: "1.0.0",
522
+ enforce: "pre",
523
+ transformTool: (tool, context2) => {
524
+ const server2 = context2.server;
525
+ const toolName = context2.toolName;
526
+ const originalName = tool._originalName || toolName;
527
+ const dotNotation = originalName.replace(/_/g, ".");
528
+ const underscoreNotation = originalName.replace(/\./g, "_");
529
+ if (dotNotation !== originalName && server2.toolNameMapping) {
530
+ server2.toolNameMapping.set(dotNotation, toolName);
531
+ }
532
+ if (underscoreNotation !== originalName && server2.toolNameMapping) {
533
+ server2.toolNameMapping.set(underscoreNotation, toolName);
534
+ }
535
+ if (originalName !== toolName && server2.toolNameMapping) {
536
+ server2.toolNameMapping.set(originalName, toolName);
537
+ }
538
+ return tool;
539
+ }
540
+ });
541
+ var tool_name_mapping_plugin_default = createToolNameMappingPlugin();
542
+
543
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/logger.js
544
+ var LOG_LEVELS = {
545
+ debug: 0,
546
+ info: 1,
547
+ notice: 2,
548
+ warning: 3,
549
+ error: 4,
550
+ critical: 5,
551
+ alert: 6,
552
+ emergency: 7
553
+ };
554
+ var MCPLogger = class _MCPLogger {
555
+ server;
556
+ loggerName;
557
+ minLevel = "debug";
558
+ constructor(loggerName = "mcpc", server2) {
559
+ this.loggerName = loggerName;
560
+ this.server = server2;
561
+ }
562
+ setServer(server2) {
563
+ this.server = server2;
564
+ }
565
+ setLevel(level) {
566
+ this.minLevel = level;
567
+ }
568
+ async log(level, data) {
569
+ if (LOG_LEVELS[level] < LOG_LEVELS[this.minLevel]) {
570
+ return;
571
+ }
572
+ this.logToConsole(level, data);
573
+ if (this.server) {
574
+ try {
575
+ await this.server.sendLoggingMessage({
576
+ level,
577
+ logger: this.loggerName,
578
+ data
579
+ });
580
+ } catch {
581
+ }
582
+ }
583
+ }
584
+ logToConsole(level, data) {
585
+ const message = typeof data === "string" ? data : JSON.stringify(data);
586
+ const prefix = `[${this.loggerName}:${level}]`;
587
+ console.error(prefix, message);
588
+ }
589
+ debug(data) {
590
+ return this.log("debug", data);
591
+ }
592
+ info(data) {
593
+ return this.log("info", data);
594
+ }
595
+ notice(data) {
596
+ return this.log("notice", data);
597
+ }
598
+ warning(data) {
599
+ return this.log("warning", data);
600
+ }
601
+ error(data) {
602
+ return this.log("error", data);
603
+ }
604
+ critical(data) {
605
+ return this.log("critical", data);
606
+ }
607
+ alert(data) {
608
+ return this.log("alert", data);
609
+ }
610
+ emergency(data) {
611
+ return this.log("emergency", data);
612
+ }
613
+ child(name) {
614
+ const child = new _MCPLogger(`${this.loggerName}.${name}`, this.server);
615
+ child.setLevel(this.minLevel);
616
+ return child;
617
+ }
618
+ };
619
+ var logger = new MCPLogger("mcpc");
620
+ function createLogger(name, server2) {
621
+ return new MCPLogger(name, server2);
622
+ }
623
+
624
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/logging-plugin.js
625
+ var createLoggingPlugin = (options = {}) => {
626
+ const { enabled = true, verbose = false, compact: compact2 = true } = options;
627
+ return {
628
+ name: "built-in-logging",
629
+ version: "1.0.0",
630
+ composeEnd: async (context2) => {
631
+ if (!enabled) return;
632
+ const logger2 = createLogger("mcpc.plugin.logging", context2.server);
633
+ if (compact2) {
634
+ const pluginCount = context2.pluginNames.length;
635
+ const { stats } = context2;
636
+ await logger2.info(`[${context2.toolName}] ${pluginCount} plugins \u2022 ${stats.publicTools} public \u2022 ${stats.hiddenTools} hidden`);
637
+ } else if (verbose) {
638
+ await logger2.info(`[${context2.toolName}] Composition complete`);
639
+ await logger2.info(` \u251C\u2500 Plugins: ${context2.pluginNames.join(", ")}`);
640
+ const { stats } = context2;
641
+ const server2 = context2.server;
642
+ const publicTools = Array.from(new Set(server2.getPublicToolNames().map(String)));
643
+ const internalTools = Array.from(new Set(server2.getInternalToolNames().map(String)));
644
+ const hiddenTools = Array.from(new Set(server2.getHiddenToolNames().map(String)));
645
+ const normalInternal = internalTools.filter((name) => !hiddenTools.includes(name));
646
+ if (publicTools.length > 0) {
647
+ await logger2.info(` \u251C\u2500 Public: ${publicTools.join(", ")}`);
648
+ }
649
+ if (internalTools.length > 0) {
650
+ const parts = [];
651
+ if (normalInternal.length > 0) {
652
+ parts.push(normalInternal.join(", "));
653
+ }
654
+ if (hiddenTools.length > 0) {
655
+ parts.push(`(${hiddenTools.join(", ")})`);
656
+ }
657
+ await logger2.info(` \u251C\u2500 Internal: ${parts.join(", ")}`);
658
+ }
659
+ await logger2.info(` \u2514\u2500 Total: ${stats.totalTools} tools`);
660
+ }
661
+ }
662
+ };
663
+ };
664
+ var logging_plugin_default = createLoggingPlugin({
665
+ verbose: true,
666
+ compact: false
667
+ });
845
668
 
846
669
  // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/prompts/index.js
847
670
  var SystemPrompts = {
848
671
  /**
849
672
  * Base system prompt for autonomous MCP execution
850
673
  */
851
- AUTONOMOUS_EXECUTION: `Agentic tool \`{toolName}\` that executes complex tasks by iteratively calling actions, gathering results, and deciding next steps until completion. Use this tool when the task matches the manual below.
674
+ AUTONOMOUS_EXECUTION: `Agentic tool \`{toolName}\` that executes complex tasks by iteratively selecting and calling tools, gathering results, and continuing until completion. Use this tool when the task matches the manual below.
852
675
 
853
676
  You must follow the <manual/>, obey the <execution_rules/>, and use the <call_format/>.
854
677
 
@@ -856,31 +679,39 @@ You must follow the <manual/>, obey the <execution_rules/>, and use the <call_fo
856
679
  {description}
857
680
  </manual>
858
681
 
682
+ <parameters>
683
+ \`useTool\` - Which tool to execute this iteration
684
+ \`hasDefinitions\` - Tool names whose schemas you already have
685
+ \`definitionsOf\` - Tool names whose schemas you need
686
+ </parameters>
687
+
859
688
  <execution_rules>
860
- 1. **Execute** one action per call
861
- 2. **Collect** feedback from each action result
862
- 3. **Decide** next step based on feedback:
863
- - **proceed**: More work needed
864
- - **complete**: Task finished (omit action field)
865
- - **retry**: Current action failed
866
- 4. **Provide** parameters matching the action name
867
- 5. **Continue** until task is complete
868
- 6. Note: You are an agent exposed as an MCP tool - **"action" is an internal parameter, NOT an external MCP tool you can call**
689
+ 1. **First call**: No tool definitions available\u2014you must request them via \`definitionsOf\`
690
+ 2. **When executing tools**: Must provide \`hasDefinitions\` with ALL tools you have schemas for (avoid duplicate requests and reduce tokens)
691
+ 3. **When requesting definitions**: Use \`definitionsOf\` to request tool schemas you need
692
+ 4. **Both together**: Execute tool AND request new definitions in one call for efficiency
693
+ 5. **Never request definitions you already have**
694
+ 6. **Select** one tool to execute per call using \`useTool\`
695
+ 7. **Provide** parameters matching the selected tool name
696
+ 8. Note: You are an agent exposed as an MCP tool - **\`useTool\` is an internal parameter for choosing which tool to execute, NOT an external MCP tool you can call**
869
697
  </execution_rules>
870
698
 
871
699
  <call_format>
700
+ Initial definition request:
872
701
  \`\`\`json
873
702
  {
874
- "action": "action_name",
875
- "decision": "proceed|retry",
876
- "action_name": { /* action parameters */ }
703
+ "hasDefinitions": [],
704
+ "definitionsOf": ["tool1", "tool2"]
877
705
  }
878
706
  \`\`\`
879
707
 
880
- When complete:
708
+ Execute tool + get new definitions:
881
709
  \`\`\`json
882
710
  {
883
- "decision": "complete"
711
+ "useTool": "tool1",
712
+ "tool1": { /* parameters */ },
713
+ "hasDefinitions": ["tool1", "tool2"],
714
+ "definitionsOf": ["tool3"]
884
715
  }
885
716
  \`\`\`
886
717
  </call_format>`,
@@ -1179,11 +1010,28 @@ ${JSON.stringify(steps, null, 2)}`;
1179
1010
  }
1180
1011
  };
1181
1012
 
1182
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/agentic/agentic-executor.js
1013
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/schema-validator.js
1183
1014
  import { Ajv } from "ajv";
1184
- import { AggregateAjvError } from "@segment/ajv-human-errors";
1185
1015
  import addFormats from "ajv-formats";
1186
- init_logger();
1016
+ import { AggregateAjvError } from "@segment/ajv-human-errors";
1017
+ var ajv = new Ajv({
1018
+ allErrors: true,
1019
+ verbose: true
1020
+ });
1021
+ addFormats.default(ajv);
1022
+ function validateSchema(args, schema) {
1023
+ const validate = ajv.compile(schema);
1024
+ if (!validate(args)) {
1025
+ const errors = new AggregateAjvError(validate.errors);
1026
+ return {
1027
+ valid: false,
1028
+ error: errors.message
1029
+ };
1030
+ }
1031
+ return {
1032
+ valid: true
1033
+ };
1034
+ }
1187
1035
 
1188
1036
  // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/tracing.js
1189
1037
  import { context, SpanStatusCode, trace } from "@opentelemetry/api";
@@ -1254,27 +1102,20 @@ function endSpan(span, error) {
1254
1102
 
1255
1103
  // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/agentic/agentic-executor.js
1256
1104
  import process4 from "node:process";
1257
- var ajv = new Ajv({
1258
- allErrors: true,
1259
- verbose: true
1260
- });
1261
- addFormats(ajv);
1262
1105
  var AgenticExecutor = class {
1263
1106
  name;
1264
1107
  allToolNames;
1265
1108
  toolNameToDetailList;
1266
1109
  server;
1267
- ACTION_KEY;
1268
- NEXT_ACTION_KEY;
1110
+ USE_TOOL_KEY;
1269
1111
  logger;
1270
1112
  tracingEnabled;
1271
- constructor(name, allToolNames, toolNameToDetailList, server2, ACTION_KEY = "action", NEXT_ACTION_KEY = "nextAction") {
1113
+ constructor(name, allToolNames, toolNameToDetailList, server2, USE_TOOL_KEY = "useTool") {
1272
1114
  this.name = name;
1273
1115
  this.allToolNames = allToolNames;
1274
1116
  this.toolNameToDetailList = toolNameToDetailList;
1275
1117
  this.server = server2;
1276
- this.ACTION_KEY = ACTION_KEY;
1277
- this.NEXT_ACTION_KEY = NEXT_ACTION_KEY;
1118
+ this.USE_TOOL_KEY = USE_TOOL_KEY;
1278
1119
  this.tracingEnabled = false;
1279
1120
  this.logger = createLogger(`mcpc.agentic.${name}`, server2);
1280
1121
  try {
@@ -1294,8 +1135,7 @@ var AgenticExecutor = class {
1294
1135
  async execute(args, schema, parentSpan) {
1295
1136
  const executeSpan = this.tracingEnabled ? startSpan("mcpc.agentic_execute", {
1296
1137
  agent: this.name,
1297
- action: String(args[this.ACTION_KEY] ?? "unknown"),
1298
- nextAction: String(args[this.NEXT_ACTION_KEY] ?? "none"),
1138
+ selectTool: String(args[this.USE_TOOL_KEY] ?? "unknown"),
1299
1139
  args: JSON.stringify(args)
1300
1140
  }, parentSpan ?? void 0) : null;
1301
1141
  try {
@@ -1310,7 +1150,7 @@ var AgenticExecutor = class {
1310
1150
  }
1311
1151
  this.logger.warning({
1312
1152
  message: "Validation failed",
1313
- action: args[this.ACTION_KEY],
1153
+ selectTool: args[this.USE_TOOL_KEY],
1314
1154
  error: validationResult.error
1315
1155
  });
1316
1156
  return {
@@ -1325,103 +1165,67 @@ var AgenticExecutor = class {
1325
1165
  isError: true
1326
1166
  };
1327
1167
  }
1328
- const actionName = args[this.ACTION_KEY];
1329
- if (executeSpan && actionName) {
1168
+ const useTool = args[this.USE_TOOL_KEY];
1169
+ const definitionsOf = args.definitionsOf || [];
1170
+ const hasDefinitions = args.hasDefinitions || [];
1171
+ if (executeSpan && useTool) {
1330
1172
  try {
1331
- const safeAction = String(actionName).replace(/\s+/g, "_");
1173
+ const safeTool = String(useTool).replace(/\s+/g, "_");
1332
1174
  if (typeof executeSpan.updateName === "function") {
1333
- executeSpan.updateName(`mcpc.agentic_execute.${safeAction}`);
1175
+ executeSpan.updateName(`mcpc.agentic_execute.${safeTool}`);
1334
1176
  }
1335
1177
  } catch {
1336
1178
  }
1337
1179
  }
1338
- const currentTool = this.toolNameToDetailList.find(([name, _detail]) => name === actionName)?.[1];
1180
+ const currentTool = this.toolNameToDetailList.find(([name, _detail]) => name === useTool)?.[1];
1339
1181
  if (currentTool) {
1340
- const nextAction = args[this.NEXT_ACTION_KEY];
1341
1182
  if (executeSpan) {
1342
1183
  executeSpan.setAttributes({
1343
1184
  toolType: "external",
1344
- actionName,
1345
- nextAction: nextAction || "none"
1185
+ selectedTool: useTool
1346
1186
  });
1347
1187
  }
1348
1188
  this.logger.debug({
1349
1189
  message: "Executing external tool",
1350
- action: actionName,
1351
- nextAction
1190
+ selectTool: useTool
1352
1191
  });
1353
1192
  const currentResult = await currentTool.execute({
1354
- ...args[actionName]
1193
+ ...args[useTool]
1355
1194
  });
1356
- if (args[nextAction]) {
1357
- currentResult?.content?.push({
1358
- type: "text",
1359
- text: CompiledPrompts.actionSuccess({
1360
- toolName: this.name,
1361
- nextAction,
1362
- currentAction: actionName
1363
- })
1364
- });
1365
- } else {
1366
- currentResult?.content?.push({
1367
- type: "text",
1368
- text: CompiledPrompts.planningPrompt({
1369
- currentAction: actionName
1370
- })
1371
- });
1372
- }
1195
+ this.appendToolSchemas(currentResult, definitionsOf, hasDefinitions);
1373
1196
  if (executeSpan) {
1374
1197
  executeSpan.setAttributes({
1375
1198
  success: true,
1376
1199
  isError: !!currentResult.isError,
1377
1200
  resultContentLength: currentResult.content?.length || 0,
1378
- hasNextAction: !!args[nextAction],
1379
1201
  toolResult: JSON.stringify(currentResult)
1380
1202
  });
1381
1203
  endSpan(executeSpan);
1382
1204
  }
1383
1205
  return currentResult;
1384
1206
  }
1385
- if (this.allToolNames.includes(actionName)) {
1207
+ if (this.allToolNames.includes(useTool)) {
1386
1208
  if (executeSpan) {
1387
1209
  executeSpan.setAttributes({
1388
1210
  toolType: "internal",
1389
- actionName
1211
+ selectedTool: useTool
1390
1212
  });
1391
1213
  }
1392
1214
  this.logger.debug({
1393
1215
  message: "Executing internal tool",
1394
- action: actionName
1216
+ selectTool: useTool
1395
1217
  });
1396
1218
  try {
1397
- const result = await this.server.callTool(actionName, args[actionName]);
1398
- const nextAction = args[this.NEXT_ACTION_KEY];
1399
- const callToolResult = result ?? {
1219
+ const result2 = await this.server.callTool(useTool, args[useTool]);
1220
+ const callToolResult = result2 ?? {
1400
1221
  content: []
1401
1222
  };
1402
- if (nextAction && this.allToolNames.includes(nextAction)) {
1403
- callToolResult.content.push({
1404
- type: "text",
1405
- text: CompiledPrompts.actionSuccess({
1406
- toolName: this.name,
1407
- nextAction,
1408
- currentAction: actionName
1409
- })
1410
- });
1411
- } else {
1412
- callToolResult.content.push({
1413
- type: "text",
1414
- text: CompiledPrompts.planningPrompt({
1415
- currentAction: actionName
1416
- })
1417
- });
1418
- }
1223
+ this.appendToolSchemas(callToolResult, definitionsOf, hasDefinitions);
1419
1224
  if (executeSpan) {
1420
1225
  executeSpan.setAttributes({
1421
1226
  success: true,
1422
1227
  isError: !!callToolResult.isError,
1423
1228
  resultContentLength: callToolResult.content?.length || 0,
1424
- hasNextAction: !!(nextAction && this.allToolNames.includes(nextAction)),
1425
1229
  toolResult: JSON.stringify(callToolResult)
1426
1230
  });
1427
1231
  endSpan(executeSpan);
@@ -1433,14 +1237,14 @@ var AgenticExecutor = class {
1433
1237
  }
1434
1238
  this.logger.error({
1435
1239
  message: "Error executing internal tool",
1436
- action: actionName,
1240
+ useTool,
1437
1241
  error: String(error)
1438
1242
  });
1439
1243
  return {
1440
1244
  content: [
1441
1245
  {
1442
1246
  type: "text",
1443
- text: `Error executing internal tool ${actionName}: ${error instanceof Error ? error.message : String(error)}`
1247
+ text: `Error executing internal tool ${useTool}: ${error instanceof Error ? error.message : String(error)}`
1444
1248
  }
1445
1249
  ],
1446
1250
  isError: true
@@ -1450,23 +1254,20 @@ var AgenticExecutor = class {
1450
1254
  if (executeSpan) {
1451
1255
  executeSpan.setAttributes({
1452
1256
  toolType: "not_found",
1453
- actionName: actionName || "unknown",
1257
+ useTool: useTool || "unknown",
1454
1258
  completion: true
1455
1259
  });
1456
1260
  endSpan(executeSpan);
1457
1261
  }
1458
1262
  this.logger.debug({
1459
1263
  message: "Tool not found, returning completion message",
1460
- action: actionName
1264
+ useTool
1461
1265
  });
1462
- return {
1463
- content: [
1464
- {
1465
- type: "text",
1466
- text: CompiledPrompts.completionMessage()
1467
- }
1468
- ]
1266
+ const result = {
1267
+ content: []
1469
1268
  };
1269
+ this.appendToolSchemas(result, definitionsOf, hasDefinitions);
1270
+ return result;
1470
1271
  } catch (error) {
1471
1272
  if (executeSpan) {
1472
1273
  endSpan(executeSpan, error);
@@ -1486,24 +1287,33 @@ var AgenticExecutor = class {
1486
1287
  };
1487
1288
  }
1488
1289
  }
1489
- // Validate arguments using JSON schema
1490
- validate(args, schema) {
1491
- if (args.decision === "complete") {
1492
- return {
1493
- valid: true
1494
- };
1290
+ // Append tool schemas to result if requested
1291
+ appendToolSchemas(result, definitionsOf, hasDefinitions) {
1292
+ const schemasToProvide = definitionsOf.filter((toolName) => !hasDefinitions.includes(toolName));
1293
+ if (schemasToProvide.length === 0) {
1294
+ return;
1495
1295
  }
1496
- const validate = ajv.compile(schema);
1497
- if (!validate(args)) {
1498
- const errors = new AggregateAjvError(validate.errors);
1499
- return {
1500
- valid: false,
1501
- error: errors.message
1502
- };
1296
+ const definitionTexts = [];
1297
+ for (const toolName of schemasToProvide) {
1298
+ const toolDetail = this.toolNameToDetailList.find(([name]) => name === toolName);
1299
+ if (toolDetail) {
1300
+ const [name, schema] = toolDetail;
1301
+ const schemaJson = JSON.stringify(schema, null, 2);
1302
+ definitionTexts.push(`<tool_definition name="${name}">
1303
+ ${schemaJson}
1304
+ </tool_definition>`);
1305
+ }
1306
+ }
1307
+ if (definitionTexts.length > 0) {
1308
+ result.content.push({
1309
+ type: "text",
1310
+ text: `${definitionTexts.join("\n\n")}`
1311
+ });
1503
1312
  }
1504
- return {
1505
- valid: true
1506
- };
1313
+ }
1314
+ // Validate arguments using JSON schema
1315
+ validate(args, schema) {
1316
+ return validateSchema(args, schema);
1507
1317
  }
1508
1318
  };
1509
1319
 
@@ -1738,47 +1548,103 @@ Workflow step definitions - provide ONLY on initial call.
1738
1548
  ]
1739
1549
  };
1740
1550
  },
1741
- forAgentic: function(toolNameToDetailList, _sampling = false, ACTION_KEY = "action", NEXT_ACTION_KEY = "nextAction") {
1742
- const allOf = toolNameToDetailList.map(([toolName, _toolDetail]) => {
1743
- return {
1551
+ forAgentic: function(toolNameToDetailList, _sampling = false, USE_TOOL_KEY = "useTool") {
1552
+ const allOf = [
1553
+ // When hasDefinitions is empty, definitionsOf must be provided
1554
+ {
1744
1555
  if: {
1745
1556
  properties: {
1746
- [ACTION_KEY]: {
1747
- const: toolName
1557
+ hasDefinitions: {
1558
+ type: "array",
1559
+ maxItems: 0
1748
1560
  }
1749
1561
  },
1750
1562
  required: [
1751
- ACTION_KEY
1563
+ "hasDefinitions"
1752
1564
  ]
1753
1565
  },
1754
1566
  then: {
1755
1567
  required: [
1756
- toolName
1568
+ "definitionsOf"
1757
1569
  ]
1758
1570
  }
1759
- };
1760
- });
1761
- const actionDescription = `Specifies the action to be performed from the enum. **\u26A0\uFE0F When setting \`action: "example_action"\`, you MUST also provide \`"example_action": { ... }\`**`;
1571
+ },
1572
+ // When useTool is present, hasDefinitions must contain that tool
1573
+ ...toolNameToDetailList.map(([toolName, _toolDetail]) => {
1574
+ return {
1575
+ if: {
1576
+ properties: {
1577
+ [USE_TOOL_KEY]: {
1578
+ const: toolName
1579
+ }
1580
+ },
1581
+ required: [
1582
+ USE_TOOL_KEY
1583
+ ]
1584
+ },
1585
+ then: {
1586
+ properties: {
1587
+ hasDefinitions: {
1588
+ type: "array",
1589
+ contains: {
1590
+ const: toolName
1591
+ }
1592
+ }
1593
+ },
1594
+ required: [
1595
+ "hasDefinitions"
1596
+ ]
1597
+ }
1598
+ };
1599
+ }),
1600
+ // When a specific tool is selected, its parameters must be provided
1601
+ ...toolNameToDetailList.map(([toolName, _toolDetail]) => {
1602
+ return {
1603
+ if: {
1604
+ properties: {
1605
+ [USE_TOOL_KEY]: {
1606
+ const: toolName
1607
+ }
1608
+ },
1609
+ required: [
1610
+ USE_TOOL_KEY
1611
+ ]
1612
+ },
1613
+ then: {
1614
+ required: [
1615
+ toolName
1616
+ ]
1617
+ }
1618
+ };
1619
+ })
1620
+ ];
1621
+ const useToolDescription = `Specifies which tool to execute from the available options. **When setting \`useTool: "example_tool"\`, you MUST also provide \`"example_tool": { ...parameters }\` with that tool's parameters**`;
1622
+ const toolItems = allToolNames.length > 0 ? {
1623
+ type: "string",
1624
+ enum: allToolNames
1625
+ } : {
1626
+ type: "string"
1627
+ };
1762
1628
  const baseProperties = {
1763
- [ACTION_KEY]: {
1629
+ [USE_TOOL_KEY]: {
1764
1630
  type: "string",
1765
1631
  enum: allToolNames,
1766
- description: actionDescription
1632
+ description: useToolDescription
1767
1633
  },
1768
- [NEXT_ACTION_KEY]: {
1769
- type: "string",
1770
- enum: allToolNames,
1771
- description: "Optional: Specify the next action to execute. Only include this when you know additional actions are needed after the current one completes."
1634
+ hasDefinitions: {
1635
+ type: "array",
1636
+ items: toolItems,
1637
+ description: "Tool names whose schemas you already have. List all tools you have schemas for to avoid duplicate schema requests and reduce token usage."
1772
1638
  },
1773
- decision: this.decision(),
1774
- ...depGroups
1639
+ definitionsOf: {
1640
+ type: "array",
1641
+ items: toolItems,
1642
+ description: "Tool names whose schemas you need. Request tool schemas before calling them to understand their parameters."
1643
+ }
1775
1644
  };
1776
- const requiredFields = [
1777
- ACTION_KEY,
1778
- "decision"
1779
- ];
1645
+ const requiredFields = [];
1780
1646
  const schema = {
1781
- additionalProperties: false,
1647
+ additionalProperties: true,
1782
1648
  type: "object",
1783
1649
  properties: baseProperties,
1784
1650
  required: requiredFields
@@ -1829,1025 +1695,1082 @@ NOTE: The \`steps\` has been predefined` : `**You MUST execute this tool with fo
1829
1695
  };
1830
1696
  }
1831
1697
 
1832
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/sampling/base-sampling-executor.js
1833
- import { Ajv as Ajv2 } from "ajv";
1834
- import { AggregateAjvError as AggregateAjvError2 } from "@segment/ajv-human-errors";
1835
- import addFormats2 from "ajv-formats";
1836
- init_logger();
1837
- import process5 from "node:process";
1838
- var ajv2 = new Ajv2({
1839
- allErrors: true,
1840
- verbose: true
1841
- });
1842
- addFormats2(ajv2);
1843
- var BaseSamplingExecutor = class {
1844
- name;
1845
- description;
1846
- allToolNames;
1847
- toolNameToDetailList;
1848
- server;
1849
- conversationHistory;
1850
- maxIterations;
1851
- currentIteration;
1852
- logger;
1853
- tracingEnabled;
1854
- summarize;
1855
- constructor(name, description, allToolNames, toolNameToDetailList, server2, config2) {
1856
- this.name = name;
1857
- this.description = description;
1858
- this.allToolNames = allToolNames;
1859
- this.toolNameToDetailList = toolNameToDetailList;
1860
- this.server = server2;
1861
- this.conversationHistory = [];
1862
- this.maxIterations = 55;
1863
- this.currentIteration = 0;
1864
- this.tracingEnabled = false;
1865
- this.summarize = true;
1866
- if (config2?.maxIterations) {
1867
- this.maxIterations = config2.maxIterations;
1868
- }
1869
- if (config2?.summarize !== void 0) {
1870
- this.summarize = config2.summarize;
1871
- }
1872
- this.logger = createLogger(`mcpc.sampling.${name}`, server2);
1873
- try {
1874
- const tracingConfig = {
1875
- enabled: process5.env.MCPC_TRACING_ENABLED === "true",
1876
- serviceName: `mcpc-sampling-${name}`,
1877
- exportTo: process5.env.MCPC_TRACING_EXPORT ?? "otlp",
1878
- otlpEndpoint: process5.env.MCPC_TRACING_OTLP_ENDPOINT ?? "http://localhost:4318/v1/traces"
1879
- };
1880
- this.tracingEnabled = tracingConfig.enabled;
1881
- if (this.tracingEnabled) {
1882
- initializeTracing(tracingConfig);
1883
- }
1884
- } catch {
1885
- this.tracingEnabled = false;
1698
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/agentic/agentic-tool-registrar.js
1699
+ function registerAgenticTool(server2, { description, name, allToolNames, depGroups, toolNameToDetailList }) {
1700
+ const createArgsDef = createArgsDefFactory(name, allToolNames, depGroups, void 0, void 0);
1701
+ const agenticExecutor = new AgenticExecutor(name, allToolNames, toolNameToDetailList, server2);
1702
+ description = CompiledPrompts.autonomousExecution({
1703
+ toolName: name,
1704
+ description
1705
+ });
1706
+ const agenticArgsDef = createArgsDef.forAgentic(toolNameToDetailList, false);
1707
+ const argsDef = agenticArgsDef;
1708
+ const schema = allToolNames.length > 0 ? argsDef : {
1709
+ type: "object",
1710
+ properties: {}
1711
+ };
1712
+ server2.tool(name, description, jsonSchema(createGoogleCompatibleJSONSchema(schema)), async (args) => {
1713
+ return await agenticExecutor.execute(args, schema);
1714
+ });
1715
+ }
1716
+
1717
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/mode-agentic-plugin.js
1718
+ var createAgenticModePlugin = () => ({
1719
+ name: "mode-agentic",
1720
+ version: "1.0.0",
1721
+ // Only apply to agentic mode
1722
+ apply: "agentic",
1723
+ // Register the agent tool
1724
+ registerAgentTool: (context2) => {
1725
+ registerAgenticTool(context2.server, {
1726
+ description: context2.description,
1727
+ name: context2.name,
1728
+ allToolNames: context2.allToolNames,
1729
+ depGroups: context2.depGroups,
1730
+ toolNameToDetailList: context2.toolNameToDetailList
1731
+ });
1732
+ }
1733
+ });
1734
+ var mode_agentic_plugin_default = createAgenticModePlugin();
1735
+
1736
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/state.js
1737
+ var WorkflowState = class {
1738
+ currentStepIndex = -1;
1739
+ steps = [];
1740
+ stepStatuses = [];
1741
+ stepResults = [];
1742
+ stepErrors = [];
1743
+ isInitialized = false;
1744
+ isStarted = false;
1745
+ constructor(steps) {
1746
+ if (steps) {
1747
+ this.initialize(steps);
1886
1748
  }
1887
1749
  }
1888
- async runSamplingLoop(systemPrompt, schema, state) {
1889
- this.conversationHistory = [
1890
- {
1891
- role: "user",
1892
- content: {
1893
- type: "text",
1894
- text: 'Return ONE AND ONLY ONE raw JSON object (no code fences, explanations, or multiple objects). During execution provide: {"action":"<tool>","decision":"proceed|retry","<tool>":{}}. When complete provide: {"decision":"complete"}'
1895
- }
1896
- }
1897
- ];
1898
- const loopSpan = this.tracingEnabled ? startSpan("mcpc.sampling_loop", {
1899
- agent: this.name,
1900
- maxIterations: this.maxIterations,
1901
- systemPrompt: systemPrompt()
1902
- }) : null;
1903
- try {
1904
- for (this.currentIteration = 0; this.currentIteration < this.maxIterations; this.currentIteration++) {
1905
- let iterationSpan = null;
1906
- try {
1907
- const response = await this.server.createMessage({
1908
- systemPrompt: systemPrompt(),
1909
- messages: this.conversationHistory,
1910
- maxTokens: 55e3
1911
- });
1912
- const responseContent = response.content.text || "{}";
1913
- const model = response.model;
1914
- const stopReason = response.stopReason;
1915
- const role = response.role;
1916
- let parsedData;
1917
- try {
1918
- parsedData = parseJSON(responseContent.trim(), true);
1919
- } catch (parseError) {
1920
- iterationSpan = this.tracingEnabled ? startSpan("mcpc.sampling_iteration.parse_error", {
1921
- iteration: this.currentIteration + 1,
1922
- agent: this.name,
1923
- error: String(parseError),
1924
- maxIterations: this.maxIterations
1925
- }, loopSpan ?? void 0) : null;
1926
- this.addParsingErrorToHistory(responseContent, parseError);
1927
- if (iterationSpan) endSpan(iterationSpan);
1928
- continue;
1929
- }
1930
- this.conversationHistory.push({
1931
- role: "assistant",
1932
- content: {
1933
- type: "text",
1934
- text: JSON.stringify(parsedData, null, 2)
1935
- }
1936
- });
1937
- const action = parsedData["action"];
1938
- const decision = parsedData["decision"];
1939
- if (typeof decision !== "string") {
1940
- this.conversationHistory.push({
1941
- role: "user",
1942
- content: {
1943
- type: "text",
1944
- text: 'Missing required field "decision". Provide: {"action":"<tool>","decision":"proceed|retry","<tool>":{}} or {"decision":"complete"}'
1945
- }
1946
- });
1947
- if (iterationSpan) endSpan(iterationSpan);
1948
- continue;
1949
- }
1950
- if (decision === "complete" && action) {
1951
- this.conversationHistory.push({
1952
- role: "user",
1953
- content: {
1954
- type: "text",
1955
- text: 'Invalid: Cannot have both "decision":"complete" and "action" field. When complete, only provide {"decision":"complete"}.'
1956
- }
1957
- });
1958
- if (iterationSpan) endSpan(iterationSpan);
1959
- continue;
1960
- }
1961
- if (decision !== "complete" && !action) {
1962
- this.conversationHistory.push({
1963
- role: "user",
1964
- content: {
1965
- type: "text",
1966
- text: 'Missing required field "action". When executing, provide: {"action":"<tool>","decision":"proceed|retry","<tool>":{}}'
1967
- }
1968
- });
1969
- if (iterationSpan) endSpan(iterationSpan);
1970
- continue;
1971
- }
1972
- const actionStr = decision === "complete" ? "completion" : action && typeof action === "string" ? String(action) : "unknown_action";
1973
- const spanName = `mcpc.sampling_iteration.${actionStr}`;
1974
- iterationSpan = this.tracingEnabled ? startSpan(spanName, {
1975
- iteration: this.currentIteration + 1,
1976
- agent: this.name,
1977
- action: actionStr,
1978
- systemPrompt: systemPrompt(),
1979
- maxTokens: String(Number.MAX_SAFE_INTEGER),
1980
- maxIterations: this.maxIterations,
1981
- messages: JSON.stringify(this.conversationHistory)
1982
- }, loopSpan ?? void 0) : null;
1983
- const result = await this.processAction(parsedData, schema, state, iterationSpan);
1984
- this.logIterationProgress(parsedData, result, model, stopReason, role);
1985
- if (iterationSpan) {
1986
- let rawJson = "{}";
1987
- try {
1988
- rawJson = parsedData ? JSON.stringify(parsedData) : "{}";
1989
- } catch {
1990
- }
1991
- const attr = {
1992
- isError: !!result.isError,
1993
- isComplete: !!result.isComplete,
1994
- iteration: this.currentIteration + 1,
1995
- maxIterations: this.maxIterations,
1996
- parsed: rawJson,
1997
- action: typeof action === "string" ? action : String(action),
1998
- decision: typeof decision === "string" ? decision : String(decision),
1999
- samplingResponse: responseContent,
2000
- toolResult: JSON.stringify(result),
2001
- model,
2002
- role
2003
- };
2004
- if (stopReason) {
2005
- attr.stopReason = stopReason;
2006
- }
2007
- iterationSpan.setAttributes(attr);
2008
- }
2009
- if (result.isError) {
2010
- this.conversationHistory.push({
2011
- role: "user",
2012
- content: {
2013
- type: "text",
2014
- text: result.content[0].text
2015
- }
2016
- });
2017
- if (iterationSpan) endSpan(iterationSpan);
2018
- continue;
2019
- }
2020
- if (result.isComplete) {
2021
- if (iterationSpan) endSpan(iterationSpan);
2022
- if (loopSpan) endSpan(loopSpan);
2023
- return result;
2024
- }
2025
- if (iterationSpan) endSpan(iterationSpan);
2026
- } catch (iterError) {
2027
- if (iterationSpan) endSpan(iterationSpan, iterError);
2028
- throw iterError;
2029
- }
2030
- }
2031
- if (loopSpan) endSpan(loopSpan);
2032
- return await this.createMaxIterationsError(loopSpan);
2033
- } catch (error) {
2034
- if (loopSpan) endSpan(loopSpan, error);
2035
- return await this.createExecutionError(error, loopSpan);
1750
+ getCurrentStepIndex() {
1751
+ return this.currentStepIndex;
1752
+ }
1753
+ getSteps() {
1754
+ return this.steps;
1755
+ }
1756
+ isWorkflowInitialized() {
1757
+ return this.isInitialized;
1758
+ }
1759
+ getCurrentStep() {
1760
+ if (!this.isInitialized || this.currentStepIndex < 0) {
1761
+ return null;
2036
1762
  }
1763
+ return this.steps[this.currentStepIndex] || null;
2037
1764
  }
2038
- addParsingErrorToHistory(_responseText, parseError) {
2039
- const errorMsg = parseError instanceof Error ? parseError.message : String(parseError);
2040
- this.conversationHistory.push({
2041
- role: "user",
2042
- content: {
2043
- type: "text",
2044
- text: `Invalid JSON: ${errorMsg}
2045
-
2046
- Respond with valid JSON.`
2047
- }
2048
- });
1765
+ getNextStep() {
1766
+ if (!this.isInitialized) return null;
1767
+ const nextIndex = this.currentStepIndex + 1;
1768
+ return this.steps[nextIndex] || null;
2049
1769
  }
2050
- async createMaxIterationsError(parentSpan) {
2051
- const result = await this.createCompletionResult(`Reached max iterations (${this.maxIterations}). Try a more specific request.`, parentSpan);
2052
- result.isError = true;
2053
- result.isComplete = false;
2054
- return result;
1770
+ // Get the previous step in the workflow
1771
+ getPreviousStep() {
1772
+ if (!this.isInitialized) return null;
1773
+ const prevIndex = this.currentStepIndex - 1;
1774
+ return this.steps[prevIndex] || null;
2055
1775
  }
2056
- async createExecutionError(error, parentSpan) {
2057
- const result = await this.createCompletionResult(`Execution error: ${error instanceof Error ? error.message : String(error)}`, parentSpan);
2058
- result.isError = true;
2059
- result.isComplete = false;
2060
- return result;
1776
+ hasNextStep() {
1777
+ return this.getNextStep() !== null;
2061
1778
  }
2062
- async createCompletionResult(text, parentSpan) {
2063
- const summary = this.summarize ? await this.summarizeConversation(parentSpan) : this.formatConversation();
2064
- return {
2065
- content: [
2066
- {
2067
- type: "text",
2068
- text: `${text}
2069
-
2070
- **Execution Summary:**
2071
- - Iterations used: ${this.currentIteration + 1}/${this.maxIterations}
2072
- - Agent: ${this.name}
2073
- ${summary}`
2074
- }
2075
- ],
2076
- isError: false,
2077
- isComplete: true
2078
- };
1779
+ // Check if there is a previous step available
1780
+ hasPreviousStep() {
1781
+ return this.getPreviousStep() !== null;
2079
1782
  }
2080
- // Use LLM to create high-signal summary for parent agent
2081
- async summarizeConversation(parentSpan) {
2082
- if (this.conversationHistory.length === 0) {
2083
- return "\n\n**No conversation history**";
1783
+ // Check if currently at the first step
1784
+ isAtFirstStep() {
1785
+ return this.isInitialized && this.currentStepIndex === 0;
1786
+ }
1787
+ // Check if currently at the last step
1788
+ isAtLastStep() {
1789
+ return this.isInitialized && this.currentStepIndex >= this.steps.length - 1;
1790
+ }
1791
+ isWorkflowStarted() {
1792
+ return this.isStarted;
1793
+ }
1794
+ isCompleted() {
1795
+ return this.isInitialized && this.currentStepIndex > this.steps.length - 1;
1796
+ }
1797
+ // Mark workflow as completed by moving beyond the last step
1798
+ markCompleted() {
1799
+ if (this.isInitialized) {
1800
+ this.currentStepIndex = this.steps.length;
2084
1801
  }
2085
- if (this.conversationHistory.length <= 3) {
2086
- return this.formatConversation();
1802
+ }
1803
+ initialize(steps) {
1804
+ this.steps = steps;
1805
+ this.stepStatuses = new Array(steps.length).fill("pending");
1806
+ this.stepResults = new Array(steps.length).fill("");
1807
+ this.stepErrors = new Array(steps.length).fill("");
1808
+ this.currentStepIndex = 0;
1809
+ this.isInitialized = true;
1810
+ this.isStarted = false;
1811
+ }
1812
+ // Mark current step as running
1813
+ markCurrentStepRunning() {
1814
+ if (this.isInitialized && this.currentStepIndex >= 0 && this.currentStepIndex < this.steps.length) {
1815
+ this.stepStatuses[this.currentStepIndex] = "running";
2087
1816
  }
2088
- const summarizeSpan = this.tracingEnabled ? startSpan("mcpc.sampling_summarize", {
2089
- agent: this.name,
2090
- messageCount: this.conversationHistory.length
2091
- }, parentSpan ?? void 0) : null;
2092
- try {
2093
- this.logger.debug({
2094
- message: "Starting conversation summarization",
2095
- messageCount: this.conversationHistory.length
2096
- });
2097
- const history = this.conversationHistory.map((msg, i) => {
2098
- const prefix = `[${i + 1}] ${msg.role.toUpperCase()}`;
2099
- return `${prefix}:
2100
- ${msg.content.text}`;
2101
- }).join("\n\n---\n\n");
2102
- const response = await this.server.createMessage({
2103
- systemPrompt: `Summarize this agent execution:
2104
-
2105
- Final Decision: (include complete JSON if present)
2106
- Key Findings: (most important)
2107
- Actions Taken: (high-level flow)
2108
- Errors/Warnings: (if any)
2109
-
2110
- ${history}`,
2111
- messages: [
2112
- {
2113
- role: "user",
2114
- content: {
2115
- type: "text",
2116
- text: "Please provide a concise summary."
2117
- }
2118
- }
2119
- ],
2120
- maxTokens: 3e3
2121
- });
2122
- const summary = "\n\n" + response.content.text;
2123
- this.logger.debug({
2124
- message: "Summarization completed",
2125
- summaryLength: summary.length
2126
- });
2127
- if (summarizeSpan) {
2128
- summarizeSpan.setAttributes({
2129
- summaryLength: summary.length,
2130
- summary,
2131
- success: true
2132
- });
2133
- endSpan(summarizeSpan);
1817
+ }
1818
+ // Mark current step as completed
1819
+ markCurrentStepCompleted(result) {
1820
+ if (this.isInitialized && this.currentStepIndex >= 0 && this.currentStepIndex < this.steps.length) {
1821
+ this.stepStatuses[this.currentStepIndex] = "completed";
1822
+ if (result) {
1823
+ this.stepResults[this.currentStepIndex] = result;
2134
1824
  }
2135
- return summary;
2136
- } catch (error) {
2137
- this.logger.warning({
2138
- message: "Summarization failed, falling back to full history",
2139
- error: String(error)
2140
- });
2141
- if (summarizeSpan) {
2142
- endSpan(summarizeSpan, error);
1825
+ }
1826
+ }
1827
+ // Mark current step as failed
1828
+ markCurrentStepFailed(error) {
1829
+ if (this.isInitialized && this.currentStepIndex >= 0 && this.currentStepIndex < this.steps.length) {
1830
+ this.stepStatuses[this.currentStepIndex] = "failed";
1831
+ if (error) {
1832
+ this.stepErrors[this.currentStepIndex] = error;
2143
1833
  }
2144
- return this.formatConversation();
2145
1834
  }
2146
1835
  }
2147
- // Format full conversation history (for debugging)
2148
- formatConversation() {
2149
- if (this.conversationHistory.length === 0) {
2150
- return "\n\n**No conversation history**";
1836
+ // Get steps with their status
1837
+ getStepsWithStatus() {
1838
+ return this.steps.map((step, index) => ({
1839
+ ...step,
1840
+ status: this.stepStatuses[index] || "pending",
1841
+ result: this.stepResults[index] || void 0,
1842
+ error: this.stepErrors[index] || void 0
1843
+ }));
1844
+ }
1845
+ // Get basic workflow progress data for template rendering
1846
+ getProgressData() {
1847
+ return {
1848
+ steps: this.steps,
1849
+ statuses: this.stepStatuses,
1850
+ results: this.stepResults,
1851
+ errors: this.stepErrors,
1852
+ currentStepIndex: this.currentStepIndex,
1853
+ totalSteps: this.steps.length
1854
+ };
1855
+ }
1856
+ start() {
1857
+ this.isStarted = true;
1858
+ }
1859
+ moveToNextStep() {
1860
+ if (!this.hasNextStep()) {
1861
+ return false;
1862
+ }
1863
+ this.currentStepIndex++;
1864
+ return true;
1865
+ }
1866
+ // Move to the previous step in the workflow
1867
+ moveToPreviousStep() {
1868
+ if (!this.hasPreviousStep()) {
1869
+ return false;
2151
1870
  }
2152
- const messages = this.conversationHistory.map((msg, i) => {
2153
- const header = `### Message ${i + 1}: ${msg.role}`;
2154
- try {
2155
- const parsed = JSON.parse(msg.content.text);
2156
- if (JSON.stringify(parsed).length < 100) {
2157
- return `${header}
2158
- ${JSON.stringify(parsed)}`;
2159
- }
2160
- return `${header}
2161
- \`\`\`json
2162
- ${JSON.stringify(parsed, null, 2)}
2163
- \`\`\``;
2164
- } catch {
2165
- return `${header}
2166
- ${msg.content.text}`;
2167
- }
2168
- });
2169
- return "\n\n**Conversation History:**\n" + messages.join("\n\n");
1871
+ this.currentStepIndex--;
1872
+ return true;
2170
1873
  }
2171
- logIterationProgress(parsedData, result, model, stopReason, role) {
2172
- this.logger.debug({
2173
- iteration: `${this.currentIteration + 1}/${this.maxIterations}`,
2174
- parsedData,
2175
- isError: result.isError,
2176
- isComplete: result.isComplete,
2177
- model,
2178
- stopReason,
2179
- role,
2180
- result
2181
- });
1874
+ // Move to a specific step by index (optional feature)
1875
+ moveToStep(stepIndex) {
1876
+ if (!this.isInitialized || stepIndex < 0 || stepIndex >= this.steps.length) {
1877
+ return false;
1878
+ }
1879
+ this.currentStepIndex = stepIndex;
1880
+ return true;
2182
1881
  }
2183
- injectJsonInstruction({ prompt, schema, schemaPrefix = "JSON schema:", schemaSuffix = `STRICT REQUIREMENTS:
2184
- 1. Return ONE AND ONLY ONE raw JSON object that passes JSON.parse() - no markdown, code blocks, explanatory text, or multiple JSON objects
2185
- 2. Include ALL required fields with correct data types and satisfy ALL schema constraints (anyOf, oneOf, allOf, not, enum, pattern, min/max, conditionals)
2186
- 3. Your response must be a single JSON object, nothing else
1882
+ reset() {
1883
+ this.currentStepIndex = -1;
1884
+ this.steps = [];
1885
+ this.stepStatuses = [];
1886
+ this.stepResults = [];
1887
+ this.stepErrors = [];
1888
+ this.isInitialized = false;
1889
+ this.isStarted = false;
1890
+ }
1891
+ getDebugInfo() {
1892
+ return {
1893
+ currentStepIndex: this.currentStepIndex,
1894
+ totalSteps: this.steps.length,
1895
+ isInitialized: this.isInitialized,
1896
+ currentStep: this.getCurrentStep()?.description,
1897
+ nextStep: this.getNextStep()?.description,
1898
+ previousStep: this.getPreviousStep()?.description,
1899
+ isAtFirstStep: this.isAtFirstStep(),
1900
+ hasPreviousStep: this.hasPreviousStep()
1901
+ };
1902
+ }
1903
+ };
2187
1904
 
2188
- INVALID: \`\`\`json{"key":"value"}\`\`\` or "Here is: {"key":"value"}" or {"key":"value"}{"key":"value"}
2189
- VALID: {"key":"value"}` }) {
2190
- return [
2191
- prompt != null && prompt.length > 0 ? prompt : void 0,
2192
- prompt != null && prompt.length > 0 ? "" : void 0,
2193
- schemaPrefix,
2194
- schema != null ? JSON.stringify(schema, null, 2) : void 0,
2195
- schemaSuffix
2196
- ].filter((line) => line != null).join("\n");
1905
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/workflow/workflow-executor.js
1906
+ var WorkflowExecutor = class {
1907
+ name;
1908
+ allToolNames;
1909
+ toolNameToDetailList;
1910
+ createArgsDef;
1911
+ server;
1912
+ predefinedSteps;
1913
+ ensureStepActions;
1914
+ toolNameToIdMapping;
1915
+ constructor(name, allToolNames, toolNameToDetailList, createArgsDef, server2, predefinedSteps, ensureStepActions, toolNameToIdMapping) {
1916
+ this.name = name;
1917
+ this.allToolNames = allToolNames;
1918
+ this.toolNameToDetailList = toolNameToDetailList;
1919
+ this.createArgsDef = createArgsDef;
1920
+ this.server = server2;
1921
+ this.predefinedSteps = predefinedSteps;
1922
+ this.ensureStepActions = ensureStepActions;
1923
+ this.toolNameToIdMapping = toolNameToIdMapping;
2197
1924
  }
2198
- // Validate arguments using JSON schema
2199
- validateSchema(args, schema) {
2200
- const validate = ajv2.compile(schema);
2201
- if (!validate(args)) {
2202
- const errors = new AggregateAjvError2(validate.errors);
1925
+ // Helper method to validate required actions are present in workflow steps
1926
+ validateRequiredActions(steps) {
1927
+ if (!this.ensureStepActions || this.ensureStepActions.length === 0) {
2203
1928
  return {
2204
- valid: false,
2205
- error: errors.message
1929
+ valid: true,
1930
+ missing: []
2206
1931
  };
2207
1932
  }
1933
+ const allStepActions = /* @__PURE__ */ new Set();
1934
+ steps.forEach((step) => {
1935
+ step.actions.forEach((action) => allStepActions.add(action));
1936
+ });
1937
+ const missing = [];
1938
+ for (const requiredAction of this.ensureStepActions) {
1939
+ if (allStepActions.has(requiredAction)) {
1940
+ continue;
1941
+ }
1942
+ if (this.toolNameToIdMapping) {
1943
+ const mappedToolId = this.toolNameToIdMapping.get(requiredAction);
1944
+ if (mappedToolId && allStepActions.has(mappedToolId)) {
1945
+ continue;
1946
+ }
1947
+ }
1948
+ missing.push(requiredAction);
1949
+ }
2208
1950
  return {
2209
- valid: true
1951
+ valid: missing.length === 0,
1952
+ missing
2210
1953
  };
2211
1954
  }
2212
- };
2213
-
2214
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/sampling/agentic-sampling-executor.js
2215
- var SamplingExecutor = class extends BaseSamplingExecutor {
2216
- agenticExecutor;
2217
- constructor(name, description, allToolNames, toolNameToDetailList, server2, config2) {
2218
- super(name, description, allToolNames, toolNameToDetailList, server2, config2);
2219
- this.agenticExecutor = new AgenticExecutor(name, allToolNames, toolNameToDetailList, server2);
1955
+ // Helper method to format workflow progress
1956
+ formatProgress(state) {
1957
+ const progressData = state.getProgressData();
1958
+ return PromptUtils.formatWorkflowProgress(progressData);
2220
1959
  }
2221
- buildDepGroups() {
2222
- const depGroups = {};
2223
- this.toolNameToDetailList.forEach(([toolName, tool]) => {
2224
- if (tool?.inputSchema) {
2225
- depGroups[toolName] = {
2226
- type: "object",
2227
- description: tool.description || `Tool: ${toolName}`,
2228
- ...tool.inputSchema
1960
+ async execute(args, state) {
1961
+ if (args.init) {
1962
+ state.reset();
1963
+ } else {
1964
+ if (!state.isWorkflowInitialized() && !args.init) {
1965
+ return {
1966
+ content: [
1967
+ {
1968
+ type: "text",
1969
+ text: this.predefinedSteps ? WorkflowPrompts.ERRORS.NOT_INITIALIZED.WITH_PREDEFINED : WorkflowPrompts.ERRORS.NOT_INITIALIZED.WITHOUT_PREDEFINED
1970
+ }
1971
+ ],
1972
+ isError: true
2229
1973
  };
2230
- } else {
2231
- const toolSchema = this.server.getHiddenToolSchema(toolName);
2232
- if (toolSchema) {
2233
- depGroups[toolName] = {
2234
- ...toolSchema.schema,
2235
- description: toolSchema.description
1974
+ }
1975
+ const decision2 = args.decision;
1976
+ if (decision2 === "proceed") {
1977
+ if (state.isAtLastStep() && state.isWorkflowStarted()) {
1978
+ state.markCompleted();
1979
+ return {
1980
+ content: [
1981
+ {
1982
+ type: "text",
1983
+ text: `## Workflow Completed!
1984
+
1985
+ ${this.formatProgress(state)}
1986
+
1987
+ ${CompiledPrompts.workflowCompleted({
1988
+ totalSteps: state.getSteps().length,
1989
+ toolName: this.name,
1990
+ newWorkflowInstructions: this.predefinedSteps ? "" : " and new `steps` array"
1991
+ })}`
1992
+ }
1993
+ ],
1994
+ isError: false
1995
+ };
1996
+ }
1997
+ if (state.isCompleted()) {
1998
+ return {
1999
+ content: [
2000
+ {
2001
+ type: "text",
2002
+ text: WorkflowPrompts.ERRORS.ALREADY_AT_FINAL
2003
+ }
2004
+ ],
2005
+ isError: true
2006
+ };
2007
+ }
2008
+ const currentStepIndex = state.getCurrentStepIndex();
2009
+ const wasStarted = state.isWorkflowStarted();
2010
+ if (state.isWorkflowStarted()) {
2011
+ state.moveToNextStep();
2012
+ } else {
2013
+ state.start();
2014
+ }
2015
+ const nextStepValidationSchema = this.createArgsDef.forCurrentState(state);
2016
+ const nextStepValidationResult = this.validateInput(args, nextStepValidationSchema);
2017
+ if (!nextStepValidationResult.valid) {
2018
+ if (wasStarted) {
2019
+ state.moveToStep(currentStepIndex);
2020
+ } else {
2021
+ state.moveToStep(currentStepIndex);
2022
+ }
2023
+ return {
2024
+ content: [
2025
+ {
2026
+ type: "text",
2027
+ text: CompiledPrompts.workflowErrorResponse({
2028
+ errorMessage: `Cannot proceed to next step: ${nextStepValidationResult.error || "Arguments validation failed"}`
2029
+ })
2030
+ }
2031
+ ],
2032
+ isError: true
2033
+ };
2034
+ }
2035
+ } else if (decision2 === "complete") {
2036
+ if (state.isAtLastStep() && state.isWorkflowStarted()) {
2037
+ state.markCompleted();
2038
+ return {
2039
+ content: [
2040
+ {
2041
+ type: "text",
2042
+ text: `## Workflow Completed!
2043
+
2044
+ ${this.formatProgress(state)}
2045
+
2046
+ ${CompiledPrompts.workflowCompleted({
2047
+ totalSteps: state.getSteps().length,
2048
+ toolName: this.name,
2049
+ newWorkflowInstructions: this.predefinedSteps ? "" : " and new `steps` array"
2050
+ })}`
2051
+ }
2052
+ ],
2053
+ isError: false
2054
+ };
2055
+ } else {
2056
+ return {
2057
+ content: [
2058
+ {
2059
+ type: "text",
2060
+ text: WorkflowPrompts.ERRORS.CANNOT_COMPLETE_NOT_AT_FINAL
2061
+ }
2062
+ ],
2063
+ isError: true
2236
2064
  };
2237
2065
  }
2238
2066
  }
2239
- });
2240
- return depGroups;
2067
+ }
2068
+ const decision = args.decision;
2069
+ if (decision !== "proceed") {
2070
+ const validationSchema = this.createArgsDef.forCurrentState(state);
2071
+ const validationResult = this.validateInput(args, validationSchema);
2072
+ if (!validationResult.valid) {
2073
+ return {
2074
+ content: [
2075
+ {
2076
+ type: "text",
2077
+ text: CompiledPrompts.workflowErrorResponse({
2078
+ errorMessage: validationResult.error || "Arguments validation failed"
2079
+ })
2080
+ }
2081
+ ],
2082
+ isError: true
2083
+ };
2084
+ }
2085
+ }
2086
+ if (args.init) {
2087
+ return this.initialize(args, state);
2088
+ }
2089
+ return await this.executeStep(args, state);
2241
2090
  }
2242
- executeSampling(args, schema) {
2243
- const validationResult = this.validateSchema(args, schema);
2244
- if (!validationResult.valid) {
2091
+ initialize(args, state) {
2092
+ const steps = args.steps ?? this.predefinedSteps;
2093
+ if (!steps || steps.length === 0) {
2245
2094
  return {
2246
2095
  content: [
2247
2096
  {
2248
2097
  type: "text",
2249
- text: CompiledPrompts.errorResponse({
2250
- errorMessage: validationResult.error || "Validation failed"
2251
- })
2098
+ text: WorkflowPrompts.ERRORS.NO_STEPS_PROVIDED
2252
2099
  }
2253
2100
  ],
2254
2101
  isError: true
2255
2102
  };
2256
2103
  }
2257
- const createArgsDef = createArgsDefFactory(this.name, this.allToolNames, this.buildDepGroups(), void 0, void 0);
2258
- const agenticSchema = createArgsDef.forAgentic(this.toolNameToDetailList, true);
2259
- const systemPrompt = this.buildSystemPrompt(args.userRequest, agenticSchema, args.context && typeof args.context === "object" ? args.context : void 0);
2260
- return this.runSamplingLoop(() => systemPrompt, agenticSchema);
2261
- }
2262
- async processAction(parsedData, schema, _state, parentSpan) {
2263
- const toolCallData = parsedData;
2264
- if (toolCallData.decision === "complete") {
2265
- return await this.createCompletionResult("Task completed", parentSpan);
2266
- }
2267
- try {
2268
- const { action: _action, decision: _decision, ..._toolArgs } = toolCallData;
2269
- const toolResult = await this.agenticExecutor.execute(toolCallData, schema, parentSpan);
2270
- const resultText = toolResult.content?.filter((content) => content.type === "text")?.map((content) => content.text)?.join("\n") || "No result";
2271
- this.conversationHistory.push({
2272
- role: "assistant",
2273
- content: {
2274
- type: "text",
2275
- text: resultText
2276
- }
2277
- });
2278
- return toolResult;
2279
- } catch (error) {
2280
- return this.createExecutionError(error, parentSpan);
2281
- }
2282
- }
2283
- buildSystemPrompt(userRequest, agenticSchema, context2) {
2284
- const toolList = this.allToolNames.map((name) => {
2285
- const tool = this.toolNameToDetailList.find(([toolName]) => toolName === name);
2286
- const toolSchema = this.server.getHiddenToolSchema(name);
2287
- if (tool && tool[1]) {
2288
- return `- ${name}: ${tool[1].description || `Tool: ${name}`}`;
2289
- } else if (toolSchema) {
2290
- return `- ${name}: ${toolSchema.description}`;
2291
- }
2292
- return `- ${name}`;
2293
- }).join("\n");
2294
- let contextInfo = "";
2295
- if (context2 && typeof context2 === "object" && Object.keys(context2).length > 0) {
2296
- contextInfo = `
2297
-
2298
- Context:
2299
- ${JSON.stringify(context2, null, 2)}`;
2300
- }
2301
- const basePrompt = CompiledPrompts.samplingExecution({
2302
- toolName: this.name,
2303
- description: this.description,
2304
- toolList
2305
- });
2306
- const taskPrompt = `
2307
-
2308
- ## Current Task
2309
- You will now use agentic sampling to complete the following task: "${userRequest}"${contextInfo}
2310
-
2311
- When you need to use a tool, specify the tool name in 'action' and provide tool-specific parameters as additional properties.`;
2312
- return this.injectJsonInstruction({
2313
- prompt: basePrompt + taskPrompt,
2314
- schema: agenticSchema
2315
- });
2316
- }
2317
- };
2318
-
2319
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/agentic/agentic-tool-registrar.js
2320
- function registerAgenticTool(server2, { description, name, allToolNames, depGroups, toolNameToDetailList, sampling = false }) {
2321
- const createArgsDef = createArgsDefFactory(name, allToolNames, depGroups, void 0, void 0);
2322
- const isSamplingMode = sampling === true || typeof sampling === "object";
2323
- const samplingConfig = typeof sampling === "object" ? sampling : void 0;
2324
- const agenticExecutor = new AgenticExecutor(name, allToolNames, toolNameToDetailList, server2);
2325
- const samplingExecutor = new SamplingExecutor(name, description, allToolNames, toolNameToDetailList, server2, samplingConfig);
2326
- description = isSamplingMode ? CompiledPrompts.samplingExecution({
2327
- toolName: name,
2328
- description,
2329
- toolList: allToolNames.map((name2) => `- ${name2}`).join("\n")
2330
- }) : CompiledPrompts.autonomousExecution({
2331
- toolName: name,
2332
- description
2333
- });
2334
- const agenticArgsDef = createArgsDef.forAgentic(toolNameToDetailList, false);
2335
- const argsDef = isSamplingMode ? createArgsDef.forSampling() : agenticArgsDef;
2336
- const schema = allToolNames.length > 0 ? argsDef : {
2337
- type: "object",
2338
- properties: {}
2339
- };
2340
- server2.tool(name, description, jsonSchema(createGoogleCompatibleJSONSchema(schema)), async (args) => {
2341
- if (isSamplingMode) {
2342
- return await samplingExecutor.executeSampling(args, schema);
2343
- } else {
2344
- return await agenticExecutor.execute(args, schema);
2345
- }
2346
- });
2347
- }
2104
+ const validation = this.validateRequiredActions(steps);
2105
+ if (!validation.valid) {
2106
+ return {
2107
+ content: [
2108
+ {
2109
+ type: "text",
2110
+ text: `## Workflow Validation Failed \u274C
2348
2111
 
2349
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/workflow/workflow-tool-registrar.js
2350
- init_schema();
2112
+ **Missing Required Actions:** The following actions must be included in the workflow steps:
2351
2113
 
2352
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/state.js
2353
- var WorkflowState = class {
2354
- currentStepIndex = -1;
2355
- steps = [];
2356
- stepStatuses = [];
2357
- stepResults = [];
2358
- stepErrors = [];
2359
- isInitialized = false;
2360
- isStarted = false;
2361
- constructor(steps) {
2362
- if (steps) {
2363
- this.initialize(steps);
2364
- }
2365
- }
2366
- getCurrentStepIndex() {
2367
- return this.currentStepIndex;
2368
- }
2369
- getSteps() {
2370
- return this.steps;
2371
- }
2372
- isWorkflowInitialized() {
2373
- return this.isInitialized;
2374
- }
2375
- getCurrentStep() {
2376
- if (!this.isInitialized || this.currentStepIndex < 0) {
2377
- return null;
2378
- }
2379
- return this.steps[this.currentStepIndex] || null;
2380
- }
2381
- getNextStep() {
2382
- if (!this.isInitialized) return null;
2383
- const nextIndex = this.currentStepIndex + 1;
2384
- return this.steps[nextIndex] || null;
2385
- }
2386
- // Get the previous step in the workflow
2387
- getPreviousStep() {
2388
- if (!this.isInitialized) return null;
2389
- const prevIndex = this.currentStepIndex - 1;
2390
- return this.steps[prevIndex] || null;
2391
- }
2392
- hasNextStep() {
2393
- return this.getNextStep() !== null;
2394
- }
2395
- // Check if there is a previous step available
2396
- hasPreviousStep() {
2397
- return this.getPreviousStep() !== null;
2398
- }
2399
- // Check if currently at the first step
2400
- isAtFirstStep() {
2401
- return this.isInitialized && this.currentStepIndex === 0;
2402
- }
2403
- // Check if currently at the last step
2404
- isAtLastStep() {
2405
- return this.isInitialized && this.currentStepIndex >= this.steps.length - 1;
2406
- }
2407
- isWorkflowStarted() {
2408
- return this.isStarted;
2409
- }
2410
- isCompleted() {
2411
- return this.isInitialized && this.currentStepIndex > this.steps.length - 1;
2412
- }
2413
- // Mark workflow as completed by moving beyond the last step
2414
- markCompleted() {
2415
- if (this.isInitialized) {
2416
- this.currentStepIndex = this.steps.length;
2417
- }
2418
- }
2419
- initialize(steps) {
2420
- this.steps = steps;
2421
- this.stepStatuses = new Array(steps.length).fill("pending");
2422
- this.stepResults = new Array(steps.length).fill("");
2423
- this.stepErrors = new Array(steps.length).fill("");
2424
- this.currentStepIndex = 0;
2425
- this.isInitialized = true;
2426
- this.isStarted = false;
2427
- }
2428
- // Mark current step as running
2429
- markCurrentStepRunning() {
2430
- if (this.isInitialized && this.currentStepIndex >= 0 && this.currentStepIndex < this.steps.length) {
2431
- this.stepStatuses[this.currentStepIndex] = "running";
2432
- }
2433
- }
2434
- // Mark current step as completed
2435
- markCurrentStepCompleted(result) {
2436
- if (this.isInitialized && this.currentStepIndex >= 0 && this.currentStepIndex < this.steps.length) {
2437
- this.stepStatuses[this.currentStepIndex] = "completed";
2438
- if (result) {
2439
- this.stepResults[this.currentStepIndex] = result;
2440
- }
2441
- }
2442
- }
2443
- // Mark current step as failed
2444
- markCurrentStepFailed(error) {
2445
- if (this.isInitialized && this.currentStepIndex >= 0 && this.currentStepIndex < this.steps.length) {
2446
- this.stepStatuses[this.currentStepIndex] = "failed";
2447
- if (error) {
2448
- this.stepErrors[this.currentStepIndex] = error;
2449
- }
2450
- }
2451
- }
2452
- // Get steps with their status
2453
- getStepsWithStatus() {
2454
- return this.steps.map((step, index) => ({
2455
- ...step,
2456
- status: this.stepStatuses[index] || "pending",
2457
- result: this.stepResults[index] || void 0,
2458
- error: this.stepErrors[index] || void 0
2459
- }));
2460
- }
2461
- // Get basic workflow progress data for template rendering
2462
- getProgressData() {
2463
- return {
2464
- steps: this.steps,
2465
- statuses: this.stepStatuses,
2466
- results: this.stepResults,
2467
- errors: this.stepErrors,
2468
- currentStepIndex: this.currentStepIndex,
2469
- totalSteps: this.steps.length
2114
+ ${validation.missing.map((action) => `- \`${this.toolNameToIdMapping?.get(action) ?? action}\``).join("\n")}`
2115
+ }
2116
+ ],
2117
+ isError: true
2118
+ };
2119
+ }
2120
+ state.initialize(steps);
2121
+ return {
2122
+ content: [
2123
+ {
2124
+ type: "text",
2125
+ text: `## Workflow Initialized
2126
+ ${this.formatProgress(state)}
2127
+ ${this.createArgsDef.forInitialStepDescription(steps, state)}`
2128
+ }
2129
+ ],
2130
+ isError: false
2470
2131
  };
2471
2132
  }
2472
- start() {
2473
- this.isStarted = true;
2474
- }
2475
- moveToNextStep() {
2476
- if (!this.hasNextStep()) {
2477
- return false;
2133
+ async executeStep(args, state) {
2134
+ const currentStep = state.getCurrentStep();
2135
+ if (!currentStep) {
2136
+ return {
2137
+ content: [
2138
+ {
2139
+ type: "text",
2140
+ text: WorkflowPrompts.ERRORS.NO_CURRENT_STEP
2141
+ }
2142
+ ],
2143
+ isError: true
2144
+ };
2478
2145
  }
2479
- this.currentStepIndex++;
2480
- return true;
2481
- }
2482
- // Move to the previous step in the workflow
2483
- moveToPreviousStep() {
2484
- if (!this.hasPreviousStep()) {
2485
- return false;
2146
+ state.markCurrentStepRunning();
2147
+ const results = {
2148
+ content: [],
2149
+ isError: false
2150
+ };
2151
+ for (const action of currentStep.actions) {
2152
+ try {
2153
+ const actionArgs = args[action] || {};
2154
+ const actionResult = await this.server.callTool(action, actionArgs);
2155
+ if (!results.isError) {
2156
+ results.isError = actionResult.isError;
2157
+ }
2158
+ results.content = results.content.concat(actionResult.content ?? []);
2159
+ results.content.push({
2160
+ type: "text",
2161
+ text: `Action \`${action}\` executed ${actionResult.isError ? "\u274C **FAILED**" : "\u2705 **SUCCESS**"}:`
2162
+ });
2163
+ } catch (error) {
2164
+ results.content.push({
2165
+ type: "text",
2166
+ text: `${error.message}`
2167
+ });
2168
+ results.content.push({
2169
+ type: "text",
2170
+ text: `Action \`${action}\` \u274C **FAILED** with error: `
2171
+ });
2172
+ results.isError = true;
2173
+ }
2486
2174
  }
2487
- this.currentStepIndex--;
2488
- return true;
2489
- }
2490
- // Move to a specific step by index (optional feature)
2491
- moveToStep(stepIndex) {
2492
- if (!this.isInitialized || stepIndex < 0 || stepIndex >= this.steps.length) {
2493
- return false;
2175
+ if (results.isError) {
2176
+ state.markCurrentStepFailed("Step execution failed");
2177
+ } else {
2178
+ state.markCurrentStepCompleted("Step completed successfully");
2494
2179
  }
2495
- this.currentStepIndex = stepIndex;
2496
- return true;
2497
- }
2498
- reset() {
2499
- this.currentStepIndex = -1;
2500
- this.steps = [];
2501
- this.stepStatuses = [];
2502
- this.stepResults = [];
2503
- this.stepErrors = [];
2504
- this.isInitialized = false;
2505
- this.isStarted = false;
2180
+ if (state.hasNextStep()) {
2181
+ const nextStepArgsDef = this.createArgsDef.forNextState(state);
2182
+ results.content.push({
2183
+ type: "text",
2184
+ text: CompiledPrompts.nextStepDecision({
2185
+ toolName: this.name,
2186
+ nextStepDescription: state.getNextStep()?.description || "Unknown step",
2187
+ nextStepSchema: JSON.stringify(nextStepArgsDef, null, 2)
2188
+ })
2189
+ });
2190
+ } else {
2191
+ results.content.push({
2192
+ type: "text",
2193
+ text: CompiledPrompts.finalStepCompletion({
2194
+ statusIcon: results.isError ? "\u274C" : "\u2705",
2195
+ statusText: results.isError ? "with errors" : "successfully",
2196
+ toolName: this.name,
2197
+ newWorkflowInstructions: this.predefinedSteps ? "" : " and new `steps` array"
2198
+ })
2199
+ });
2200
+ }
2201
+ results.content.push({
2202
+ type: "text",
2203
+ text: `## Workflow Progress
2204
+ ${this.formatProgress(state)}`
2205
+ });
2206
+ return results;
2506
2207
  }
2507
- getDebugInfo() {
2508
- return {
2509
- currentStepIndex: this.currentStepIndex,
2510
- totalSteps: this.steps.length,
2511
- isInitialized: this.isInitialized,
2512
- currentStep: this.getCurrentStep()?.description,
2513
- nextStep: this.getNextStep()?.description,
2514
- previousStep: this.getPreviousStep()?.description,
2515
- isAtFirstStep: this.isAtFirstStep(),
2516
- hasPreviousStep: this.hasPreviousStep()
2517
- };
2208
+ // Validate arguments using JSON schema
2209
+ validateInput(args, schema) {
2210
+ return validateSchema(args, schema);
2518
2211
  }
2519
2212
  };
2520
2213
 
2521
2214
  // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/workflow/workflow-tool-registrar.js
2522
- init_provider();
2215
+ function registerAgenticWorkflowTool(server2, { description, name, allToolNames, depGroups, toolNameToDetailList, predefinedSteps, ensureStepActions, toolNameToIdMapping }) {
2216
+ const createArgsDef = createArgsDefFactory(name, allToolNames, depGroups, predefinedSteps, ensureStepActions);
2217
+ const workflowExecutor = new WorkflowExecutor(name, allToolNames, toolNameToDetailList, createArgsDef, server2, predefinedSteps, ensureStepActions, toolNameToIdMapping);
2218
+ const workflowState = new WorkflowState();
2219
+ const planningInstructions = predefinedSteps ? "- Set `init: true` (steps are predefined)" : "- Set `init: true` and define complete `steps` array";
2220
+ const baseDescription = CompiledPrompts.workflowExecution({
2221
+ toolName: name,
2222
+ description,
2223
+ planningInstructions
2224
+ });
2225
+ const argsDef = createArgsDef.forTool();
2226
+ const toolDescription = createArgsDef.forToolDescription(baseDescription, workflowState);
2227
+ server2.tool(name, toolDescription, jsonSchema(createGoogleCompatibleJSONSchema(argsDef)), async (args) => {
2228
+ try {
2229
+ return await workflowExecutor.execute(args, workflowState);
2230
+ } catch (error) {
2231
+ workflowState.reset();
2232
+ return {
2233
+ content: [
2234
+ {
2235
+ type: "text",
2236
+ text: `Workflow execution error: ${error.message}`
2237
+ }
2238
+ ],
2239
+ isError: true
2240
+ };
2241
+ }
2242
+ });
2243
+ }
2523
2244
 
2524
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/workflow/workflow-executor.js
2525
- import { Ajv as Ajv3 } from "ajv";
2526
- import { AggregateAjvError as AggregateAjvError3 } from "@segment/ajv-human-errors";
2527
- import addFormats3 from "ajv-formats";
2528
- var ajv3 = new Ajv3({
2529
- allErrors: true,
2530
- verbose: true
2245
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/mode-workflow-plugin.js
2246
+ var createWorkflowModePlugin = () => ({
2247
+ name: "mode-workflow",
2248
+ version: "1.0.0",
2249
+ // Only apply to workflow mode
2250
+ apply: "agentic_workflow",
2251
+ // Register the agent tool
2252
+ registerAgentTool: (context2) => {
2253
+ registerAgenticWorkflowTool(context2.server, {
2254
+ description: context2.description,
2255
+ name: context2.name,
2256
+ allToolNames: context2.allToolNames,
2257
+ depGroups: context2.depGroups,
2258
+ toolNameToDetailList: context2.toolNameToDetailList,
2259
+ predefinedSteps: context2.options.steps,
2260
+ ensureStepActions: context2.options.ensureStepActions,
2261
+ toolNameToIdMapping: context2.toolNameToIdMapping
2262
+ });
2263
+ }
2531
2264
  });
2532
- addFormats3(ajv3);
2533
- var WorkflowExecutor = class {
2265
+ var mode_workflow_plugin_default = createWorkflowModePlugin();
2266
+
2267
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/sampling/base-sampling-executor.js
2268
+ import process5 from "node:process";
2269
+ var BaseSamplingExecutor = class {
2534
2270
  name;
2271
+ description;
2535
2272
  allToolNames;
2536
2273
  toolNameToDetailList;
2537
- createArgsDef;
2538
2274
  server;
2539
- predefinedSteps;
2540
- ensureStepActions;
2541
- toolNameToIdMapping;
2542
- constructor(name, allToolNames, toolNameToDetailList, createArgsDef, server2, predefinedSteps, ensureStepActions, toolNameToIdMapping) {
2275
+ conversationHistory;
2276
+ maxIterations;
2277
+ currentIteration;
2278
+ logger;
2279
+ tracingEnabled;
2280
+ summarize;
2281
+ constructor(name, description, allToolNames, toolNameToDetailList, server2, config2) {
2543
2282
  this.name = name;
2283
+ this.description = description;
2544
2284
  this.allToolNames = allToolNames;
2545
2285
  this.toolNameToDetailList = toolNameToDetailList;
2546
- this.createArgsDef = createArgsDef;
2547
2286
  this.server = server2;
2548
- this.predefinedSteps = predefinedSteps;
2549
- this.ensureStepActions = ensureStepActions;
2550
- this.toolNameToIdMapping = toolNameToIdMapping;
2551
- }
2552
- // Helper method to validate required actions are present in workflow steps
2553
- validateRequiredActions(steps) {
2554
- if (!this.ensureStepActions || this.ensureStepActions.length === 0) {
2555
- return {
2556
- valid: true,
2557
- missing: []
2558
- };
2287
+ this.conversationHistory = [];
2288
+ this.maxIterations = 55;
2289
+ this.currentIteration = 0;
2290
+ this.tracingEnabled = false;
2291
+ this.summarize = true;
2292
+ if (config2?.maxIterations) {
2293
+ this.maxIterations = config2.maxIterations;
2559
2294
  }
2560
- const allStepActions = /* @__PURE__ */ new Set();
2561
- steps.forEach((step) => {
2562
- step.actions.forEach((action) => allStepActions.add(action));
2563
- });
2564
- const missing = [];
2565
- for (const requiredAction of this.ensureStepActions) {
2566
- if (allStepActions.has(requiredAction)) {
2567
- continue;
2568
- }
2569
- if (this.toolNameToIdMapping) {
2570
- const mappedToolId = this.toolNameToIdMapping.get(requiredAction);
2571
- if (mappedToolId && allStepActions.has(mappedToolId)) {
2572
- continue;
2573
- }
2295
+ if (config2?.summarize !== void 0) {
2296
+ this.summarize = config2.summarize;
2297
+ }
2298
+ this.logger = createLogger(`mcpc.sampling.${name}`, server2);
2299
+ try {
2300
+ const tracingConfig = {
2301
+ enabled: process5.env.MCPC_TRACING_ENABLED === "true",
2302
+ serviceName: `mcpc-sampling-${name}`,
2303
+ exportTo: process5.env.MCPC_TRACING_EXPORT ?? "otlp",
2304
+ otlpEndpoint: process5.env.MCPC_TRACING_OTLP_ENDPOINT ?? "http://localhost:4318/v1/traces"
2305
+ };
2306
+ this.tracingEnabled = tracingConfig.enabled;
2307
+ if (this.tracingEnabled) {
2308
+ initializeTracing(tracingConfig);
2574
2309
  }
2575
- missing.push(requiredAction);
2310
+ } catch {
2311
+ this.tracingEnabled = false;
2576
2312
  }
2577
- return {
2578
- valid: missing.length === 0,
2579
- missing
2580
- };
2581
- }
2582
- // Helper method to format workflow progress
2583
- formatProgress(state) {
2584
- const progressData = state.getProgressData();
2585
- return PromptUtils.formatWorkflowProgress(progressData);
2586
2313
  }
2587
- async execute(args, state) {
2588
- if (args.init) {
2589
- state.reset();
2590
- } else {
2591
- if (!state.isWorkflowInitialized() && !args.init) {
2592
- return {
2593
- content: [
2594
- {
2314
+ async runSamplingLoop(systemPrompt, schema, state) {
2315
+ this.conversationHistory = [
2316
+ {
2317
+ role: "user",
2318
+ content: {
2319
+ type: "text",
2320
+ text: 'Return ONE AND ONLY ONE raw JSON object (no code fences, explanations, or multiple objects). During execution provide: {"action":"<tool>","decision":"proceed|retry","<tool>":{}}. When complete provide: {"decision":"complete"}'
2321
+ }
2322
+ }
2323
+ ];
2324
+ const loopSpan = this.tracingEnabled ? startSpan("mcpc.sampling_loop", {
2325
+ agent: this.name,
2326
+ maxIterations: this.maxIterations,
2327
+ systemPrompt: systemPrompt()
2328
+ }) : null;
2329
+ try {
2330
+ for (this.currentIteration = 0; this.currentIteration < this.maxIterations; this.currentIteration++) {
2331
+ let iterationSpan = null;
2332
+ try {
2333
+ const response = await this.server.createMessage({
2334
+ systemPrompt: systemPrompt(),
2335
+ messages: this.conversationHistory,
2336
+ maxTokens: 55e3
2337
+ });
2338
+ const responseContent = response.content.text || "{}";
2339
+ const model = response.model;
2340
+ const stopReason = response.stopReason;
2341
+ const role = response.role;
2342
+ let parsedData;
2343
+ try {
2344
+ parsedData = parseJSON(responseContent.trim(), true);
2345
+ } catch (parseError) {
2346
+ iterationSpan = this.tracingEnabled ? startSpan("mcpc.sampling_iteration.parse_error", {
2347
+ iteration: this.currentIteration + 1,
2348
+ agent: this.name,
2349
+ error: String(parseError),
2350
+ maxIterations: this.maxIterations
2351
+ }, loopSpan ?? void 0) : null;
2352
+ this.addParsingErrorToHistory(responseContent, parseError);
2353
+ if (iterationSpan) endSpan(iterationSpan);
2354
+ continue;
2355
+ }
2356
+ this.conversationHistory.push({
2357
+ role: "assistant",
2358
+ content: {
2595
2359
  type: "text",
2596
- text: this.predefinedSteps ? WorkflowPrompts.ERRORS.NOT_INITIALIZED.WITH_PREDEFINED : WorkflowPrompts.ERRORS.NOT_INITIALIZED.WITHOUT_PREDEFINED
2360
+ text: JSON.stringify(parsedData, null, 2)
2597
2361
  }
2598
- ],
2599
- isError: true
2600
- };
2601
- }
2602
- const decision2 = args.decision;
2603
- if (decision2 === "proceed") {
2604
- if (state.isAtLastStep() && state.isWorkflowStarted()) {
2605
- state.markCompleted();
2606
- return {
2607
- content: [
2608
- {
2609
- type: "text",
2610
- text: `## Workflow Completed!
2611
-
2612
- ${this.formatProgress(state)}
2613
-
2614
- ${CompiledPrompts.workflowCompleted({
2615
- totalSteps: state.getSteps().length,
2616
- toolName: this.name,
2617
- newWorkflowInstructions: this.predefinedSteps ? "" : " and new `steps` array"
2618
- })}`
2619
- }
2620
- ],
2621
- isError: false
2622
- };
2623
- }
2624
- if (state.isCompleted()) {
2625
- return {
2626
- content: [
2627
- {
2362
+ });
2363
+ const action = parsedData["action"];
2364
+ const decision = parsedData["decision"];
2365
+ if (typeof decision !== "string") {
2366
+ this.conversationHistory.push({
2367
+ role: "user",
2368
+ content: {
2628
2369
  type: "text",
2629
- text: WorkflowPrompts.ERRORS.ALREADY_AT_FINAL
2370
+ text: 'Missing required field "decision". Provide: {"action":"<tool>","decision":"proceed|retry","<tool>":{}} or {"decision":"complete"}'
2630
2371
  }
2631
- ],
2632
- isError: true
2633
- };
2634
- }
2635
- const currentStepIndex = state.getCurrentStepIndex();
2636
- const wasStarted = state.isWorkflowStarted();
2637
- if (state.isWorkflowStarted()) {
2638
- state.moveToNextStep();
2639
- } else {
2640
- state.start();
2641
- }
2642
- const nextStepValidationSchema = this.createArgsDef.forCurrentState(state);
2643
- const nextStepValidationResult = this.validate(args, nextStepValidationSchema);
2644
- if (!nextStepValidationResult.valid) {
2645
- if (wasStarted) {
2646
- state.moveToStep(currentStepIndex);
2647
- } else {
2648
- state.moveToStep(currentStepIndex);
2372
+ });
2373
+ if (iterationSpan) endSpan(iterationSpan);
2374
+ continue;
2649
2375
  }
2650
- return {
2651
- content: [
2652
- {
2376
+ if (decision === "complete" && action) {
2377
+ this.conversationHistory.push({
2378
+ role: "user",
2379
+ content: {
2653
2380
  type: "text",
2654
- text: CompiledPrompts.workflowErrorResponse({
2655
- errorMessage: `Cannot proceed to next step: ${nextStepValidationResult.error || "Arguments validation failed"}`
2656
- })
2381
+ text: 'Invalid: Cannot have both "decision":"complete" and "action" field. When complete, only provide {"decision":"complete"}.'
2657
2382
  }
2658
- ],
2659
- isError: true
2660
- };
2661
- }
2662
- } else if (decision2 === "complete") {
2663
- if (state.isAtLastStep() && state.isWorkflowStarted()) {
2664
- state.markCompleted();
2665
- return {
2666
- content: [
2667
- {
2383
+ });
2384
+ if (iterationSpan) endSpan(iterationSpan);
2385
+ continue;
2386
+ }
2387
+ if (decision !== "complete" && !action) {
2388
+ this.conversationHistory.push({
2389
+ role: "user",
2390
+ content: {
2668
2391
  type: "text",
2669
- text: `## Workflow Completed!
2670
-
2671
- ${this.formatProgress(state)}
2672
-
2673
- ${CompiledPrompts.workflowCompleted({
2674
- totalSteps: state.getSteps().length,
2675
- toolName: this.name,
2676
- newWorkflowInstructions: this.predefinedSteps ? "" : " and new `steps` array"
2677
- })}`
2392
+ text: 'Missing required field "action". When executing, provide: {"action":"<tool>","decision":"proceed|retry","<tool>":{}}'
2678
2393
  }
2679
- ],
2680
- isError: false
2681
- };
2682
- } else {
2683
- return {
2684
- content: [
2685
- {
2394
+ });
2395
+ if (iterationSpan) endSpan(iterationSpan);
2396
+ continue;
2397
+ }
2398
+ const actionStr = decision === "complete" ? "completion" : action && typeof action === "string" ? String(action) : "unknown_action";
2399
+ const spanName = `mcpc.sampling_iteration.${actionStr}`;
2400
+ iterationSpan = this.tracingEnabled ? startSpan(spanName, {
2401
+ iteration: this.currentIteration + 1,
2402
+ agent: this.name,
2403
+ action: actionStr,
2404
+ systemPrompt: systemPrompt(),
2405
+ maxTokens: String(Number.MAX_SAFE_INTEGER),
2406
+ maxIterations: this.maxIterations,
2407
+ messages: JSON.stringify(this.conversationHistory)
2408
+ }, loopSpan ?? void 0) : null;
2409
+ const result = await this.processAction(parsedData, schema, state, iterationSpan);
2410
+ this.logIterationProgress(parsedData, result, model, stopReason, role);
2411
+ if (iterationSpan) {
2412
+ let rawJson = "{}";
2413
+ try {
2414
+ rawJson = parsedData ? JSON.stringify(parsedData) : "{}";
2415
+ } catch {
2416
+ }
2417
+ const attr = {
2418
+ isError: !!result.isError,
2419
+ isComplete: !!result.isComplete,
2420
+ iteration: this.currentIteration + 1,
2421
+ maxIterations: this.maxIterations,
2422
+ parsed: rawJson,
2423
+ action: typeof action === "string" ? action : String(action),
2424
+ decision: typeof decision === "string" ? decision : String(decision),
2425
+ samplingResponse: responseContent,
2426
+ toolResult: JSON.stringify(result),
2427
+ model,
2428
+ role
2429
+ };
2430
+ if (stopReason) {
2431
+ attr.stopReason = stopReason;
2432
+ }
2433
+ iterationSpan.setAttributes(attr);
2434
+ }
2435
+ if (result.isError) {
2436
+ this.conversationHistory.push({
2437
+ role: "user",
2438
+ content: {
2686
2439
  type: "text",
2687
- text: WorkflowPrompts.ERRORS.CANNOT_COMPLETE_NOT_AT_FINAL
2440
+ text: result.content[0].text
2688
2441
  }
2689
- ],
2690
- isError: true
2691
- };
2442
+ });
2443
+ if (iterationSpan) endSpan(iterationSpan);
2444
+ continue;
2445
+ }
2446
+ if (result.isComplete) {
2447
+ if (iterationSpan) endSpan(iterationSpan);
2448
+ if (loopSpan) endSpan(loopSpan);
2449
+ return result;
2450
+ }
2451
+ if (iterationSpan) endSpan(iterationSpan);
2452
+ } catch (iterError) {
2453
+ if (iterationSpan) endSpan(iterationSpan, iterError);
2454
+ throw iterError;
2692
2455
  }
2693
2456
  }
2457
+ if (loopSpan) endSpan(loopSpan);
2458
+ return await this.createMaxIterationsError(loopSpan);
2459
+ } catch (error) {
2460
+ if (loopSpan) endSpan(loopSpan, error);
2461
+ return await this.createExecutionError(error, loopSpan);
2462
+ }
2463
+ }
2464
+ addParsingErrorToHistory(_responseText, parseError) {
2465
+ const errorMsg = parseError instanceof Error ? parseError.message : String(parseError);
2466
+ this.conversationHistory.push({
2467
+ role: "user",
2468
+ content: {
2469
+ type: "text",
2470
+ text: `Invalid JSON: ${errorMsg}
2471
+
2472
+ Respond with valid JSON.`
2473
+ }
2474
+ });
2475
+ }
2476
+ async createMaxIterationsError(parentSpan) {
2477
+ const result = await this.createCompletionResult(`Reached max iterations (${this.maxIterations}). Try a more specific request.`, parentSpan);
2478
+ result.isError = true;
2479
+ result.isComplete = false;
2480
+ return result;
2481
+ }
2482
+ async createExecutionError(error, parentSpan) {
2483
+ const result = await this.createCompletionResult(`Execution error: ${error instanceof Error ? error.message : String(error)}`, parentSpan);
2484
+ result.isError = true;
2485
+ result.isComplete = false;
2486
+ return result;
2487
+ }
2488
+ async createCompletionResult(text, parentSpan) {
2489
+ const summary = this.summarize ? await this.summarizeConversation(parentSpan) : this.formatConversation();
2490
+ return {
2491
+ content: [
2492
+ {
2493
+ type: "text",
2494
+ text: `${text}
2495
+
2496
+ **Execution Summary:**
2497
+ - Iterations used: ${this.currentIteration + 1}/${this.maxIterations}
2498
+ - Agent: ${this.name}
2499
+ ${summary}`
2500
+ }
2501
+ ],
2502
+ isError: false,
2503
+ isComplete: true
2504
+ };
2505
+ }
2506
+ // Use LLM to create high-signal summary for parent agent
2507
+ async summarizeConversation(parentSpan) {
2508
+ if (this.conversationHistory.length === 0) {
2509
+ return "\n\n**No conversation history**";
2510
+ }
2511
+ if (this.conversationHistory.length <= 3) {
2512
+ return this.formatConversation();
2694
2513
  }
2695
- const decision = args.decision;
2696
- if (decision !== "proceed") {
2697
- const validationSchema = this.createArgsDef.forCurrentState(state);
2698
- const validationResult = this.validate(args, validationSchema);
2699
- if (!validationResult.valid) {
2700
- return {
2701
- content: [
2702
- {
2514
+ const summarizeSpan = this.tracingEnabled ? startSpan("mcpc.sampling_summarize", {
2515
+ agent: this.name,
2516
+ messageCount: this.conversationHistory.length
2517
+ }, parentSpan ?? void 0) : null;
2518
+ try {
2519
+ this.logger.debug({
2520
+ message: "Starting conversation summarization",
2521
+ messageCount: this.conversationHistory.length
2522
+ });
2523
+ const history = this.conversationHistory.map((msg, i) => {
2524
+ const prefix = `[${i + 1}] ${msg.role.toUpperCase()}`;
2525
+ return `${prefix}:
2526
+ ${msg.content.text}`;
2527
+ }).join("\n\n---\n\n");
2528
+ const response = await this.server.createMessage({
2529
+ systemPrompt: `Summarize this agent execution:
2530
+
2531
+ Final Decision: (include complete JSON if present)
2532
+ Key Findings: (most important)
2533
+ Actions Taken: (high-level flow)
2534
+ Errors/Warnings: (if any)
2535
+
2536
+ ${history}`,
2537
+ messages: [
2538
+ {
2539
+ role: "user",
2540
+ content: {
2703
2541
  type: "text",
2704
- text: CompiledPrompts.workflowErrorResponse({
2705
- errorMessage: validationResult.error || "Arguments validation failed"
2706
- })
2542
+ text: "Please provide a concise summary."
2707
2543
  }
2708
- ],
2709
- isError: true
2710
- };
2544
+ }
2545
+ ],
2546
+ maxTokens: 3e3
2547
+ });
2548
+ const summary = "\n\n" + response.content.text;
2549
+ this.logger.debug({
2550
+ message: "Summarization completed",
2551
+ summaryLength: summary.length
2552
+ });
2553
+ if (summarizeSpan) {
2554
+ summarizeSpan.setAttributes({
2555
+ summaryLength: summary.length,
2556
+ summary,
2557
+ success: true
2558
+ });
2559
+ endSpan(summarizeSpan);
2711
2560
  }
2561
+ return summary;
2562
+ } catch (error) {
2563
+ this.logger.warning({
2564
+ message: "Summarization failed, falling back to full history",
2565
+ error: String(error)
2566
+ });
2567
+ if (summarizeSpan) {
2568
+ endSpan(summarizeSpan, error);
2569
+ }
2570
+ return this.formatConversation();
2712
2571
  }
2713
- if (args.init) {
2714
- return this.initialize(args, state);
2715
- }
2716
- return await this.executeStep(args, state);
2717
2572
  }
2718
- initialize(args, state) {
2719
- const steps = args.steps ?? this.predefinedSteps;
2720
- if (!steps || steps.length === 0) {
2721
- return {
2722
- content: [
2723
- {
2724
- type: "text",
2725
- text: WorkflowPrompts.ERRORS.NO_STEPS_PROVIDED
2726
- }
2727
- ],
2728
- isError: true
2729
- };
2573
+ // Format full conversation history (for debugging)
2574
+ formatConversation() {
2575
+ if (this.conversationHistory.length === 0) {
2576
+ return "\n\n**No conversation history**";
2730
2577
  }
2731
- const validation = this.validateRequiredActions(steps);
2732
- if (!validation.valid) {
2733
- return {
2734
- content: [
2735
- {
2736
- type: "text",
2737
- text: `## Workflow Validation Failed \u274C
2578
+ const messages = this.conversationHistory.map((msg, i) => {
2579
+ const header = `### Message ${i + 1}: ${msg.role}`;
2580
+ try {
2581
+ const parsed = JSON.parse(msg.content.text);
2582
+ if (JSON.stringify(parsed).length < 100) {
2583
+ return `${header}
2584
+ ${JSON.stringify(parsed)}`;
2585
+ }
2586
+ return `${header}
2587
+ \`\`\`json
2588
+ ${JSON.stringify(parsed, null, 2)}
2589
+ \`\`\``;
2590
+ } catch {
2591
+ return `${header}
2592
+ ${msg.content.text}`;
2593
+ }
2594
+ });
2595
+ return "\n\n**Conversation History:**\n" + messages.join("\n\n");
2596
+ }
2597
+ logIterationProgress(parsedData, result, model, stopReason, role) {
2598
+ this.logger.debug({
2599
+ iteration: `${this.currentIteration + 1}/${this.maxIterations}`,
2600
+ parsedData,
2601
+ isError: result.isError,
2602
+ isComplete: result.isComplete,
2603
+ model,
2604
+ stopReason,
2605
+ role,
2606
+ result
2607
+ });
2608
+ }
2609
+ injectJsonInstruction({ prompt, schema, schemaPrefix = "JSON schema:", schemaSuffix = `STRICT REQUIREMENTS:
2610
+ 1. Return ONE AND ONLY ONE raw JSON object that passes JSON.parse() - no markdown, code blocks, explanatory text, or multiple JSON objects
2611
+ 2. Include ALL required fields with correct data types and satisfy ALL schema constraints (anyOf, oneOf, allOf, not, enum, pattern, min/max, conditionals)
2612
+ 3. Your response must be a single JSON object, nothing else
2738
2613
 
2739
- **Missing Required Actions:** The following actions must be included in the workflow steps:
2614
+ INVALID: \`\`\`json{"key":"value"}\`\`\` or "Here is: {"key":"value"}" or {"key":"value"}{"key":"value"}
2615
+ VALID: {"key":"value"}` }) {
2616
+ return [
2617
+ prompt != null && prompt.length > 0 ? prompt : void 0,
2618
+ prompt != null && prompt.length > 0 ? "" : void 0,
2619
+ schemaPrefix,
2620
+ schema != null ? JSON.stringify(schema, null, 2) : void 0,
2621
+ schemaSuffix
2622
+ ].filter((line) => line != null).join("\n");
2623
+ }
2624
+ // Validate arguments using JSON schema
2625
+ validateInput(args, schema) {
2626
+ return validateSchema(args, schema);
2627
+ }
2628
+ };
2740
2629
 
2741
- ${validation.missing.map((action) => `- \`${this.toolNameToIdMapping?.get(action) ?? action}\``).join("\n")}`
2742
- }
2743
- ],
2744
- isError: true
2745
- };
2746
- }
2747
- state.initialize(steps);
2748
- return {
2749
- content: [
2750
- {
2751
- type: "text",
2752
- text: `## Workflow Initialized
2753
- ${this.formatProgress(state)}
2754
- ${this.createArgsDef.forInitialStepDescription(steps, state)}`
2630
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/sampling/agentic-sampling-executor.js
2631
+ var SamplingExecutor = class extends BaseSamplingExecutor {
2632
+ agenticExecutor;
2633
+ constructor(name, description, allToolNames, toolNameToDetailList, server2, config2) {
2634
+ super(name, description, allToolNames, toolNameToDetailList, server2, config2);
2635
+ this.agenticExecutor = new AgenticExecutor(name, allToolNames, toolNameToDetailList, server2);
2636
+ }
2637
+ buildDepGroups() {
2638
+ const depGroups = {};
2639
+ this.toolNameToDetailList.forEach(([toolName, tool]) => {
2640
+ if (tool?.inputSchema) {
2641
+ depGroups[toolName] = {
2642
+ type: "object",
2643
+ description: tool.description || `Tool: ${toolName}`,
2644
+ ...tool.inputSchema
2645
+ };
2646
+ } else {
2647
+ const toolSchema = this.server.getHiddenToolSchema(toolName);
2648
+ if (toolSchema) {
2649
+ depGroups[toolName] = {
2650
+ ...toolSchema.schema,
2651
+ description: toolSchema.description
2652
+ };
2755
2653
  }
2756
- ],
2757
- isError: false
2758
- };
2654
+ }
2655
+ });
2656
+ return depGroups;
2759
2657
  }
2760
- async executeStep(args, state) {
2761
- const currentStep = state.getCurrentStep();
2762
- if (!currentStep) {
2658
+ executeSampling(args, schema) {
2659
+ const validationResult = validateSchema(args, schema);
2660
+ if (!validationResult.valid) {
2763
2661
  return {
2764
2662
  content: [
2765
2663
  {
2766
2664
  type: "text",
2767
- text: WorkflowPrompts.ERRORS.NO_CURRENT_STEP
2665
+ text: CompiledPrompts.errorResponse({
2666
+ errorMessage: validationResult.error || "Validation failed"
2667
+ })
2768
2668
  }
2769
2669
  ],
2770
2670
  isError: true
2771
2671
  };
2772
2672
  }
2773
- state.markCurrentStepRunning();
2774
- const results = {
2775
- content: [],
2776
- isError: false
2777
- };
2778
- for (const action of currentStep.actions) {
2779
- try {
2780
- const actionArgs = args[action] || {};
2781
- const actionResult = await this.server.callTool(action, actionArgs);
2782
- if (!results.isError) {
2783
- results.isError = actionResult.isError;
2784
- }
2785
- results.content = results.content.concat(actionResult.content ?? []);
2786
- results.content.push({
2787
- type: "text",
2788
- text: `Action \`${action}\` executed ${actionResult.isError ? "\u274C **FAILED**" : "\u2705 **SUCCESS**"}:`
2789
- });
2790
- } catch (error) {
2791
- results.content.push({
2792
- type: "text",
2793
- text: `${error.message}`
2794
- });
2795
- results.content.push({
2796
- type: "text",
2797
- text: `Action \`${action}\` \u274C **FAILED** with error: `
2798
- });
2799
- results.isError = true;
2800
- }
2801
- }
2802
- if (results.isError) {
2803
- state.markCurrentStepFailed("Step execution failed");
2804
- } else {
2805
- state.markCurrentStepCompleted("Step completed successfully");
2806
- }
2807
- if (state.hasNextStep()) {
2808
- const nextStepArgsDef = this.createArgsDef.forNextState(state);
2809
- results.content.push({
2810
- type: "text",
2811
- text: CompiledPrompts.nextStepDecision({
2812
- toolName: this.name,
2813
- nextStepDescription: state.getNextStep()?.description || "Unknown step",
2814
- nextStepSchema: JSON.stringify(nextStepArgsDef, null, 2)
2815
- })
2816
- });
2817
- } else {
2818
- results.content.push({
2819
- type: "text",
2820
- text: CompiledPrompts.finalStepCompletion({
2821
- statusIcon: results.isError ? "\u274C" : "\u2705",
2822
- statusText: results.isError ? "with errors" : "successfully",
2823
- toolName: this.name,
2824
- newWorkflowInstructions: this.predefinedSteps ? "" : " and new `steps` array"
2825
- })
2673
+ const createArgsDef = createArgsDefFactory(this.name, this.allToolNames, this.buildDepGroups(), void 0, void 0);
2674
+ const agenticSchema = createArgsDef.forAgentic(this.toolNameToDetailList, true);
2675
+ const systemPrompt = this.buildSystemPrompt(args.userRequest, agenticSchema, args.context && typeof args.context === "object" ? args.context : void 0);
2676
+ return this.runSamplingLoop(() => systemPrompt, agenticSchema);
2677
+ }
2678
+ async processAction(parsedData, schema, _state, parentSpan) {
2679
+ const toolCallData = parsedData;
2680
+ if (toolCallData.decision === "complete") {
2681
+ return await this.createCompletionResult("Task completed", parentSpan);
2682
+ }
2683
+ try {
2684
+ const { action: _action, decision: _decision, ..._toolArgs } = toolCallData;
2685
+ const toolResult = await this.agenticExecutor.execute(toolCallData, schema, parentSpan);
2686
+ const resultText = toolResult.content?.filter((content) => content.type === "text")?.map((content) => content.text)?.join("\n") || "No result";
2687
+ this.conversationHistory.push({
2688
+ role: "assistant",
2689
+ content: {
2690
+ type: "text",
2691
+ text: resultText
2692
+ }
2826
2693
  });
2694
+ return toolResult;
2695
+ } catch (error) {
2696
+ return this.createExecutionError(error, parentSpan);
2827
2697
  }
2828
- results.content.push({
2829
- type: "text",
2830
- text: `## Workflow Progress
2831
- ${this.formatProgress(state)}`
2832
- });
2833
- return results;
2834
2698
  }
2835
- // Validate arguments using JSON schema
2836
- validate(args, schema) {
2837
- const validate = ajv3.compile(schema);
2838
- if (!validate(args)) {
2839
- const errors = new AggregateAjvError3(validate.errors);
2840
- return {
2841
- valid: false,
2842
- error: errors.message
2843
- };
2699
+ buildSystemPrompt(userRequest, agenticSchema, context2) {
2700
+ const toolList = this.allToolNames.map((name) => {
2701
+ const tool = this.toolNameToDetailList.find(([toolName]) => toolName === name);
2702
+ const toolSchema = this.server.getHiddenToolSchema(name);
2703
+ if (tool && tool[1]) {
2704
+ return `- ${name}: ${tool[1].description || `Tool: ${name}`}`;
2705
+ } else if (toolSchema) {
2706
+ return `- ${name}: ${toolSchema.description}`;
2707
+ }
2708
+ return `- ${name}`;
2709
+ }).join("\n");
2710
+ let contextInfo = "";
2711
+ if (context2 && typeof context2 === "object" && Object.keys(context2).length > 0) {
2712
+ contextInfo = `
2713
+
2714
+ Context:
2715
+ ${JSON.stringify(context2, null, 2)}`;
2844
2716
  }
2845
- return {
2846
- valid: true
2847
- };
2717
+ const basePrompt = CompiledPrompts.samplingExecution({
2718
+ toolName: this.name,
2719
+ description: this.description,
2720
+ toolList
2721
+ });
2722
+ const taskPrompt = `
2723
+
2724
+ ## Current Task
2725
+ You will now use agentic sampling to complete the following task: "${userRequest}"${contextInfo}
2726
+
2727
+ When you need to use a tool, specify the tool name in 'action' and provide tool-specific parameters as additional properties.`;
2728
+ return this.injectJsonInstruction({
2729
+ prompt: basePrompt + taskPrompt,
2730
+ schema: agenticSchema
2731
+ });
2848
2732
  }
2849
2733
  };
2850
2734
 
2735
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/agentic/agentic-sampling-registrar.js
2736
+ function registerAgenticSamplingTool(server2, { description, name, allToolNames, depGroups, toolNameToDetailList, samplingConfig }) {
2737
+ const createArgsDef = createArgsDefFactory(name, allToolNames, depGroups, void 0, void 0);
2738
+ const samplingExecutor = new SamplingExecutor(name, description, allToolNames, toolNameToDetailList, server2, samplingConfig);
2739
+ description = CompiledPrompts.samplingExecution({
2740
+ toolName: name,
2741
+ description,
2742
+ toolList: allToolNames.map((name2) => `- ${name2}`).join("\n")
2743
+ });
2744
+ const argsDef = createArgsDef.forSampling();
2745
+ const schema = allToolNames.length > 0 ? argsDef : {
2746
+ type: "object",
2747
+ properties: {}
2748
+ };
2749
+ server2.tool(name, description, jsonSchema(createGoogleCompatibleJSONSchema(schema)), async (args) => {
2750
+ return await samplingExecutor.executeSampling(args, schema);
2751
+ });
2752
+ }
2753
+
2754
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/mode-agentic-sampling-plugin.js
2755
+ var createAgenticSamplingModePlugin = () => ({
2756
+ name: "mode-agentic-sampling",
2757
+ version: "1.0.0",
2758
+ // Only apply to agentic_sampling mode
2759
+ apply: "agentic_sampling",
2760
+ // Register the agent tool with sampling
2761
+ registerAgentTool: (context2) => {
2762
+ registerAgenticSamplingTool(context2.server, {
2763
+ description: context2.description,
2764
+ name: context2.name,
2765
+ allToolNames: context2.allToolNames,
2766
+ depGroups: context2.depGroups,
2767
+ toolNameToDetailList: context2.toolNameToDetailList,
2768
+ samplingConfig: context2.options.samplingConfig
2769
+ });
2770
+ }
2771
+ });
2772
+ var mode_agentic_sampling_plugin_default = createAgenticSamplingModePlugin();
2773
+
2851
2774
  // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/sampling/workflow-sampling-executor.js
2852
2775
  var WorkflowSamplingExecutor = class extends BaseSamplingExecutor {
2853
2776
  createArgsDef;
@@ -2858,7 +2781,7 @@ var WorkflowSamplingExecutor = class extends BaseSamplingExecutor {
2858
2781
  this.workflowExecutor = new WorkflowExecutor(name, allToolNames, toolNameToDetailList, createArgsDef, server2, predefinedSteps);
2859
2782
  }
2860
2783
  async executeWorkflowSampling(args, schema, state) {
2861
- const validationResult = this.validateSchema(args, schema);
2784
+ const validationResult = validateSchema(args, schema);
2862
2785
  if (!validationResult.valid) {
2863
2786
  return {
2864
2787
  content: [
@@ -2922,33 +2845,24 @@ Current Task: <user_request>${args.userRequest}</user_request>${contextInfo}`;
2922
2845
  }
2923
2846
  };
2924
2847
 
2925
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/workflow/workflow-tool-registrar.js
2926
- function registerAgenticWorkflowTool(server2, { description, name, allToolNames, depGroups, toolNameToDetailList, predefinedSteps, sampling = false, ensureStepActions, toolNameToIdMapping }) {
2848
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/workflow/workflow-sampling-registrar.js
2849
+ function registerWorkflowSamplingTool(server2, { description, name, allToolNames, depGroups, toolNameToDetailList, predefinedSteps, samplingConfig, ensureStepActions, toolNameToIdMapping: _toolNameToIdMapping }) {
2927
2850
  const createArgsDef = createArgsDefFactory(name, allToolNames, depGroups, predefinedSteps, ensureStepActions);
2928
- const isSamplingMode = sampling === true || typeof sampling === "object";
2929
- const samplingConfig = typeof sampling === "object" ? sampling : void 0;
2930
- const workflowExecutor = new WorkflowExecutor(name, allToolNames, toolNameToDetailList, createArgsDef, server2, predefinedSteps, ensureStepActions, toolNameToIdMapping);
2931
2851
  const workflowSamplingExecutor = new WorkflowSamplingExecutor(name, description, allToolNames, toolNameToDetailList, createArgsDef, server2, predefinedSteps, samplingConfig);
2932
2852
  const workflowState = new WorkflowState();
2933
- const planningInstructions = predefinedSteps ? "- Set `init: true` (steps are predefined)" : "- Set `init: true` and define complete `steps` array";
2934
- const baseDescription = isSamplingMode ? CompiledPrompts.samplingExecution({
2853
+ const baseDescription = CompiledPrompts.samplingExecution({
2935
2854
  toolName: name,
2936
2855
  description,
2937
2856
  toolList: allToolNames.map((name2) => `- ${name2}`).join("\n")
2938
- }) : CompiledPrompts.workflowExecution({
2939
- toolName: name,
2940
- description,
2941
- planningInstructions
2942
2857
  });
2943
- const argsDef = isSamplingMode ? createArgsDef.forSampling() : createArgsDef.forTool();
2944
- const toolDescription = isSamplingMode ? baseDescription : createArgsDef.forToolDescription(baseDescription, workflowState);
2945
- server2.tool(name, toolDescription, jsonSchema(createGoogleCompatibleJSONSchema(argsDef)), async (args) => {
2858
+ const argsDef = createArgsDef.forSampling();
2859
+ const schema = allToolNames.length > 0 ? argsDef : {
2860
+ type: "object",
2861
+ properties: {}
2862
+ };
2863
+ server2.tool(name, baseDescription, jsonSchema(createGoogleCompatibleJSONSchema(schema)), async (args) => {
2946
2864
  try {
2947
- if (isSamplingMode) {
2948
- return await workflowSamplingExecutor.executeWorkflowSampling(args, argsDef, workflowState);
2949
- } else {
2950
- return await workflowExecutor.execute(args, workflowState);
2951
- }
2865
+ return await workflowSamplingExecutor.executeWorkflowSampling(args, schema, workflowState);
2952
2866
  } catch (error) {
2953
2867
  workflowState.reset();
2954
2868
  return {
@@ -2964,52 +2878,48 @@ function registerAgenticWorkflowTool(server2, { description, name, allToolNames,
2964
2878
  });
2965
2879
  }
2966
2880
 
2967
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/tool-tag-processor.js
2968
- var ALL_TOOLS_PLACEHOLDER = "__ALL__";
2969
- function findToolId(toolName, tools, toolNameMapping) {
2970
- const mappedId = toolNameMapping?.get(toolName);
2971
- if (mappedId) {
2972
- return mappedId;
2881
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/mode-workflow-sampling-plugin.js
2882
+ var createWorkflowSamplingModePlugin = () => ({
2883
+ name: "mode-agentic-workflow-sampling",
2884
+ version: "1.0.0",
2885
+ // Only apply to agentic_workflow_sampling mode
2886
+ apply: "agentic_workflow_sampling",
2887
+ // Register the agent tool with sampling
2888
+ registerAgentTool: (context2) => {
2889
+ registerWorkflowSamplingTool(context2.server, {
2890
+ description: context2.description,
2891
+ name: context2.name,
2892
+ allToolNames: context2.allToolNames,
2893
+ depGroups: context2.depGroups,
2894
+ toolNameToDetailList: context2.toolNameToDetailList,
2895
+ predefinedSteps: context2.options.steps,
2896
+ samplingConfig: context2.options.samplingConfig,
2897
+ ensureStepActions: context2.options.ensureStepActions,
2898
+ toolNameToIdMapping: context2.toolNameToIdMapping
2899
+ });
2973
2900
  }
2974
- return Object.keys(tools).find((id) => {
2975
- const dotNotation = id.replace(/_/g, ".");
2976
- return toolName === id || toolName === dotNotation;
2977
- });
2978
- }
2979
- function processToolTags({ description, tagToResults, $, tools, toolOverrides, toolNameMapping }) {
2980
- tagToResults.tool.forEach((toolEl) => {
2981
- const toolName = toolEl.attribs.name;
2982
- if (!toolName || toolName.includes(ALL_TOOLS_PLACEHOLDER)) {
2983
- $(toolEl).remove();
2984
- return;
2985
- }
2986
- const override = toolOverrides.get(toolName);
2987
- if (override?.visibility?.hidden) {
2988
- $(toolEl).remove();
2989
- } else if (override?.visibility?.public) {
2990
- $(toolEl).replaceWith(`<tool name="${toolName}"/>`);
2991
- } else {
2992
- const toolId = findToolId(toolName, tools, toolNameMapping);
2993
- if (toolId) {
2994
- $(toolEl).replaceWith(`<action action="${toolId}"/>`);
2995
- } else {
2996
- $(toolEl).remove();
2997
- }
2998
- }
2999
- });
3000
- return $.root().html() ?? description;
3001
- }
2901
+ });
2902
+ var mode_workflow_sampling_plugin_default = createWorkflowSamplingModePlugin();
3002
2903
 
3003
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/compose.js
3004
- init_built_in();
3005
- init_logger();
2904
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/index.js
2905
+ function getBuiltInPlugins() {
2906
+ return [
2907
+ tool_name_mapping_plugin_default,
2908
+ config_plugin_default,
2909
+ mode_agentic_plugin_default,
2910
+ mode_workflow_plugin_default,
2911
+ mode_agentic_sampling_plugin_default,
2912
+ mode_workflow_sampling_plugin_default,
2913
+ logging_plugin_default
2914
+ ];
2915
+ }
3006
2916
 
3007
2917
  // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugin-utils.js
3008
2918
  var pluginCache = /* @__PURE__ */ new Map();
3009
2919
  function shouldApplyPlugin(plugin, mode) {
3010
2920
  if (!plugin.apply) return true;
3011
2921
  if (typeof plugin.apply === "string") {
3012
- return mode.includes(plugin.apply);
2922
+ return mode === plugin.apply;
3013
2923
  }
3014
2924
  if (typeof plugin.apply === "function") {
3015
2925
  try {
@@ -3059,7 +2969,7 @@ function isValidPlugin(plugin) {
3059
2969
  if (!p2.name || typeof p2.name !== "string" || p2.name.trim() === "") {
3060
2970
  return false;
3061
2971
  }
3062
- 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";
2972
+ const hasHook = typeof p2.configureServer === "function" || typeof p2.composeStart === "function" || typeof p2.transformTool === "function" || typeof p2.finalizeComposition === "function" || typeof p2.registerAgentTool === "function" || typeof p2.composeEnd === "function" || typeof p2.transformInput === "function" || typeof p2.transformOutput === "function" || typeof p2.dispose === "function";
3063
2973
  if (!hasHook) return false;
3064
2974
  if (p2.enforce && p2.enforce !== "pre" && p2.enforce !== "post") {
3065
2975
  return false;
@@ -3196,7 +3106,6 @@ function validatePlugins(plugins) {
3196
3106
  }
3197
3107
 
3198
3108
  // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/plugin-manager.js
3199
- init_logger();
3200
3109
  var PluginManager = class {
3201
3110
  server;
3202
3111
  plugins;
@@ -3344,6 +3253,29 @@ var PluginManager = class {
3344
3253
  }
3345
3254
  }
3346
3255
  }
3256
+ /**
3257
+ * Trigger registerAgentTool hook - allows plugins to register the main agent tool
3258
+ * Returns true if any plugin handled the registration
3259
+ */
3260
+ async triggerRegisterAgentTool(context2) {
3261
+ const registerPlugins = this.plugins.filter((p2) => p2.registerAgentTool && shouldApplyPlugin(p2, context2.mode));
3262
+ if (registerPlugins.length === 0) {
3263
+ return false;
3264
+ }
3265
+ const sortedPlugins = sortPluginsByOrder(registerPlugins).reverse();
3266
+ for (const plugin of sortedPlugins) {
3267
+ if (plugin.registerAgentTool) {
3268
+ try {
3269
+ await plugin.registerAgentTool(context2);
3270
+ return true;
3271
+ } catch (error) {
3272
+ const errorMsg = error instanceof Error ? error.message : String(error);
3273
+ await this.logger.error(`Plugin "${plugin.name}" registerAgentTool failed: ${errorMsg}`);
3274
+ }
3275
+ }
3276
+ }
3277
+ return false;
3278
+ }
3347
3279
  /**
3348
3280
  * Dispose all plugins and cleanup resources
3349
3281
  */
@@ -3363,7 +3295,6 @@ var PluginManager = class {
3363
3295
  };
3364
3296
 
3365
3297
  // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/tool-manager.js
3366
- init_schema();
3367
3298
  var ToolManager = class {
3368
3299
  toolRegistry = /* @__PURE__ */ new Map();
3369
3300
  toolConfigs = /* @__PURE__ */ new Map();
@@ -3572,9 +3503,103 @@ var ToolManager = class {
3572
3503
  }
3573
3504
  };
3574
3505
 
3506
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/schema.js
3507
+ import traverse from "json-schema-traverse";
3508
+ function updateRefPaths(schema, wrapperPath) {
3509
+ if (!schema || typeof schema !== "object") {
3510
+ return schema;
3511
+ }
3512
+ if (!wrapperPath || typeof wrapperPath !== "string") {
3513
+ throw new Error("wrapperPath must be a non-empty string");
3514
+ }
3515
+ const clonedSchema = JSON.parse(JSON.stringify(schema));
3516
+ try {
3517
+ traverse(clonedSchema, {
3518
+ allKeys: true,
3519
+ cb: function(schemaNode, _jsonPtr, _rootSchema, _parentJsonPtr, _parentKeyword, _parentSchema, _keyIndex) {
3520
+ if (schemaNode && typeof schemaNode === "object" && schemaNode.$ref) {
3521
+ const ref = schemaNode.$ref;
3522
+ if (ref.startsWith("#/properties/")) {
3523
+ const relativePath = ref.substring(13);
3524
+ schemaNode.$ref = `#/properties/${wrapperPath}/properties/${relativePath}`;
3525
+ } else if (ref === "#") {
3526
+ schemaNode.$ref = `#/properties/${wrapperPath}`;
3527
+ }
3528
+ }
3529
+ }
3530
+ });
3531
+ } catch (error) {
3532
+ console.warn(`Failed to traverse schema for path "${wrapperPath}":`, error);
3533
+ return clonedSchema;
3534
+ }
3535
+ return clonedSchema;
3536
+ }
3537
+
3538
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/compose-helpers.js
3539
+ async function processToolsWithPlugins(server2, _externalTools, mode) {
3540
+ const toolManager = server2.toolManager;
3541
+ const pluginManager = server2.pluginManager;
3542
+ for (const [toolId, toolData] of toolManager.getToolEntries()) {
3543
+ const defaultSchema = {
3544
+ type: "object",
3545
+ properties: {},
3546
+ additionalProperties: true
3547
+ };
3548
+ const tempTool = {
3549
+ name: toolId,
3550
+ description: toolData.description,
3551
+ inputSchema: toolData.schema || defaultSchema,
3552
+ execute: toolData.callback
3553
+ };
3554
+ const processedTool = await pluginManager.applyTransformToolHooks(tempTool, {
3555
+ toolName: toolId,
3556
+ server: server2,
3557
+ mode,
3558
+ originalTool: {
3559
+ ...tempTool
3560
+ },
3561
+ transformationIndex: 0
3562
+ });
3563
+ toolManager.registerTool(toolId, processedTool.description || toolData.description, processedTool.inputSchema, processedTool.execute);
3564
+ }
3565
+ }
3566
+ function buildDependencyGroups(toolNameToDetailList, hiddenToolNames, publicToolNames, server2) {
3567
+ const depGroups = {};
3568
+ const toolManager = server2.toolManager;
3569
+ toolNameToDetailList.forEach(([toolName, tool]) => {
3570
+ const resolvedName = toolManager.resolveToolName(toolName);
3571
+ if (hiddenToolNames.includes(resolvedName ?? "") || publicToolNames.includes(resolvedName ?? "")) {
3572
+ return;
3573
+ }
3574
+ if (!tool) {
3575
+ const allToolNames = [
3576
+ ...toolNameToDetailList.map(([n]) => n)
3577
+ ];
3578
+ throw new Error(`Action ${toolName} not found, available action list: ${allToolNames.join(", ")}`);
3579
+ }
3580
+ const baseSchema = tool.inputSchema.jsonSchema ?? tool.inputSchema ?? {
3581
+ type: "object",
3582
+ properties: {},
3583
+ required: []
3584
+ };
3585
+ const baseProperties = baseSchema.type === "object" && baseSchema.properties ? baseSchema.properties : {};
3586
+ const baseRequired = baseSchema.type === "object" && Array.isArray(baseSchema.required) ? baseSchema.required : [];
3587
+ const updatedProperties = updateRefPaths(baseProperties, toolName);
3588
+ const sanitizedKey = sanitizePropertyKey(toolName);
3589
+ depGroups[sanitizedKey] = {
3590
+ type: "object",
3591
+ description: tool.description,
3592
+ properties: updatedProperties,
3593
+ required: [
3594
+ ...baseRequired
3595
+ ],
3596
+ additionalProperties: false
3597
+ };
3598
+ });
3599
+ return depGroups;
3600
+ }
3601
+
3575
3602
  // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/compose.js
3576
- init_compose_helpers();
3577
- init_provider();
3578
3603
  var ALL_TOOLS_PLACEHOLDER2 = "__ALL__";
3579
3604
  var ComposableMCPServer = class extends Server {
3580
3605
  pluginManager;
@@ -3789,8 +3814,7 @@ var ComposableMCPServer = class extends Server {
3789
3814
  * Apply plugins to all tools in registry and handle visibility configurations
3790
3815
  */
3791
3816
  async processToolsWithPlugins(externalTools, mode) {
3792
- const { processToolsWithPlugins: processTools } = await Promise.resolve().then(() => (init_compose_helpers(), compose_helpers_exports));
3793
- await processTools(this, externalTools, mode);
3817
+ await processToolsWithPlugins(this, externalTools, mode);
3794
3818
  }
3795
3819
  /**
3796
3820
  * Dispose all plugins and cleanup resources
@@ -3798,6 +3822,13 @@ var ComposableMCPServer = class extends Server {
3798
3822
  async disposePlugins() {
3799
3823
  await this.pluginManager.dispose();
3800
3824
  }
3825
+ /**
3826
+ * Close the server and ensure all plugins are disposed
3827
+ */
3828
+ async close() {
3829
+ await this.disposePlugins();
3830
+ await super.close();
3831
+ }
3801
3832
  async compose(name, description, depsConfig = {
3802
3833
  mcpServers: {}
3803
3834
  }, options = {
@@ -3943,30 +3974,23 @@ var ComposableMCPServer = class extends Server {
3943
3974
  });
3944
3975
  const allToolNames = contextToolNames;
3945
3976
  const depGroups = buildDependencyGroups(toolNameToDetailList, hiddenToolNames, publicToolNames, this);
3946
- switch (options.mode ?? "agentic") {
3947
- case "agentic":
3948
- registerAgenticTool(this, {
3949
- description,
3950
- name,
3951
- allToolNames,
3952
- depGroups,
3953
- toolNameToDetailList,
3954
- sampling: options.sampling
3955
- });
3956
- break;
3957
- case "agentic_workflow":
3958
- registerAgenticWorkflowTool(this, {
3959
- description,
3960
- name,
3961
- allToolNames,
3962
- depGroups,
3963
- toolNameToDetailList,
3964
- predefinedSteps: options.steps,
3965
- sampling: options.sampling,
3966
- ensureStepActions: options.ensureStepActions,
3967
- toolNameToIdMapping
3968
- });
3969
- break;
3977
+ const mode = options.mode ?? "agentic";
3978
+ const context2 = {
3979
+ server: this,
3980
+ name,
3981
+ description,
3982
+ mode,
3983
+ allToolNames,
3984
+ toolNameToDetailList,
3985
+ depGroups,
3986
+ toolNameToIdMapping,
3987
+ publicToolNames,
3988
+ hiddenToolNames,
3989
+ options
3990
+ };
3991
+ const handled = await this.pluginManager.triggerRegisterAgentTool(context2);
3992
+ if (!handled) {
3993
+ throw new Error(`No plugin registered to handle execution mode "${mode}". Did you override the default mode plugin, but in the wrong way?`);
3970
3994
  }
3971
3995
  }
3972
3996
  };
@@ -3981,9 +4005,6 @@ if (isSCF()) {
3981
4005
  });
3982
4006
  }
3983
4007
 
3984
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/mod.js
3985
- init_json();
3986
-
3987
4008
  // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/set-up-mcp-compose.js
3988
4009
  function parseMcpcConfigs(conf) {
3989
4010
  const mcpcConfigs = conf ?? [];
@@ -4025,16 +4046,12 @@ async function mcpc(serverConf, composeConf, setupCallback) {
4025
4046
  return server2;
4026
4047
  }
4027
4048
 
4028
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/mod.js
4029
- init_schema();
4030
-
4031
4049
  // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/large-result.js
4032
4050
  import { mkdtemp, writeFile } from "node:fs/promises";
4033
4051
  import { join } from "node:path";
4034
4052
  import { tmpdir as tmpdir2 } from "node:os";
4035
4053
 
4036
4054
  // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/search-tool.js
4037
- init_schema();
4038
4055
  import rg from "@mcpc-tech/ripgrep-napi";
4039
4056
  import { tmpdir } from "node:os";
4040
4057
  import { resolve } from "node:path";