@mcpc-tech/core 0.3.17 → 0.3.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.mjs CHANGED
@@ -401,7 +401,7 @@ var require_parse = __commonJS({
401
401
  "use strict";
402
402
  var path = __require("path");
403
403
  var resolveCommand = require_resolveCommand();
404
- var escape2 = require_escape();
404
+ var escape = require_escape();
405
405
  var readShebang = require_readShebang();
406
406
  var isWin = process.platform === "win32";
407
407
  var isExecutableRegExp = /\.(?:com|exe)$/i;
@@ -425,8 +425,8 @@ var require_parse = __commonJS({
425
425
  if (parsed.options.forceShell || needsShell) {
426
426
  const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
427
427
  parsed.command = path.normalize(parsed.command);
428
- parsed.command = escape2.command(parsed.command);
429
- parsed.args = parsed.args.map((arg) => escape2.argument(arg, needsDoubleEscapeMetaChars));
428
+ parsed.command = escape.command(parsed.command);
429
+ parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));
430
430
  const shellCommand = [parsed.command].concat(parsed.args).join(" ");
431
431
  parsed.args = ["/d", "/s", "/c", `"${shellCommand}"`];
432
432
  parsed.command = process.env.comspec || "cmd.exe";
@@ -2771,15 +2771,15 @@ var $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => {
2771
2771
  }
2772
2772
  }
2773
2773
  const input = payload.value;
2774
- const isDate2 = input instanceof Date;
2775
- const isValidDate = isDate2 && !Number.isNaN(input.getTime());
2774
+ const isDate = input instanceof Date;
2775
+ const isValidDate = isDate && !Number.isNaN(input.getTime());
2776
2776
  if (isValidDate)
2777
2777
  return payload;
2778
2778
  payload.issues.push({
2779
2779
  expected: "date",
2780
2780
  code: "invalid_type",
2781
2781
  input,
2782
- ...isDate2 ? { received: "Invalid Date" } : {},
2782
+ ...isDate ? { received: "Invalid Date" } : {},
2783
2783
  inst
2784
2784
  });
2785
2785
  return payload;
@@ -3384,8 +3384,8 @@ var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => {
3384
3384
  }
3385
3385
  }
3386
3386
  if (def.rest) {
3387
- const rest2 = input.slice(items.length);
3388
- for (const el of rest2) {
3387
+ const rest = input.slice(items.length);
3388
+ for (const el of rest) {
3389
3389
  i++;
3390
3390
  const result = def.rest._zod.run({
3391
3391
  value: el,
@@ -5839,30 +5839,30 @@ var tupleProcessor = (schema, ctx, _json, params) => {
5839
5839
  ...params,
5840
5840
  path: [...params.path, prefixPath, i]
5841
5841
  }));
5842
- const rest2 = def.rest ? process2(def.rest, ctx, {
5842
+ const rest = def.rest ? process2(def.rest, ctx, {
5843
5843
  ...params,
5844
5844
  path: [...params.path, restPath, ...ctx.target === "openapi-3.0" ? [def.items.length] : []]
5845
5845
  }) : null;
5846
5846
  if (ctx.target === "draft-2020-12") {
5847
5847
  json2.prefixItems = prefixItems;
5848
- if (rest2) {
5849
- json2.items = rest2;
5848
+ if (rest) {
5849
+ json2.items = rest;
5850
5850
  }
5851
5851
  } else if (ctx.target === "openapi-3.0") {
5852
5852
  json2.items = {
5853
5853
  anyOf: prefixItems
5854
5854
  };
5855
- if (rest2) {
5856
- json2.items.anyOf.push(rest2);
5855
+ if (rest) {
5856
+ json2.items.anyOf.push(rest);
5857
5857
  }
5858
5858
  json2.minItems = prefixItems.length;
5859
- if (!rest2) {
5859
+ if (!rest) {
5860
5860
  json2.maxItems = prefixItems.length;
5861
5861
  }
5862
5862
  } else {
5863
5863
  json2.items = prefixItems;
5864
- if (rest2) {
5865
- json2.additionalItems = rest2;
5864
+ if (rest) {
5865
+ json2.additionalItems = rest;
5866
5866
  }
5867
5867
  }
5868
5868
  const { minimum, maximum } = schema._zod.bag;
@@ -6888,19 +6888,19 @@ var ZodTuple = /* @__PURE__ */ $constructor("ZodTuple", (inst, def) => {
6888
6888
  $ZodTuple.init(inst, def);
6889
6889
  ZodType.init(inst, def);
6890
6890
  inst._zod.processJSONSchema = (ctx, json2, params) => tupleProcessor(inst, ctx, json2, params);
6891
- inst.rest = (rest2) => inst.clone({
6891
+ inst.rest = (rest) => inst.clone({
6892
6892
  ...inst._zod.def,
6893
- rest: rest2
6893
+ rest
6894
6894
  });
6895
6895
  });
6896
6896
  function tuple(items, _paramsOrRest, _params) {
6897
6897
  const hasRest = _paramsOrRest instanceof $ZodType;
6898
6898
  const params = hasRest ? _params : _paramsOrRest;
6899
- const rest2 = hasRest ? _paramsOrRest : null;
6899
+ const rest = hasRest ? _paramsOrRest : null;
6900
6900
  return new ZodTuple({
6901
6901
  type: "tuple",
6902
6902
  items,
6903
- rest: rest2,
6903
+ rest,
6904
6904
  ...util_exports.normalizeParams(params)
6905
6905
  });
6906
6906
  }
@@ -11844,8 +11844,8 @@ var ZodTuple2 = class _ZodTuple extends ZodType2 {
11844
11844
  });
11845
11845
  return INVALID;
11846
11846
  }
11847
- const rest2 = this._def.rest;
11848
- if (!rest2 && ctx.data.length > this._def.items.length) {
11847
+ const rest = this._def.rest;
11848
+ if (!rest && ctx.data.length > this._def.items.length) {
11849
11849
  addIssueToContext(ctx, {
11850
11850
  code: ZodIssueCode2.too_big,
11851
11851
  maximum: this._def.items.length,
@@ -11872,10 +11872,10 @@ var ZodTuple2 = class _ZodTuple extends ZodType2 {
11872
11872
  get items() {
11873
11873
  return this._def.items;
11874
11874
  }
11875
- rest(rest2) {
11875
+ rest(rest) {
11876
11876
  return new _ZodTuple({
11877
11877
  ...this._def,
11878
- rest: rest2
11878
+ rest
11879
11879
  });
11880
11880
  }
11881
11881
  };
@@ -13058,11 +13058,11 @@ var Protocol = class {
13058
13058
  const controller = this._requestHandlerAbortControllers.get(notification.params.requestId);
13059
13059
  controller?.abort(notification.params.reason);
13060
13060
  }
13061
- _setupTimeout(messageId, timeout2, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) {
13061
+ _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) {
13062
13062
  this._timeoutInfo.set(messageId, {
13063
- timeoutId: setTimeout(onTimeout, timeout2),
13063
+ timeoutId: setTimeout(onTimeout, timeout),
13064
13064
  startTime: Date.now(),
13065
- timeout: timeout2,
13065
+ timeout,
13066
13066
  maxTotalTimeout,
13067
13067
  resetTimeoutOnProgress,
13068
13068
  onTimeout
@@ -13506,9 +13506,9 @@ var Protocol = class {
13506
13506
  options?.signal?.addEventListener("abort", () => {
13507
13507
  cancel(options?.signal?.reason);
13508
13508
  });
13509
- const timeout2 = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC;
13510
- const timeoutHandler = () => cancel(McpError.fromError(ErrorCode.RequestTimeout, "Request timed out", { timeout: timeout2 }));
13511
- this._setupTimeout(messageId, timeout2, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false);
13509
+ const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC;
13510
+ const timeoutHandler = () => cancel(McpError.fromError(ErrorCode.RequestTimeout, "Request timed out", { timeout }));
13511
+ this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false);
13512
13512
  const relatedTaskId = relatedTask?.taskId;
13513
13513
  if (relatedTaskId) {
13514
13514
  const responseResolver = (response) => {
@@ -14413,71 +14413,6 @@ var Server = class extends Protocol {
14413
14413
 
14414
14414
  // __mcpc__core_latest/node_modules/@jsr/mcpc__utils/src/json.js
14415
14415
  import { jsonrepair } from "jsonrepair";
14416
- function stripMarkdownAndText(text) {
14417
- text = text.trim();
14418
- text = text.replace(/^```(?:json)?\s*\n?/i, "");
14419
- text = text.replace(/\n?```\s*$/, "");
14420
- text = text.replace(/^(?:here is|here's|response|result|output|json):\s*/i, "");
14421
- const firstJsonIndex = text.search(/[\{\[]/);
14422
- if (firstJsonIndex >= 0) {
14423
- text = text.slice(firstJsonIndex);
14424
- let depth = 0;
14425
- let inString = false;
14426
- let escapeNext = false;
14427
- const startChar = text[0];
14428
- const endChar = startChar === "{" ? "}" : "]";
14429
- for (let i = 0; i < text.length; i++) {
14430
- const char = text[i];
14431
- if (escapeNext) {
14432
- escapeNext = false;
14433
- continue;
14434
- }
14435
- if (char === "\\") {
14436
- escapeNext = true;
14437
- continue;
14438
- }
14439
- if (char === '"' && !inString) {
14440
- inString = true;
14441
- continue;
14442
- }
14443
- if (char === '"' && inString) {
14444
- inString = false;
14445
- continue;
14446
- }
14447
- if (inString) continue;
14448
- if (char === startChar) {
14449
- depth++;
14450
- } else if (char === endChar) {
14451
- depth--;
14452
- if (depth === 0) {
14453
- return text.slice(0, i + 1);
14454
- }
14455
- }
14456
- }
14457
- }
14458
- return text.trim();
14459
- }
14460
- function parseJSON(text, throwError) {
14461
- try {
14462
- return JSON.parse(text);
14463
- } catch (_error) {
14464
- try {
14465
- const cleanedText = stripMarkdownAndText(text);
14466
- try {
14467
- return JSON.parse(cleanedText);
14468
- } catch {
14469
- const repairedText = jsonrepair(cleanedText);
14470
- console.warn(`Failed to parse JSON, cleaned and repaired. Original: ${text.slice(0, 100)}...`);
14471
- return JSON.parse(repairedText);
14472
- }
14473
- } catch (_repairError) {
14474
- if (throwError) {
14475
- throw new Error(`Failed to parse JSON after cleanup and repair. Original error: ${_error instanceof Error ? _error.message : String(_error)}`);
14476
- }
14477
- return null;
14478
- }
14479
- }
14480
- }
14481
14416
 
14482
14417
  // __mcpc__core_latest/node_modules/@jsr/mcpc__utils/src/ai.js
14483
14418
  var p = (template, options = {}) => {
@@ -15251,8 +15186,8 @@ import { PassThrough } from "node:stream";
15251
15186
 
15252
15187
  // __mcpc__core_latest/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js
15253
15188
  var ReadBuffer = class {
15254
- append(chunk2) {
15255
- this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk2]) : chunk2;
15189
+ append(chunk) {
15190
+ this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk;
15256
15191
  }
15257
15192
  readMessage() {
15258
15193
  if (!this._buffer) {
@@ -15351,8 +15286,8 @@ var StdioClientTransport = class {
15351
15286
  this._process.stdin?.on("error", (error2) => {
15352
15287
  this.onerror?.(error2);
15353
15288
  });
15354
- this._process.stdout?.on("data", (chunk2) => {
15355
- this._readBuffer.append(chunk2);
15289
+ this._process.stdout?.on("data", (chunk) => {
15290
+ this._readBuffer.append(chunk);
15356
15291
  this.processReadBuffer();
15357
15292
  });
15358
15293
  this._process.stdout?.on("error", (error2) => {
@@ -15461,7 +15396,7 @@ function createParser(callbacks) {
15461
15396
  const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks;
15462
15397
  let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = "";
15463
15398
  function feed(newChunk) {
15464
- const chunk2 = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk2}`);
15399
+ const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);
15465
15400
  for (const line of complete)
15466
15401
  parseLine(line);
15467
15402
  incompleteLine = incomplete, isFirstChunk = false;
@@ -15529,19 +15464,19 @@ function createParser(callbacks) {
15529
15464
  }
15530
15465
  return { feed, reset };
15531
15466
  }
15532
- function splitLines(chunk2) {
15467
+ function splitLines(chunk) {
15533
15468
  const lines = [];
15534
15469
  let incompleteLine = "", searchIndex = 0;
15535
- for (; searchIndex < chunk2.length; ) {
15536
- const crIndex = chunk2.indexOf("\r", searchIndex), lfIndex = chunk2.indexOf(`
15470
+ for (; searchIndex < chunk.length; ) {
15471
+ const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
15537
15472
  `, searchIndex);
15538
15473
  let lineEnd = -1;
15539
- if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? crIndex === chunk2.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {
15540
- incompleteLine = chunk2.slice(searchIndex);
15474
+ if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {
15475
+ incompleteLine = chunk.slice(searchIndex);
15541
15476
  break;
15542
15477
  } else {
15543
- const line = chunk2.slice(searchIndex, lineEnd);
15544
- lines.push(line), searchIndex = lineEnd + 1, chunk2[searchIndex - 1] === "\r" && chunk2[searchIndex] === `
15478
+ const line = chunk.slice(searchIndex, lineEnd);
15479
+ lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === `
15545
15480
  ` && searchIndex++;
15546
15481
  }
15547
15482
  }
@@ -16875,8 +16810,8 @@ var EventSourceParserStream = class extends TransformStream {
16875
16810
  onComment
16876
16811
  });
16877
16812
  },
16878
- transform(chunk2) {
16879
- parser.feed(chunk2);
16813
+ transform(chunk) {
16814
+ parser.feed(chunk);
16880
16815
  }
16881
16816
  });
16882
16817
  }
@@ -16984,14 +16919,14 @@ var StreamableHTTPClientTransport = class {
16984
16919
  * @param attempt Current reconnection attempt count for the specific stream
16985
16920
  * @returns Time to wait in milliseconds before next reconnection attempt
16986
16921
  */
16987
- _getNextReconnectionDelay(attempt2) {
16922
+ _getNextReconnectionDelay(attempt) {
16988
16923
  if (this._serverRetryMs !== void 0) {
16989
16924
  return this._serverRetryMs;
16990
16925
  }
16991
16926
  const initialDelay = this._reconnectionOptions.initialReconnectionDelay;
16992
16927
  const growFactor = this._reconnectionOptions.reconnectionDelayGrowFactor;
16993
16928
  const maxDelay = this._reconnectionOptions.maxReconnectionDelay;
16994
- return Math.min(initialDelay * Math.pow(growFactor, attempt2), maxDelay);
16929
+ return Math.min(initialDelay * Math.pow(growFactor, attempt), maxDelay);
16995
16930
  }
16996
16931
  /**
16997
16932
  * Schedule a reconnection attempt using server-provided retry interval or backoff
@@ -17005,13 +16940,13 @@ var StreamableHTTPClientTransport = class {
17005
16940
  this.onerror?.(new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`));
17006
16941
  return;
17007
16942
  }
17008
- const delay2 = this._getNextReconnectionDelay(attemptCount);
16943
+ const delay = this._getNextReconnectionDelay(attemptCount);
17009
16944
  this._reconnectionTimeout = setTimeout(() => {
17010
16945
  this._startOrAuthSse(options).catch((error2) => {
17011
16946
  this.onerror?.(new Error(`Failed to reconnect SSE stream: ${error2 instanceof Error ? error2.message : String(error2)}`));
17012
16947
  this._scheduleReconnection(options, attemptCount + 1);
17013
16948
  });
17014
- }, delay2);
16949
+ }, delay);
17015
16950
  }
17016
16951
  _handleSseStream(stream, options, isReconnectable) {
17017
16952
  if (!stream) {
@@ -17328,7 +17263,7 @@ var GEMINI_PREFERRED_FORMAT = process4.env.GEMINI_PREFERRED_FORMAT === "0" ? fal
17328
17263
  // __mcpc__core_latest/node_modules/@mcpc/core/src/utils/common/json.js
17329
17264
  import { jsonrepair as jsonrepair2 } from "jsonrepair";
17330
17265
  import { inspect } from "node:util";
17331
- function parseJSON2(text, throwError) {
17266
+ function parseJSON(text, throwError) {
17332
17267
  try {
17333
17268
  return JSON.parse(text);
17334
17269
  } catch (_error) {
@@ -17378,8 +17313,8 @@ var createModelCompatibleJSONSchema = (schema) => {
17378
17313
  ]);
17379
17314
  let cleanSchema = schema;
17380
17315
  if (GEMINI_PREFERRED_FORMAT) {
17381
- const { oneOf: _oneOf, allOf: _allOf, anyOf: _anyOf, ...rest2 } = schema;
17382
- cleanSchema = rest2;
17316
+ const { oneOf: _oneOf, allOf: _allOf, anyOf: _anyOf, ...rest } = schema;
17317
+ cleanSchema = rest;
17383
17318
  }
17384
17319
  const cleanRecursively = (obj) => {
17385
17320
  if (Array.isArray(obj)) {
@@ -17398,6 +17333,34 @@ var createModelCompatibleJSONSchema = (schema) => {
17398
17333
  };
17399
17334
  return cleanRecursively(cleanSchema);
17400
17335
  };
17336
+ var INTERNAL_SCHEMA_KEYS = /* @__PURE__ */ new Set([
17337
+ "$schema",
17338
+ "_originalName",
17339
+ "_type",
17340
+ "annotations"
17341
+ ]);
17342
+ var cleanToolSchema = (schema) => {
17343
+ const cleanRecursively = (obj) => {
17344
+ if (Array.isArray(obj)) {
17345
+ return obj.map(cleanRecursively);
17346
+ }
17347
+ if (obj && typeof obj === "object") {
17348
+ const record2 = obj;
17349
+ if ("jsonSchema" in record2 && typeof record2.jsonSchema === "object" && record2.jsonSchema !== null) {
17350
+ return cleanRecursively(record2.jsonSchema);
17351
+ }
17352
+ const result = {};
17353
+ for (const [key, value] of Object.entries(record2)) {
17354
+ if (!INTERNAL_SCHEMA_KEYS.has(key)) {
17355
+ result[key] = cleanRecursively(value);
17356
+ }
17357
+ }
17358
+ return result;
17359
+ }
17360
+ return obj;
17361
+ };
17362
+ return cleanRecursively(schema);
17363
+ };
17401
17364
 
17402
17365
  // __mcpc__core_latest/node_modules/@mcpc/core/src/utils/common/mcp.js
17403
17366
  import { cwd } from "node:process";
@@ -17746,14 +17709,14 @@ function createLogger(name, server) {
17746
17709
 
17747
17710
  // __mcpc__core_latest/node_modules/@mcpc/core/src/plugins/built-in/logging-plugin.js
17748
17711
  var createLoggingPlugin = (options = {}) => {
17749
- const { enabled = true, verbose = false, compact: compact2 = true } = options;
17712
+ const { enabled = true, verbose = false, compact = true } = options;
17750
17713
  return {
17751
17714
  name: "built-in-logging",
17752
17715
  version: "1.0.0",
17753
17716
  composeEnd: async (context2) => {
17754
17717
  if (!enabled) return;
17755
17718
  const logger2 = createLogger("mcpc.plugin.logging", context2.server);
17756
- if (compact2) {
17719
+ if (compact) {
17757
17720
  const pluginCount = context2.pluginNames.length;
17758
17721
  const { stats } = context2;
17759
17722
  await logger2.info(`[${context2.toolName}] ${pluginCount} plugins \u2022 ${stats.publicTools} public \u2022 ${stats.hiddenTools} hidden`);
@@ -17793,296 +17756,85 @@ var logging_plugin_default = createLoggingPlugin({
17793
17756
  var SystemPrompts = {
17794
17757
  /**
17795
17758
  * Base system prompt for autonomous MCP execution
17759
+ *
17760
+ * Uses simplified Unix-style interface:
17761
+ * - `tool` + `args` for clean, consistent structure
17762
+ * - `man` command for fetching tool schemas (like Unix manual)
17763
+ * - No `hasDefinitions` - trusts model's context memory
17796
17764
  */
17797
- 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.
17765
+ AUTONOMOUS_EXECUTION: `Agentic tool \`{toolName}\` that executes complex tasks by iteratively selecting and calling tools.
17798
17766
 
17799
- You must follow the <manual/>, obey the <execution_rules/>, and use the <call_format/>.
17767
+ You must follow the <manual/>, obey the <rules/>, and use the <format/>.
17800
17768
 
17801
17769
  <manual>
17802
17770
  {description}
17803
17771
  </manual>
17804
17772
 
17805
17773
  <parameters>
17806
- \`useTool\` - Which tool to execute this iteration
17807
- \`hasDefinitions\` - Tool names whose schemas you already have
17808
- \`definitionsOf\` - Tool names whose schemas you need
17774
+ \`tool\` - Which tool to execute: "man" to get schemas, or a tool name to execute
17775
+ \`args\` - For "man": array of tool names. For other tools: object with parameters.
17809
17776
  </parameters>
17810
17777
 
17811
- <execution_rules>
17812
- 1. **First call**: No tool definitions available\u2014you must request them via \`definitionsOf\`
17813
- 2. **When executing tools**: Must provide \`hasDefinitions\` with ALL tools you have schemas for (avoid duplicate requests and reduce tokens)
17814
- 3. **When requesting definitions**: Use \`definitionsOf\` to request tool schemas you need
17815
- 4. **Both together**: Execute tool AND request new definitions in one call for efficiency
17816
- 5. **Never request definitions you already have**
17817
- 6. **Select** one tool to execute per call using \`useTool\`
17818
- 7. **Provide** parameters matching the selected tool name
17819
- 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**
17820
- </execution_rules>
17778
+ <rules>
17779
+ 1. **First call**: Use \`man\` to get tool schemas you need
17780
+ 2. **Execute tools**: Use tool name in \`tool\` and parameters in \`args\`
17781
+ 3. **Parallel calls**: If your client supports it, call \`man\` and execute tools simultaneously
17782
+ 4. Note: You are an agent exposed as an MCP tool
17783
+ </rules>
17821
17784
 
17822
- <call_format>
17823
- Initial definition request:
17785
+ <format>
17786
+ Get tool schemas:
17824
17787
  \`\`\`json
17825
17788
  {
17826
- "hasDefinitions": [],
17827
- "definitionsOf": ["tool1", "tool2"]
17789
+ "tool": "man",
17790
+ "args": ["tool1", "tool2"]
17828
17791
  }
17829
17792
  \`\`\`
17830
17793
 
17831
- Execute tool + get new definitions:
17794
+ Execute a tool:
17832
17795
  \`\`\`json
17833
17796
  {
17834
- "useTool": "tool1",
17835
- "tool1": { /* parameters */ },
17836
- "hasDefinitions": ["tool1", "tool2"],
17837
- "definitionsOf": ["tool3"]
17797
+ "tool": "tool_name",
17798
+ "args": { /* tool parameters */ }
17838
17799
  }
17839
17800
  \`\`\`
17840
- </call_format>`,
17801
+ </format>`,
17841
17802
  /**
17842
- * Workflow execution system prompt
17843
- */
17844
- WORKFLOW_EXECUTION: `Workflow tool \`{toolName}\` that executes multi-step workflows. Use this when your task requires sequential steps.
17845
-
17846
- <manual>
17847
- {description}
17848
- </manual>
17849
-
17850
- <rules>
17851
- 1. First call: {planningInstructions}
17852
- 2. Subsequent calls: Provide only current step parameters
17853
- 3. Use \`decision: "proceed"\` to advance, \`"retry"\` to retry, \`"complete"\` when done
17854
- 4. Include \`steps\` ONLY with \`init: true\`, never during execution
17855
- </rules>`,
17856
- /**
17857
- * Tool-based execution system prompt for autonomous sampling mode with native tools
17858
- *
17859
- * Note: Used when client supports sampling.tools capability
17803
+ * Tool description for sampling tools (shown in MCP tools list)
17804
+ * Explains how to use prompt and context parameters
17860
17805
  */
17861
- SAMPLING_EXECUTION_TOOLS: `Agent \`{toolName}\` that completes tasks by calling tools.
17862
-
17863
- <manual>
17864
- {description}
17865
- </manual>
17866
-
17867
- <rules>
17868
- 1. Execute one action per iteration
17869
- 2. Adapt based on results from previous actions
17870
- 3. Continue until task is complete
17871
- </rules>
17806
+ SAMPLING_TOOL_DESCRIPTION: `Subagent tool \`{toolName}\` that executes complex tasks.
17872
17807
 
17873
- <tools>
17874
- {toolList}
17875
- </tools>`,
17876
- /**
17877
- * JSON-only execution system prompt for autonomous sampling mode
17878
- *
17879
- * Note: Sampling mode runs an internal LLM loop that autonomously calls tools until complete.
17880
- */
17881
- SAMPLING_EXECUTION: `Agent \`{toolName}\` that completes tasks by calling tools in an autonomous loop.
17808
+ You must follow the <manual/>, obey the <rules/>, and use the <format/>.
17882
17809
 
17883
17810
  <manual>
17884
17811
  {description}
17885
17812
  </manual>
17886
17813
 
17887
- <rules>
17888
- 1. **YOUR ENTIRE RESPONSE MUST BE A SINGLE JSON OBJECT** - no text before or after
17889
- 2. Execute one tool per iteration
17890
- 3. Specify which tool to use with \`useTool\`
17891
- 4. Adapt based on results from previous actions
17892
- 5. Continue until task is complete
17893
- </rules>
17894
-
17895
17814
  <format>
17896
- CORRECT:
17897
- \`\`\`json
17898
- {"useTool": "tool_name", "decision": "proceed", "tool_name": {...}}
17899
- \`\`\`
17900
-
17901
- WRONG - No explanations:
17902
- \`\`\`
17903
- I will list the directory
17904
- {"useTool": "list_directory", ...}
17905
- \`\`\`
17906
-
17907
- During execution:
17908
- \`\`\`json
17909
- {
17910
- "useTool": "tool_name",
17911
- "decision": "proceed",
17912
- "tool_name": { /* tool parameters */ }
17913
- }
17914
- \`\`\`
17915
-
17916
- When complete:
17917
- \`\`\`json
17918
- { "decision": "complete" }
17919
- \`\`\`
17920
-
17921
- Decisions:
17922
- - \`proceed\` = action succeeded, continue
17923
- - \`retry\` = action failed, try again
17924
- - \`complete\` = task finished
17815
+ \`prompt\` - The task to be completed (e.g., "organize my desktop files")
17816
+ \`context\` - Execution context object (e.g., { cwd: "/path/to/dir" })
17925
17817
  </format>
17926
17818
 
17927
- <tools>
17928
- {toolList}
17929
- </tools>`,
17930
- /**
17931
- * Tool description for sampling tools (shown in MCP tools list)
17932
- * Explains how to use userRequest and context parameters
17933
- */
17934
- SAMPLING_TOOL_DESCRIPTION: `Subagent tool \`{toolName}\` that executes complex tasks.
17935
-
17936
- <manual>
17937
- {description}
17938
- </manual>
17939
-
17940
- <rules>
17941
- Call this tool with:
17942
- - **userRequest**: The task you want completed (e.g., "organize my desktop files", "create a project structure")
17943
- - **context**: Relevant information needed for the task (e.g., working directory, file paths, preferences)
17944
- </rules>`,
17945
- /**
17946
- * Tool-based workflow execution system prompt for sampling mode with native tools
17947
- *
17948
- * Note: Used when client supports sampling.tools capability
17949
- */
17950
- SAMPLING_WORKFLOW_EXECUTION_TOOLS: `Workflow agent \`{toolName}\` that executes multi-step workflows.
17951
-
17952
- <manual>
17953
- {description}
17954
- </manual>
17955
-
17956
17819
  <rules>
17957
- 1. First iteration: Plan workflow and initialize
17958
- 2. Subsequent iterations: Execute current step
17959
- 3. Adapt based on step results
17960
- 4. Continue until all steps complete
17820
+ 1. Always provide both \`prompt\` and \`context\` parameters
17821
+ 2. \`prompt\` must be a clear, actionable description
17822
+ 3. \`context\` must include relevant environment info (e.g., working directory)
17961
17823
  </rules>`,
17962
17824
  /**
17963
- * Sampling workflow execution system prompt combining sampling with workflow capabilities
17964
- *
17965
- * Note: Sampling mode runs an internal LLM loop that autonomously executes workflows.
17825
+ * System prompt for AI sampling loop (ai_sampling/ai_acp modes)
17826
+ * Used inside the execution loop when AI calls native tools.
17827
+ * Note: Tool schemas are passed via AI SDK native tool calling, not in prompt.
17966
17828
  */
17967
- SAMPLING_WORKFLOW_EXECUTION: `Workflow agent \`{toolName}\` that executes multi-step workflows autonomously.
17829
+ AI_LOOP_SYSTEM: `Agent \`{toolName}\` that completes tasks by calling tools.
17968
17830
 
17969
17831
  <manual>
17970
17832
  {description}
17971
17833
  </manual>
17972
17834
 
17973
17835
  <rules>
17974
- 1. Return valid JSON only
17975
- 2. First iteration: Plan workflow and initialize with \`init: true\`
17976
- 3. Subsequent iterations: Execute current step
17977
- 4. Adapt based on step results
17978
- 5. Continue until all steps complete
17979
- </rules>
17980
-
17981
- <format>
17982
- Initialize workflow (first iteration):
17983
- \`\`\`json
17984
- {
17985
- "action": "{toolName}",
17986
- "init": true,
17987
- "steps": [/* workflow steps */]
17988
- }
17989
- \`\`\`
17990
-
17991
- Execute step (subsequent iterations):
17992
- \`\`\`json
17993
- {
17994
- "action": "{toolName}",
17995
- "decision": "proceed|retry",
17996
- /* step parameters */
17997
- }
17998
- \`\`\`
17999
-
18000
- Complete workflow (omit action):
18001
- \`\`\`json
18002
- { "decision": "complete" }
18003
- \`\`\`
18004
-
18005
- Decisions:
18006
- - \`proceed\` = step succeeded, next step
18007
- - \`retry\` = step failed, retry current
18008
- - \`complete\` = workflow finished
18009
-
18010
- Rules:
18011
- - Include \`steps\` ONLY with \`init: true\`
18012
- - Omit \`steps\` during step execution
18013
- - Use \`decision: "retry"\` for failed steps
18014
- </format>`
18015
- };
18016
- var WorkflowPrompts = {
18017
- /**
18018
- * Workflow initialization instructions
18019
- */
18020
- WORKFLOW_INIT: `Workflow initialized with {stepCount} steps. Execute step 1: \`{currentStepDescription}\`
18021
-
18022
- Schema: {schemaDefinition}
18023
-
18024
- Call \`{toolName}\` with:
18025
- - Parameters matching schema above
18026
- - \`decision: "proceed"\` to advance, \`"retry"\` to retry, \`"complete"\` when done
18027
- - Omit \`steps\` (only used with \`init: true\`)
18028
-
18029
- {workflowSteps}`,
18030
- /**
18031
- * Tool description enhancement for workflow mode
18032
- */
18033
- WORKFLOW_TOOL_DESCRIPTION: `{description}
18034
- {initTitle}
18035
- {ensureStepActions}
18036
- {schemaDefinition}`,
18037
- /**
18038
- * Planning instructions for predefined workflows
18039
- */
18040
- PREDEFINED_WORKFLOW_PLANNING: `- Set \`init: true\` (steps are predefined)`,
18041
- /**
18042
- * Planning instructions for dynamic workflows
18043
- */
18044
- DYNAMIC_WORKFLOW_PLANNING: `- Set \`init: true\` and define complete \`steps\` array`,
18045
- /**
18046
- * Next step decision prompt
18047
- */
18048
- NEXT_STEP_DECISION: `Previous step completed.
18049
-
18050
- Choose action:
18051
- - RETRY: Call \`{toolName}\` with \`decision: "retry"\`
18052
- - PROCEED: Call \`{toolName}\` with \`decision: "proceed"\` and parameters below
18053
-
18054
- Next: \`{nextStepDescription}\`
18055
- {nextStepSchema}
18056
-
18057
- (Omit \`steps\` parameter)`,
18058
- /**
18059
- * Final step completion prompt
18060
- */
18061
- FINAL_STEP_COMPLETION: `Final step executed {statusIcon} - {statusText}
18062
-
18063
- Choose:
18064
- - RETRY: \`decision: "retry"\`
18065
- - COMPLETE: \`decision: "complete"\`
18066
- - NEW: \`init: true\`{newWorkflowInstructions}`,
18067
- /**
18068
- * Workflow completion success message
18069
- */
18070
- WORKFLOW_COMPLETED: `Workflow completed ({totalSteps} steps)
18071
-
18072
- Start new workflow: \`{toolName}\` with \`init: true\`{newWorkflowInstructions}`,
18073
- /**
18074
- * Error messages
18075
- */
18076
- ERRORS: {
18077
- NOT_INITIALIZED: {
18078
- WITH_PREDEFINED: "Error: Workflow not initialized. Please provide 'init' parameter to start a new workflow.",
18079
- WITHOUT_PREDEFINED: "Error: Workflow not initialized. Please provide 'init' and 'steps' parameter to start a new workflow."
18080
- },
18081
- ALREADY_AT_FINAL: "Error: Cannot proceed, already at the final step.",
18082
- CANNOT_COMPLETE_NOT_AT_FINAL: "Error: Cannot complete workflow - you are not at the final step. Please use decision=proceed to continue to the next step.",
18083
- NO_STEPS_PROVIDED: "Error: No steps provided",
18084
- NO_CURRENT_STEP: "Error: No current step to execute"
18085
- }
17836
+ {rules}
17837
+ </rules>{context}`
18086
17838
  };
18087
17839
  var ResponseTemplates = {
18088
17840
  /**
@@ -18105,9 +17857,6 @@ Next: Execute \`{nextAction}\` by calling \`{toolName}\` again.`,
18105
17857
  ERROR_RESPONSE: `Validation failed: {errorMessage}
18106
17858
 
18107
17859
  Adjust parameters and retry.`,
18108
- WORKFLOW_ERROR_RESPONSE: `Step failed: {errorMessage}
18109
-
18110
- Fix parameters and call with \`decision: "retry"\``,
18111
17860
  /**
18112
17861
  * Completion message
18113
17862
  */
@@ -18126,78 +17875,16 @@ Fix parameters and call with \`decision: "retry"\``,
18126
17875
  };
18127
17876
  var CompiledPrompts = {
18128
17877
  autonomousExecution: p(SystemPrompts.AUTONOMOUS_EXECUTION),
18129
- workflowExecution: p(SystemPrompts.WORKFLOW_EXECUTION),
18130
- samplingExecution: p(SystemPrompts.SAMPLING_EXECUTION),
18131
- samplingExecutionTools: p(SystemPrompts.SAMPLING_EXECUTION_TOOLS),
18132
17878
  samplingToolDescription: p(SystemPrompts.SAMPLING_TOOL_DESCRIPTION),
18133
- samplingWorkflowExecution: p(SystemPrompts.SAMPLING_WORKFLOW_EXECUTION),
18134
- samplingWorkflowExecutionTools: p(SystemPrompts.SAMPLING_WORKFLOW_EXECUTION_TOOLS),
18135
- workflowInit: p(WorkflowPrompts.WORKFLOW_INIT),
18136
- workflowToolDescription: p(WorkflowPrompts.WORKFLOW_TOOL_DESCRIPTION),
18137
- nextStepDecision: p(WorkflowPrompts.NEXT_STEP_DECISION),
18138
- finalStepCompletion: p(WorkflowPrompts.FINAL_STEP_COMPLETION),
18139
- workflowCompleted: p(WorkflowPrompts.WORKFLOW_COMPLETED),
17879
+ aiLoopSystem: p(SystemPrompts.AI_LOOP_SYSTEM),
18140
17880
  actionSuccess: p(ResponseTemplates.ACTION_SUCCESS),
18141
17881
  planningPrompt: p(ResponseTemplates.PLANNING_PROMPT),
18142
17882
  errorResponse: p(ResponseTemplates.ERROR_RESPONSE),
18143
- workflowErrorResponse: p(ResponseTemplates.WORKFLOW_ERROR_RESPONSE),
18144
17883
  securityPassed: p(ResponseTemplates.SECURITY_VALIDATION.PASSED),
18145
17884
  securityFailed: p(ResponseTemplates.SECURITY_VALIDATION.FAILED),
18146
17885
  auditLog: p(ResponseTemplates.AUDIT_LOG),
18147
17886
  completionMessage: () => ResponseTemplates.COMPLETION_MESSAGE
18148
17887
  };
18149
- var PromptUtils = {
18150
- /**
18151
- * Generate tool list for descriptions
18152
- */
18153
- generateToolList: (tools) => {
18154
- return tools.filter((tool2) => !tool2.hide).map((tool2) => `<tool name="${tool2.name}"${tool2.description ? ` description="${tool2.description}"` : ""}/>`).join("\n");
18155
- },
18156
- /**
18157
- * Generate hidden tool list for descriptions
18158
- */
18159
- generateHiddenToolList: (tools) => {
18160
- return tools.filter((tool2) => tool2.hide).map((tool2) => `<tool name="${tool2.name}" hide/>`).join("\n");
18161
- },
18162
- /**
18163
- * Format workflow steps for display
18164
- */
18165
- formatWorkflowSteps: (steps) => {
18166
- if (!steps.length) return "";
18167
- return `## Workflow Steps
18168
- ${JSON.stringify(steps, null, 2)}`;
18169
- },
18170
- /**
18171
- * Format workflow progress display with status icons
18172
- */
18173
- formatWorkflowProgress: (progressData) => {
18174
- const statusIcons = {
18175
- pending: "[PENDING]",
18176
- running: "[RUNNING]",
18177
- completed: "[DONE]",
18178
- failed: "[FAILED]"
18179
- };
18180
- return progressData.steps.map((step, index) => {
18181
- const status = progressData.statuses[index] || "pending";
18182
- const icon = statusIcons[status] || "[PENDING]";
18183
- const current = index === progressData.currentStepIndex ? " **[CURRENT]**" : "";
18184
- const actions = step.actions.length > 0 ? ` | Action: ${step.actions.join(", ")}` : "";
18185
- return `${icon} **Step ${index + 1}:** ${step.description}${actions}${current}`;
18186
- }).join("\n");
18187
- },
18188
- /**
18189
- * Generate user info for audit logs
18190
- */
18191
- formatUserInfo: (user) => {
18192
- return user ? ` by ${user}` : "";
18193
- },
18194
- /**
18195
- * Format timestamp for logs
18196
- */
18197
- formatTimestamp: () => {
18198
- return (/* @__PURE__ */ new Date()).toISOString();
18199
- }
18200
- };
18201
17888
 
18202
17889
  // __mcpc__core_latest/node_modules/@mcpc/core/src/utils/schema-validator.js
18203
17890
  import { Ajv as Ajv2 } from "ajv";
@@ -18206,13 +17893,14 @@ import ajvErrors from "ajv-errors";
18206
17893
  import { AggregateAjvError } from "@segment/ajv-human-errors";
18207
17894
  var ajv = new Ajv2({
18208
17895
  allErrors: true,
18209
- verbose: true
17896
+ verbose: true,
17897
+ strict: false
18210
17898
  });
18211
17899
  addFormats.default(ajv);
18212
17900
  ajvErrors.default(ajv);
18213
- function validateSchema(args, schema) {
17901
+ function validateSchema(data, schema) {
18214
17902
  const validate = ajv.compile(schema);
18215
- if (!validate(args)) {
17903
+ if (!validate(data)) {
18216
17904
  const errors = validate.errors;
18217
17905
  const customErrors = errors.filter((err) => err.keyword === "errorMessage");
18218
17906
  if (customErrors.length > 0) {
@@ -18309,17 +17997,17 @@ var AgenticExecutor = class {
18309
17997
  allToolNames;
18310
17998
  toolNameToDetailList;
18311
17999
  server;
18312
- USE_TOOL_KEY;
18313
18000
  logger;
18314
18001
  tracingEnabled;
18315
- constructor(name, allToolNames, toolNameToDetailList, server, USE_TOOL_KEY = "useTool") {
18002
+ toolSchemaMap;
18003
+ constructor(name, allToolNames, toolNameToDetailList, server) {
18316
18004
  this.name = name;
18317
18005
  this.allToolNames = allToolNames;
18318
18006
  this.toolNameToDetailList = toolNameToDetailList;
18319
18007
  this.server = server;
18320
- this.USE_TOOL_KEY = USE_TOOL_KEY;
18321
18008
  this.tracingEnabled = false;
18322
18009
  this.logger = createLogger(`mcpc.agentic.${name}`, server);
18010
+ this.toolSchemaMap = new Map(toolNameToDetailList);
18323
18011
  try {
18324
18012
  this.tracingEnabled = process6.env.MCPC_TRACING_ENABLED === "true";
18325
18013
  if (this.tracingEnabled) {
@@ -18337,7 +18025,7 @@ var AgenticExecutor = class {
18337
18025
  async execute(args, schema, parentSpan) {
18338
18026
  const executeSpan = this.tracingEnabled ? startSpan("mcpc.agentic_execute", {
18339
18027
  agent: this.name,
18340
- selectTool: String(args[this.USE_TOOL_KEY] ?? "unknown"),
18028
+ tool: String(args.tool ?? "unknown"),
18341
18029
  args: JSON.stringify(args)
18342
18030
  }, parentSpan ?? void 0) : null;
18343
18031
  try {
@@ -18352,7 +18040,7 @@ var AgenticExecutor = class {
18352
18040
  }
18353
18041
  this.logger.warning({
18354
18042
  message: "Validation failed",
18355
- selectTool: args[this.USE_TOOL_KEY],
18043
+ tool: args.tool,
18356
18044
  error: validationResult.error
18357
18045
  });
18358
18046
  return {
@@ -18367,128 +18055,39 @@ var AgenticExecutor = class {
18367
18055
  isError: true
18368
18056
  };
18369
18057
  }
18370
- const useTool = args[this.USE_TOOL_KEY];
18371
- const definitionsOf = args.definitionsOf || [];
18372
- const hasDefinitions = args.hasDefinitions || [];
18373
- if (!useTool) {
18374
- if (executeSpan) {
18375
- executeSpan.setAttributes({
18376
- toolType: "none",
18377
- completion: true
18378
- });
18379
- endSpan(executeSpan);
18380
- }
18381
- const result = {
18382
- content: []
18383
- };
18384
- this.appendToolSchemas(result, definitionsOf, hasDefinitions);
18385
- if (result.content.length === 0 && definitionsOf.length > 0) {
18386
- result.content.push({
18387
- type: "text",
18388
- text: `All requested tool schemas are already in hasDefinitions. You can now call a tool using "${this.USE_TOOL_KEY}".`
18389
- });
18390
- }
18391
- return result;
18392
- }
18393
- if (executeSpan) {
18394
- try {
18395
- const safeTool = String(useTool).replace(/\s+/g, "_");
18396
- if (typeof executeSpan.updateName === "function") {
18397
- executeSpan.updateName(`mcpc.agentic_execute.${safeTool}`);
18398
- }
18399
- } catch {
18400
- }
18401
- }
18402
- const currentTool = this.toolNameToDetailList.find(([name, _detail]) => name === useTool)?.[1];
18403
- if (currentTool) {
18404
- if (executeSpan) {
18405
- executeSpan.setAttributes({
18406
- toolType: "external",
18407
- selectedTool: useTool
18408
- });
18409
- }
18410
- this.logger.debug({
18411
- message: "Executing external tool",
18412
- selectTool: useTool
18413
- });
18414
- const currentResult = await currentTool.execute({
18415
- ...args[useTool]
18416
- });
18417
- this.appendToolSchemas(currentResult, definitionsOf, hasDefinitions);
18418
- if (executeSpan) {
18419
- executeSpan.setAttributes({
18420
- success: true,
18421
- isError: !!currentResult.isError,
18422
- resultContentLength: currentResult.content?.length || 0,
18423
- toolResult: JSON.stringify(currentResult)
18424
- });
18425
- endSpan(executeSpan);
18426
- }
18427
- return currentResult;
18428
- }
18429
- if (this.allToolNames.includes(useTool)) {
18430
- if (executeSpan) {
18431
- executeSpan.setAttributes({
18432
- toolType: "internal",
18433
- selectedTool: useTool
18434
- });
18435
- }
18436
- this.logger.debug({
18437
- message: "Executing internal tool",
18438
- selectTool: useTool
18439
- });
18440
- try {
18441
- const result = await this.server.callTool(useTool, args[useTool]);
18442
- const callToolResult = result ?? {
18443
- content: []
18444
- };
18445
- this.appendToolSchemas(callToolResult, definitionsOf, hasDefinitions);
18446
- if (executeSpan) {
18447
- executeSpan.setAttributes({
18448
- success: true,
18449
- isError: !!callToolResult.isError,
18450
- resultContentLength: callToolResult.content?.length || 0,
18451
- toolResult: JSON.stringify(callToolResult)
18452
- });
18453
- endSpan(executeSpan);
18454
- }
18455
- return callToolResult;
18456
- } catch (error2) {
18457
- if (executeSpan) {
18458
- endSpan(executeSpan, error2);
18058
+ const tool2 = args.tool;
18059
+ if (tool2 === "man") {
18060
+ const manSchema = {
18061
+ type: "array",
18062
+ items: {
18063
+ type: "string",
18064
+ enum: this.allToolNames,
18065
+ errorMessage: {
18066
+ enum: `Invalid tool name. Available: ${this.allToolNames.join(", ")}`
18067
+ }
18068
+ },
18069
+ minItems: 1,
18070
+ errorMessage: {
18071
+ type: 'Expected an array of tool names, e.g. ["tool1", "tool2"]',
18072
+ minItems: "At least one tool name is required"
18459
18073
  }
18460
- this.logger.error({
18461
- message: "Error executing internal tool",
18462
- useTool,
18463
- error: String(error2)
18464
- });
18074
+ };
18075
+ const manValidation = validateSchema(args.args ?? [], manSchema);
18076
+ if (!manValidation.valid) {
18465
18077
  return {
18466
18078
  content: [
18467
18079
  {
18468
18080
  type: "text",
18469
- text: `Error executing internal tool ${useTool}: ${error2 instanceof Error ? error2.message : String(error2)}`
18081
+ text: `Invalid args for "man": ${manValidation.error}`
18470
18082
  }
18471
18083
  ],
18472
18084
  isError: true
18473
18085
  };
18474
18086
  }
18087
+ return this.handleManCommand(args.args, executeSpan);
18475
18088
  }
18476
- if (executeSpan) {
18477
- executeSpan.setAttributes({
18478
- toolType: "not_found",
18479
- useTool
18480
- });
18481
- endSpan(executeSpan);
18482
- }
18483
- return {
18484
- content: [
18485
- {
18486
- type: "text",
18487
- text: `Tool "${useTool}" not found. Available tools: ${this.allToolNames.join(", ")}.`
18488
- }
18489
- ],
18490
- isError: true
18491
- };
18089
+ const toolArgs = args.args || {};
18090
+ return await this.executeTool(tool2, toolArgs, executeSpan);
18492
18091
  } catch (error2) {
18493
18092
  if (executeSpan) {
18494
18093
  endSpan(executeSpan, error2);
@@ -18508,1711 +18107,263 @@ var AgenticExecutor = class {
18508
18107
  };
18509
18108
  }
18510
18109
  }
18511
- // Append tool schemas to result if requested
18512
- appendToolSchemas(result, definitionsOf, hasDefinitions) {
18513
- const schemasToProvide = definitionsOf.filter((toolName) => !hasDefinitions.includes(toolName));
18514
- if (schemasToProvide.length === 0) {
18515
- return;
18110
+ /**
18111
+ * Handle `man` command - return schemas for requested tools
18112
+ * @param requestedTools - Array of tool names (already validated via JSON Schema)
18113
+ */
18114
+ handleManCommand(requestedTools, executeSpan) {
18115
+ if (executeSpan) {
18116
+ executeSpan.setAttributes({
18117
+ toolType: "man",
18118
+ requestedTools: requestedTools.join(",")
18119
+ });
18516
18120
  }
18517
- const definitionTexts = [];
18518
- for (const toolName of schemasToProvide) {
18519
- const toolDetail = this.toolNameToDetailList.find(([name]) => name === toolName);
18121
+ const schemas = requestedTools.map((toolName) => {
18122
+ const toolDetail = this.toolSchemaMap.get(toolName);
18520
18123
  if (toolDetail) {
18521
- const [name, schema] = toolDetail;
18522
- const schemaJson = JSON.stringify(schema, null, 2);
18523
- definitionTexts.push(`<tool_definition name="${name}">
18524
- ${schemaJson}
18525
- </tool_definition>`);
18124
+ const cleanedSchema = cleanToolSchema(toolDetail);
18125
+ return `<tool_definition name="${toolName}">
18126
+ ${JSON.stringify(cleanedSchema, null, 2)}
18127
+ </tool_definition>`;
18526
18128
  }
18527
- }
18528
- if (definitionTexts.length > 0) {
18529
- result.content.push({
18530
- type: "text",
18531
- text: `${definitionTexts.join("\n\n")}`
18129
+ return null;
18130
+ }).filter(Boolean);
18131
+ if (executeSpan) {
18132
+ executeSpan.setAttributes({
18133
+ schemasReturned: schemas.length,
18134
+ success: true
18532
18135
  });
18136
+ endSpan(executeSpan);
18533
18137
  }
18534
- }
18535
- // Validate arguments using JSON schema
18536
- validate(args, schema) {
18537
- return validateSchema(args, schema);
18538
- }
18539
- };
18540
-
18541
- // __mcpc__core_latest/node_modules/@jsr/es-toolkit__es-toolkit/src/function/partial.js
18542
- function partial2(func, ...partialArgs) {
18543
- return partialImpl(func, placeholderSymbol, ...partialArgs);
18544
- }
18545
- function partialImpl(func, placeholder, ...partialArgs) {
18546
- const partialed = function(...providedArgs) {
18547
- let providedArgsIndex = 0;
18548
- const substitutedArgs = partialArgs.slice().map((arg) => arg === placeholder ? providedArgs[providedArgsIndex++] : arg);
18549
- const remainingArgs = providedArgs.slice(providedArgsIndex);
18550
- return func.apply(this, substitutedArgs.concat(remainingArgs));
18551
- };
18552
- if (func.prototype) {
18553
- partialed.prototype = Object.create(func.prototype);
18554
- }
18555
- return partialed;
18556
- }
18557
- var placeholderSymbol = Symbol("partial.placeholder");
18558
- partial2.placeholder = placeholderSymbol;
18559
-
18560
- // __mcpc__core_latest/node_modules/@jsr/es-toolkit__es-toolkit/src/function/partialRight.js
18561
- function partialRight(func, ...partialArgs) {
18562
- return partialRightImpl(func, placeholderSymbol2, ...partialArgs);
18563
- }
18564
- function partialRightImpl(func, placeholder, ...partialArgs) {
18565
- const partialedRight = function(...providedArgs) {
18566
- const placeholderLength = partialArgs.filter((arg) => arg === placeholder).length;
18567
- const rangeLength = Math.max(providedArgs.length - placeholderLength, 0);
18568
- const remainingArgs = providedArgs.slice(0, rangeLength);
18569
- let providedArgsIndex = rangeLength;
18570
- const substitutedArgs = partialArgs.slice().map((arg) => arg === placeholder ? providedArgs[providedArgsIndex++] : arg);
18571
- return func.apply(this, remainingArgs.concat(substitutedArgs));
18572
- };
18573
- if (func.prototype) {
18574
- partialedRight.prototype = Object.create(func.prototype);
18575
- }
18576
- return partialedRight;
18577
- }
18578
- var placeholderSymbol2 = Symbol("partialRight.placeholder");
18579
- partialRight.placeholder = placeholderSymbol2;
18580
-
18581
- // __mcpc__core_latest/node_modules/@jsr/es-toolkit__es-toolkit/src/function/retry.js
18582
- var DEFAULT_RETRIES = Number.POSITIVE_INFINITY;
18583
-
18584
- // __mcpc__core_latest/node_modules/@jsr/es-toolkit__es-toolkit/src/object/pick.js
18585
- function pick2(obj, keys) {
18586
- const result = {};
18587
- for (let i = 0; i < keys.length; i++) {
18588
- const key = keys[i];
18589
- if (Object.hasOwn(obj, key)) {
18590
- result[key] = obj[key];
18591
- }
18592
- }
18593
- return result;
18594
- }
18595
-
18596
- // __mcpc__core_latest/node_modules/@mcpc/core/src/factories/args-def-factory.js
18597
- var DECISION_OPTIONS = {
18598
- RETRY: "retry",
18599
- PROCEED: "proceed",
18600
- COMPLETE: "complete"
18601
- };
18602
- function createArgsDefFactory(name, allToolNames, depGroups, predefinedSteps, ensureStepActions) {
18603
- const formatEnsureStepActions = () => {
18604
- if (!ensureStepActions || ensureStepActions.length === 0) {
18605
- return "";
18606
- }
18607
- return `
18608
-
18609
- ## Required Actions
18610
- The workflow MUST include at least one of these actions:
18611
- ${ensureStepActions.map((action) => `- \`${action}\``).join("\n")}`;
18612
- };
18613
- return {
18614
- common: (extra, optionalFields = []) => {
18615
- const requiredFields = Object.keys(extra).filter((key) => !optionalFields.includes(key));
18616
- return {
18617
- type: "object",
18618
- description: `**Tool parameters dynamically update per workflow step**`,
18619
- properties: {
18620
- ...extra
18621
- },
18622
- required: requiredFields
18623
- };
18624
- },
18625
- steps: () => ({
18626
- type: "array",
18627
- description: `
18628
- Workflow step definitions - provide ONLY on initial call.
18629
-
18630
- **CRITICAL RULES:**
18631
- - **Sequential Dependency:** If Action B depends on Action A's result \u2192 separate steps
18632
- - **Concurrent Actions:** Independent actions can share one step
18633
- - **Complete Mapping:** Include ALL requested operations
18634
- - **Predefined Steps:** Leave unspecified if predefined steps exist
18635
-
18636
- **BEST PRACTICES:**
18637
- - Atomic, focused steps
18638
- - Idempotent actions for safe retries
18639
- - Clear step descriptions with input/output context`,
18640
- items: {
18641
- type: "object",
18642
- description: `A single step containing actions that execute concurrently. All actions in this step run simultaneously with no guaranteed order.`,
18643
- properties: {
18644
- description: {
18645
- type: "string",
18646
- description: `**Step purpose, required inputs, and expected outputs**`
18647
- },
18648
- actions: {
18649
- type: "array",
18650
- description: `Array of action names for this step. **CURRENT LIMITATION: Only 1 action per step is allowed.** Action names must match available tool names exactly.`,
18651
- items: {
18652
- ...{
18653
- enum: allToolNames
18654
- },
18655
- type: "string",
18656
- description: `Individual action name from available tools. Must be exactly one of the allowed tool names.`
18657
- },
18658
- uniqueItems: true,
18659
- minItems: 0,
18660
- // TODO: remove this restriction when workflow planning is good enough
18661
- maxItems: 1
18662
- }
18663
- },
18664
- required: [
18665
- "description",
18666
- "actions"
18667
- ],
18668
- additionalProperties: false
18669
- },
18670
- default: predefinedSteps ? predefinedSteps : void 0,
18671
- minItems: 1
18672
- }),
18673
- init: () => ({
18674
- type: "boolean",
18675
- description: `Init a new workflow`,
18676
- enum: [
18677
- true
18678
- ]
18679
- }),
18680
- decision: () => ({
18681
- type: "string",
18682
- enum: Object.values(DECISION_OPTIONS),
18683
- description: `**Step control: \`${DECISION_OPTIONS.PROCEED}\` = next step, \`${DECISION_OPTIONS.RETRY}\` = retry/repeat current, \`${DECISION_OPTIONS.COMPLETE}\` = finish workflow**`,
18684
- errorMessage: {
18685
- enum: `Invalid decision. Must be one of: ${Object.values(DECISION_OPTIONS).join(", ")}.`
18686
- }
18687
- }),
18688
- action: () => ({
18689
- type: "string",
18690
- description: "Define the current workflow action to be performed",
18691
- enum: allToolNames,
18692
- required: [
18693
- "action"
18694
- ],
18695
- errorMessage: {
18696
- enum: `Invalid action. Must be one of: ${allToolNames.join(", ")}.`
18697
- }
18698
- }),
18699
- forTool: function() {
18700
- return this.common({});
18701
- },
18702
- forCurrentState: function(state) {
18703
- const currentStep = state.getCurrentStep();
18704
- if (!state.isWorkflowInitialized() || !currentStep) {
18705
- state.reset();
18706
- const initSchema = {
18707
- init: this.init()
18708
- };
18709
- if (!predefinedSteps) {
18710
- initSchema.steps = this.steps();
18711
- }
18712
- return this.common(initSchema);
18713
- }
18714
- const stepDependencies = {
18715
- ...pick2(depGroups, currentStep.actions)
18716
- };
18717
- stepDependencies["decision"] = this.decision();
18718
- stepDependencies["action"] = this.action();
18719
- return this.common(stepDependencies);
18720
- },
18721
- forSampling: function() {
18722
- return {
18723
- type: "object",
18724
- description: "Provide user request for autonomous tool execution",
18725
- properties: {
18726
- userRequest: {
18727
- type: "string",
18728
- description: "The task or request that should be completed autonomously by the agentic system using available tools"
18729
- },
18730
- context: {
18731
- type: "object",
18732
- description: "Necessary context for the request, e.g., the absolute path of the current working directory. This is just an example; any relevant context fields are allowed.",
18733
- additionalProperties: true
18734
- }
18735
- },
18736
- required: [
18737
- "userRequest",
18738
- "context"
18739
- ],
18740
- errorMessage: {
18741
- required: {
18742
- userRequest: "Missing required field 'userRequest'. Please provide a clear task description.",
18743
- context: "Missing required field 'context'. Please provide relevant context (e.g., current working directory)."
18744
- }
18745
- }
18746
- };
18747
- },
18748
- forAgentic: function(toolNameToDetailList, _sampling = false, USE_TOOL_KEY = "useTool") {
18749
- const allOf = [
18750
- // When a specific tool is selected, its parameters must be provided
18751
- ...toolNameToDetailList.map(([toolName, _toolDetail]) => {
18752
- return {
18753
- if: {
18754
- properties: {
18755
- [USE_TOOL_KEY]: {
18756
- const: toolName
18757
- }
18758
- },
18759
- required: [
18760
- USE_TOOL_KEY
18761
- ]
18762
- },
18763
- then: {
18764
- required: [
18765
- toolName
18766
- ],
18767
- errorMessage: {
18768
- required: {
18769
- [toolName]: `Tool "${toolName}" is selected but its parameters are missing. Please provide "${toolName}": { ...parameters }.`
18770
- }
18771
- }
18772
- }
18773
- };
18774
- })
18775
- ];
18776
- 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**`;
18777
- const toolItems = allToolNames.length > 0 ? {
18778
- type: "string",
18779
- enum: allToolNames
18780
- } : {
18781
- type: "string"
18782
- };
18783
- const baseProperties = {
18784
- [USE_TOOL_KEY]: {
18785
- type: "string",
18786
- enum: allToolNames,
18787
- description: useToolDescription,
18788
- errorMessage: {
18789
- enum: `Invalid tool name. Available tools: ${allToolNames.join(", ")}.`
18790
- }
18791
- },
18792
- hasDefinitions: {
18793
- type: "array",
18794
- items: toolItems,
18795
- description: "Tool names whose schemas you already have. List all tools you have schemas for to avoid duplicate schema requests and reduce token usage."
18796
- },
18797
- definitionsOf: {
18798
- type: "array",
18799
- items: toolItems,
18800
- description: "Tool names whose schemas you need. Request tool schemas before calling them to understand their parameters."
18801
- }
18802
- };
18803
- const requiredFields = [];
18804
- const schema = {
18805
- additionalProperties: true,
18806
- type: "object",
18807
- properties: baseProperties,
18808
- required: requiredFields
18809
- };
18810
- if (allOf.length > 0) {
18811
- schema.allOf = allOf;
18812
- }
18813
- if (allToolNames.length > 0) {
18814
- const thenClause = {
18815
- required: [
18816
- USE_TOOL_KEY
18817
- ],
18818
- errorMessage: {
18819
- required: {
18820
- [USE_TOOL_KEY]: `No tool selected. Please specify "${USE_TOOL_KEY}" to select one of: ${allToolNames.join(", ")}. Or use "definitionsOf" with tool names to get their schemas first.`
18821
- }
18822
- }
18823
- };
18824
- Object.assign(schema, {
18825
- if: {
18826
- // definitionsOf is not provided OR is empty array
18827
- anyOf: [
18828
- {
18829
- not: {
18830
- required: [
18831
- "definitionsOf"
18832
- ]
18833
- }
18834
- },
18835
- {
18836
- properties: {
18837
- definitionsOf: {
18838
- type: "array",
18839
- maxItems: 0
18840
- }
18841
- }
18842
- }
18843
- ]
18844
- },
18845
- then: thenClause
18846
- });
18847
- }
18848
- return schema;
18849
- },
18850
- forNextState: function(state) {
18851
- if (!state.isWorkflowInitialized() || !state.hasNextStep()) {
18852
- throw new Error(`Cannot get next state schema: no next step available`);
18853
- }
18854
- const currentStepIndex = state.getCurrentStepIndex();
18855
- const allSteps = state.getSteps();
18856
- const nextStep = allSteps[currentStepIndex + 1];
18857
- if (!nextStep) {
18858
- throw new Error(`Next step not found`);
18859
- }
18860
- const stepDependencies = {
18861
- ...pick2(depGroups, nextStep.actions)
18862
- };
18863
- stepDependencies["decision"] = this.decision();
18864
- stepDependencies["action"] = this.action();
18865
- return this.common(stepDependencies);
18866
- },
18867
- forToolDescription: function(description, state) {
18868
- const enforceToolArgs = this.forCurrentState(state);
18869
- const initTitle = predefinedSteps ? `**YOU MUST execute this tool with following tool arguments to init the workflow**
18870
- NOTE: The \`steps\` has been predefined` : `**You MUST execute this tool with following tool arguments to plan and init the workflow**`;
18871
- return CompiledPrompts.workflowToolDescription({
18872
- description,
18873
- initTitle,
18874
- ensureStepActions: formatEnsureStepActions(),
18875
- schemaDefinition: JSON.stringify(enforceToolArgs, null, 2)
18876
- });
18877
- },
18878
- forInitialStepDescription: function(steps, state) {
18879
- return CompiledPrompts.workflowInit({
18880
- stepCount: steps.length.toString(),
18881
- currentStepDescription: state.getCurrentStep()?.description || "",
18882
- toolName: name,
18883
- schemaDefinition: JSON.stringify(this.forCurrentState(state), null, 2),
18884
- // Remove redundant workflow steps display
18885
- workflowSteps: ""
18886
- });
18887
- }
18888
- };
18889
- }
18890
-
18891
- // __mcpc__core_latest/node_modules/@mcpc/core/src/executors/agentic/agentic-tool-registrar.js
18892
- function registerAgenticTool(server, { description, name, allToolNames, depGroups, toolNameToDetailList }) {
18893
- const createArgsDef = createArgsDefFactory(name, allToolNames, depGroups, void 0, void 0);
18894
- const agenticExecutor = new AgenticExecutor(name, allToolNames, toolNameToDetailList, server);
18895
- description = CompiledPrompts.autonomousExecution({
18896
- toolName: name,
18897
- description
18898
- });
18899
- const agenticArgsDef = createArgsDef.forAgentic(toolNameToDetailList, false);
18900
- const argsDef = agenticArgsDef;
18901
- const schema = allToolNames.length > 0 ? argsDef : {
18902
- type: "object",
18903
- properties: {}
18904
- };
18905
- server.tool(name, description, jsonSchema(createModelCompatibleJSONSchema(schema)), async (args) => {
18906
- return await agenticExecutor.execute(args, schema);
18907
- });
18908
- }
18909
-
18910
- // __mcpc__core_latest/node_modules/@mcpc/core/src/plugins/built-in/mode-agentic-plugin.js
18911
- var createAgenticModePlugin = () => ({
18912
- name: "mode-agentic",
18913
- version: "1.0.0",
18914
- // Only apply to agentic mode
18915
- apply: "agentic",
18916
- // Register the agent tool
18917
- registerAgentTool: (context2) => {
18918
- registerAgenticTool(context2.server, {
18919
- description: context2.description,
18920
- name: context2.name,
18921
- allToolNames: context2.allToolNames,
18922
- depGroups: context2.depGroups,
18923
- toolNameToDetailList: context2.toolNameToDetailList
18924
- });
18925
- }
18926
- });
18927
- var mode_agentic_plugin_default = createAgenticModePlugin();
18928
-
18929
- // __mcpc__core_latest/node_modules/@mcpc/core/src/utils/state.js
18930
- var WorkflowState = class {
18931
- currentStepIndex = -1;
18932
- steps = [];
18933
- stepStatuses = [];
18934
- stepResults = [];
18935
- stepErrors = [];
18936
- isInitialized = false;
18937
- isStarted = false;
18938
- constructor(steps) {
18939
- if (steps) {
18940
- this.initialize(steps);
18941
- }
18942
- }
18943
- getCurrentStepIndex() {
18944
- return this.currentStepIndex;
18945
- }
18946
- getSteps() {
18947
- return this.steps;
18948
- }
18949
- isWorkflowInitialized() {
18950
- return this.isInitialized;
18951
- }
18952
- getCurrentStep() {
18953
- if (!this.isInitialized || this.currentStepIndex < 0) {
18954
- return null;
18955
- }
18956
- return this.steps[this.currentStepIndex] || null;
18957
- }
18958
- getNextStep() {
18959
- if (!this.isInitialized) return null;
18960
- const nextIndex = this.currentStepIndex + 1;
18961
- return this.steps[nextIndex] || null;
18962
- }
18963
- // Get the previous step in the workflow
18964
- getPreviousStep() {
18965
- if (!this.isInitialized) return null;
18966
- const prevIndex = this.currentStepIndex - 1;
18967
- return this.steps[prevIndex] || null;
18968
- }
18969
- hasNextStep() {
18970
- return this.getNextStep() !== null;
18971
- }
18972
- // Check if there is a previous step available
18973
- hasPreviousStep() {
18974
- return this.getPreviousStep() !== null;
18975
- }
18976
- // Check if currently at the first step
18977
- isAtFirstStep() {
18978
- return this.isInitialized && this.currentStepIndex === 0;
18979
- }
18980
- // Check if currently at the last step
18981
- isAtLastStep() {
18982
- return this.isInitialized && this.currentStepIndex >= this.steps.length - 1;
18983
- }
18984
- isWorkflowStarted() {
18985
- return this.isStarted;
18986
- }
18987
- isCompleted() {
18988
- return this.isInitialized && this.currentStepIndex > this.steps.length - 1;
18989
- }
18990
- // Mark workflow as completed by moving beyond the last step
18991
- markCompleted() {
18992
- if (this.isInitialized) {
18993
- this.currentStepIndex = this.steps.length;
18994
- }
18995
- }
18996
- initialize(steps) {
18997
- this.steps = steps;
18998
- this.stepStatuses = new Array(steps.length).fill("pending");
18999
- this.stepResults = new Array(steps.length).fill("");
19000
- this.stepErrors = new Array(steps.length).fill("");
19001
- this.currentStepIndex = 0;
19002
- this.isInitialized = true;
19003
- this.isStarted = false;
19004
- }
19005
- // Mark current step as running
19006
- markCurrentStepRunning() {
19007
- if (this.isInitialized && this.currentStepIndex >= 0 && this.currentStepIndex < this.steps.length) {
19008
- this.stepStatuses[this.currentStepIndex] = "running";
19009
- }
19010
- }
19011
- // Mark current step as completed
19012
- markCurrentStepCompleted(result) {
19013
- if (this.isInitialized && this.currentStepIndex >= 0 && this.currentStepIndex < this.steps.length) {
19014
- this.stepStatuses[this.currentStepIndex] = "completed";
19015
- if (result) {
19016
- this.stepResults[this.currentStepIndex] = result;
19017
- }
19018
- }
19019
- }
19020
- // Mark current step as failed
19021
- markCurrentStepFailed(error2) {
19022
- if (this.isInitialized && this.currentStepIndex >= 0 && this.currentStepIndex < this.steps.length) {
19023
- this.stepStatuses[this.currentStepIndex] = "failed";
19024
- if (error2) {
19025
- this.stepErrors[this.currentStepIndex] = error2;
19026
- }
19027
- }
19028
- }
19029
- // Get steps with their status
19030
- getStepsWithStatus() {
19031
- return this.steps.map((step, index) => ({
19032
- ...step,
19033
- status: this.stepStatuses[index] || "pending",
19034
- result: this.stepResults[index] || void 0,
19035
- error: this.stepErrors[index] || void 0
19036
- }));
19037
- }
19038
- // Get basic workflow progress data for template rendering
19039
- getProgressData() {
19040
- return {
19041
- steps: this.steps,
19042
- statuses: this.stepStatuses,
19043
- results: this.stepResults,
19044
- errors: this.stepErrors,
19045
- currentStepIndex: this.currentStepIndex,
19046
- totalSteps: this.steps.length
19047
- };
19048
- }
19049
- start() {
19050
- this.isStarted = true;
19051
- }
19052
- moveToNextStep() {
19053
- if (!this.hasNextStep()) {
19054
- return false;
19055
- }
19056
- this.currentStepIndex++;
19057
- return true;
19058
- }
19059
- // Move to the previous step in the workflow
19060
- moveToPreviousStep() {
19061
- if (!this.hasPreviousStep()) {
19062
- return false;
19063
- }
19064
- this.currentStepIndex--;
19065
- return true;
19066
- }
19067
- // Move to a specific step by index (optional feature)
19068
- moveToStep(stepIndex) {
19069
- if (!this.isInitialized || stepIndex < 0 || stepIndex >= this.steps.length) {
19070
- return false;
19071
- }
19072
- this.currentStepIndex = stepIndex;
19073
- return true;
19074
- }
19075
- reset() {
19076
- this.currentStepIndex = -1;
19077
- this.steps = [];
19078
- this.stepStatuses = [];
19079
- this.stepResults = [];
19080
- this.stepErrors = [];
19081
- this.isInitialized = false;
19082
- this.isStarted = false;
19083
- }
19084
- getDebugInfo() {
19085
- return {
19086
- currentStepIndex: this.currentStepIndex,
19087
- totalSteps: this.steps.length,
19088
- isInitialized: this.isInitialized,
19089
- currentStep: this.getCurrentStep()?.description,
19090
- nextStep: this.getNextStep()?.description,
19091
- previousStep: this.getPreviousStep()?.description,
19092
- isAtFirstStep: this.isAtFirstStep(),
19093
- hasPreviousStep: this.hasPreviousStep()
19094
- };
19095
- }
19096
- };
19097
-
19098
- // __mcpc__core_latest/node_modules/@mcpc/core/src/executors/workflow/workflow-executor.js
19099
- var WorkflowExecutor = class {
19100
- name;
19101
- allToolNames;
19102
- toolNameToDetailList;
19103
- createArgsDef;
19104
- server;
19105
- predefinedSteps;
19106
- ensureStepActions;
19107
- toolNameToIdMapping;
19108
- constructor(name, allToolNames, toolNameToDetailList, createArgsDef, server, predefinedSteps, ensureStepActions, toolNameToIdMapping) {
19109
- this.name = name;
19110
- this.allToolNames = allToolNames;
19111
- this.toolNameToDetailList = toolNameToDetailList;
19112
- this.createArgsDef = createArgsDef;
19113
- this.server = server;
19114
- this.predefinedSteps = predefinedSteps;
19115
- this.ensureStepActions = ensureStepActions;
19116
- this.toolNameToIdMapping = toolNameToIdMapping;
19117
- }
19118
- // Helper method to validate required actions are present in workflow steps
19119
- validateRequiredActions(steps) {
19120
- if (!this.ensureStepActions || this.ensureStepActions.length === 0) {
19121
- return {
19122
- valid: true,
19123
- missing: []
19124
- };
19125
- }
19126
- const allStepActions = /* @__PURE__ */ new Set();
19127
- steps.forEach((step) => {
19128
- step.actions.forEach((action) => allStepActions.add(action));
19129
- });
19130
- const missing = [];
19131
- for (const requiredAction of this.ensureStepActions) {
19132
- if (allStepActions.has(requiredAction)) {
19133
- continue;
19134
- }
19135
- if (this.toolNameToIdMapping) {
19136
- const mappedToolId = this.toolNameToIdMapping.get(requiredAction);
19137
- if (mappedToolId && allStepActions.has(mappedToolId)) {
19138
- continue;
19139
- }
19140
- }
19141
- missing.push(requiredAction);
19142
- }
19143
- return {
19144
- valid: missing.length === 0,
19145
- missing
19146
- };
19147
- }
19148
- // Helper method to format workflow progress
19149
- formatProgress(state) {
19150
- const progressData = state.getProgressData();
19151
- return PromptUtils.formatWorkflowProgress(progressData);
19152
- }
19153
- async execute(args, state) {
19154
- if (args.init) {
19155
- state.reset();
19156
- } else {
19157
- if (!state.isWorkflowInitialized() && !args.init) {
19158
- return {
19159
- content: [
19160
- {
19161
- type: "text",
19162
- text: this.predefinedSteps ? WorkflowPrompts.ERRORS.NOT_INITIALIZED.WITH_PREDEFINED : WorkflowPrompts.ERRORS.NOT_INITIALIZED.WITHOUT_PREDEFINED
19163
- }
19164
- ],
19165
- isError: true
19166
- };
19167
- }
19168
- const decision2 = args.decision;
19169
- if (decision2 === "proceed") {
19170
- if (state.isAtLastStep() && state.isWorkflowStarted()) {
19171
- state.markCompleted();
19172
- return {
19173
- content: [
19174
- {
19175
- type: "text",
19176
- text: `## Workflow Completed!
19177
-
19178
- ${this.formatProgress(state)}
19179
-
19180
- ${CompiledPrompts.workflowCompleted({
19181
- totalSteps: state.getSteps().length,
19182
- toolName: this.name,
19183
- newWorkflowInstructions: this.predefinedSteps ? "" : " and new `steps` array"
19184
- })}`
19185
- }
19186
- ],
19187
- isError: false
19188
- };
19189
- }
19190
- if (state.isCompleted()) {
19191
- return {
19192
- content: [
19193
- {
19194
- type: "text",
19195
- text: WorkflowPrompts.ERRORS.ALREADY_AT_FINAL
19196
- }
19197
- ],
19198
- isError: true
19199
- };
19200
- }
19201
- const currentStepIndex = state.getCurrentStepIndex();
19202
- const wasStarted = state.isWorkflowStarted();
19203
- if (state.isWorkflowStarted()) {
19204
- state.moveToNextStep();
19205
- } else {
19206
- state.start();
19207
- }
19208
- const nextStepValidationSchema = this.createArgsDef.forCurrentState(state);
19209
- const nextStepValidationResult = this.validateInput(args, nextStepValidationSchema);
19210
- if (!nextStepValidationResult.valid) {
19211
- if (wasStarted) {
19212
- state.moveToStep(currentStepIndex);
19213
- } else {
19214
- state.moveToStep(currentStepIndex);
19215
- }
19216
- return {
19217
- content: [
19218
- {
19219
- type: "text",
19220
- text: CompiledPrompts.workflowErrorResponse({
19221
- errorMessage: `Cannot proceed to next step: ${nextStepValidationResult.error || "Arguments validation failed"}`
19222
- })
19223
- }
19224
- ],
19225
- isError: true
19226
- };
19227
- }
19228
- } else if (decision2 === "complete") {
19229
- if (state.isAtLastStep() && state.isWorkflowStarted()) {
19230
- state.markCompleted();
19231
- return {
19232
- content: [
19233
- {
19234
- type: "text",
19235
- text: `## Workflow Completed!
19236
-
19237
- ${this.formatProgress(state)}
19238
-
19239
- ${CompiledPrompts.workflowCompleted({
19240
- totalSteps: state.getSteps().length,
19241
- toolName: this.name,
19242
- newWorkflowInstructions: this.predefinedSteps ? "" : " and new `steps` array"
19243
- })}`
19244
- }
19245
- ],
19246
- isError: false
19247
- };
19248
- } else {
19249
- return {
19250
- content: [
19251
- {
19252
- type: "text",
19253
- text: WorkflowPrompts.ERRORS.CANNOT_COMPLETE_NOT_AT_FINAL
19254
- }
19255
- ],
19256
- isError: true
19257
- };
19258
- }
19259
- }
19260
- }
19261
- const decision = args.decision;
19262
- if (decision !== "proceed") {
19263
- const validationSchema = this.createArgsDef.forCurrentState(state);
19264
- const validationResult = this.validateInput(args, validationSchema);
19265
- if (!validationResult.valid) {
19266
- return {
19267
- content: [
19268
- {
19269
- type: "text",
19270
- text: CompiledPrompts.workflowErrorResponse({
19271
- errorMessage: validationResult.error || "Arguments validation failed"
19272
- })
19273
- }
19274
- ],
19275
- isError: true
19276
- };
19277
- }
19278
- }
19279
- if (args.init) {
19280
- return this.initialize(args, state);
19281
- }
19282
- return await this.executeStep(args, state);
19283
- }
19284
- initialize(args, state) {
19285
- const steps = args.steps ?? this.predefinedSteps;
19286
- if (!steps || steps.length === 0) {
19287
- return {
19288
- content: [
19289
- {
19290
- type: "text",
19291
- text: WorkflowPrompts.ERRORS.NO_STEPS_PROVIDED
19292
- }
19293
- ],
19294
- isError: true
19295
- };
19296
- }
19297
- const validation = this.validateRequiredActions(steps);
19298
- if (!validation.valid) {
19299
- return {
19300
- content: [
19301
- {
19302
- type: "text",
19303
- text: `## Workflow Validation Failed \u274C
19304
-
19305
- **Missing Required Actions:** The following actions must be included in the workflow steps:
19306
-
19307
- ${validation.missing.map((action) => `- \`${this.toolNameToIdMapping?.get(action) ?? action}\``).join("\n")}`
19308
- }
19309
- ],
19310
- isError: true
19311
- };
19312
- }
19313
- state.initialize(steps);
19314
- return {
19315
- content: [
19316
- {
19317
- type: "text",
19318
- text: `## Workflow Initialized
19319
- ${this.formatProgress(state)}
19320
- ${this.createArgsDef.forInitialStepDescription(steps, state)}`
19321
- }
19322
- ],
19323
- isError: false
19324
- };
19325
- }
19326
- async executeStep(args, state) {
19327
- const currentStep = state.getCurrentStep();
19328
- if (!currentStep) {
19329
- return {
19330
- content: [
19331
- {
19332
- type: "text",
19333
- text: WorkflowPrompts.ERRORS.NO_CURRENT_STEP
19334
- }
19335
- ],
19336
- isError: true
19337
- };
19338
- }
19339
- state.markCurrentStepRunning();
19340
- const results = {
19341
- content: [],
19342
- isError: false
19343
- };
19344
- for (const action of currentStep.actions) {
19345
- try {
19346
- const actionArgs = args[action] || {};
19347
- const actionResult = await this.server.callTool(action, actionArgs);
19348
- if (!results.isError) {
19349
- results.isError = actionResult.isError;
19350
- }
19351
- results.content = results.content.concat(actionResult.content ?? []);
19352
- results.content.push({
19353
- type: "text",
19354
- text: `Action \`${action}\` executed ${actionResult.isError ? "\u274C **FAILED**" : "\u2705 **SUCCESS**"}:`
19355
- });
19356
- } catch (error2) {
19357
- results.content.push({
19358
- type: "text",
19359
- text: `${error2.message}`
19360
- });
19361
- results.content.push({
19362
- type: "text",
19363
- text: `Action \`${action}\` \u274C **FAILED** with error: `
19364
- });
19365
- results.isError = true;
19366
- }
19367
- }
19368
- if (results.isError) {
19369
- state.markCurrentStepFailed("Step execution failed");
19370
- } else {
19371
- state.markCurrentStepCompleted("Step completed successfully");
19372
- }
19373
- if (state.hasNextStep()) {
19374
- const nextStepArgsDef = this.createArgsDef.forNextState(state);
19375
- results.content.push({
19376
- type: "text",
19377
- text: CompiledPrompts.nextStepDecision({
19378
- toolName: this.name,
19379
- nextStepDescription: state.getNextStep()?.description || "Unknown step",
19380
- nextStepSchema: JSON.stringify(nextStepArgsDef, null, 2)
19381
- })
19382
- });
19383
- } else {
19384
- results.content.push({
19385
- type: "text",
19386
- text: CompiledPrompts.finalStepCompletion({
19387
- statusIcon: results.isError ? "\u274C" : "\u2705",
19388
- statusText: results.isError ? "with errors" : "successfully",
19389
- toolName: this.name,
19390
- newWorkflowInstructions: this.predefinedSteps ? "" : " and new `steps` array"
19391
- })
19392
- });
19393
- }
19394
- results.content.push({
19395
- type: "text",
19396
- text: `## Workflow Progress
19397
- ${this.formatProgress(state)}`
19398
- });
19399
- return results;
19400
- }
19401
- // Validate arguments using JSON schema
19402
- validateInput(args, schema) {
19403
- return validateSchema(args, schema);
19404
- }
19405
- };
19406
-
19407
- // __mcpc__core_latest/node_modules/@mcpc/core/src/executors/workflow/workflow-tool-registrar.js
19408
- function registerAgenticWorkflowTool(server, { description, name, allToolNames, depGroups, toolNameToDetailList, predefinedSteps, ensureStepActions, toolNameToIdMapping }) {
19409
- const createArgsDef = createArgsDefFactory(name, allToolNames, depGroups, predefinedSteps, ensureStepActions);
19410
- const workflowExecutor = new WorkflowExecutor(name, allToolNames, toolNameToDetailList, createArgsDef, server, predefinedSteps, ensureStepActions, toolNameToIdMapping);
19411
- const workflowState = new WorkflowState();
19412
- const planningInstructions = predefinedSteps ? "- Set `init: true` (steps are predefined)" : "- Set `init: true` and define complete `steps` array";
19413
- const baseDescription = CompiledPrompts.workflowExecution({
19414
- toolName: name,
19415
- description,
19416
- planningInstructions
19417
- });
19418
- const argsDef = createArgsDef.forTool();
19419
- const toolDescription = createArgsDef.forToolDescription(baseDescription, workflowState);
19420
- server.tool(name, toolDescription, jsonSchema(createModelCompatibleJSONSchema(argsDef)), async (args) => {
19421
- try {
19422
- return await workflowExecutor.execute(args, workflowState);
19423
- } catch (error2) {
19424
- workflowState.reset();
19425
- return {
19426
- content: [
19427
- {
19428
- type: "text",
19429
- text: `Workflow execution error: ${error2.message}`
19430
- }
19431
- ],
19432
- isError: true
19433
- };
19434
- }
19435
- });
19436
- }
19437
-
19438
- // __mcpc__core_latest/node_modules/@mcpc/core/src/plugins/built-in/mode-workflow-plugin.js
19439
- var createWorkflowModePlugin = () => ({
19440
- name: "mode-workflow",
19441
- version: "1.0.0",
19442
- // Only apply to workflow mode
19443
- apply: "agentic_workflow",
19444
- // Register the agent tool
19445
- registerAgentTool: (context2) => {
19446
- registerAgenticWorkflowTool(context2.server, {
19447
- description: context2.description,
19448
- name: context2.name,
19449
- allToolNames: context2.allToolNames,
19450
- depGroups: context2.depGroups,
19451
- toolNameToDetailList: context2.toolNameToDetailList,
19452
- predefinedSteps: context2.options.steps,
19453
- ensureStepActions: context2.options.ensureStepActions,
19454
- toolNameToIdMapping: context2.toolNameToIdMapping
19455
- });
19456
- }
19457
- });
19458
- var mode_workflow_plugin_default = createWorkflowModePlugin();
19459
-
19460
- // __mcpc__core_latest/node_modules/@mcpc/core/src/executors/sampling/base-sampling-executor.js
19461
- import process7 from "node:process";
19462
- var BaseSamplingExecutor = class {
19463
- name;
19464
- description;
19465
- allToolNames;
19466
- toolNameToDetailList;
19467
- server;
19468
- conversationHistory;
19469
- maxIterations;
19470
- currentIteration;
19471
- logger;
19472
- tracingEnabled;
19473
- summarize;
19474
- constructor(name, description, allToolNames, toolNameToDetailList, server, config2) {
19475
- this.name = name;
19476
- this.description = description;
19477
- this.allToolNames = allToolNames;
19478
- this.toolNameToDetailList = toolNameToDetailList;
19479
- this.server = server;
19480
- this.conversationHistory = [];
19481
- this.maxIterations = 55;
19482
- this.currentIteration = 0;
19483
- this.tracingEnabled = false;
19484
- this.summarize = true;
19485
- if (config2?.maxIterations) {
19486
- this.maxIterations = config2.maxIterations;
19487
- }
19488
- if (config2?.summarize !== void 0) {
19489
- this.summarize = config2.summarize;
19490
- }
19491
- this.logger = createLogger(`mcpc.sampling.${name}`, server);
19492
- try {
19493
- const tracingConfig = {
19494
- enabled: process7.env.MCPC_TRACING_ENABLED === "true",
19495
- serviceName: `mcpc-sampling-${name}`,
19496
- exportTo: process7.env.MCPC_TRACING_EXPORT ?? "otlp",
19497
- otlpEndpoint: process7.env.MCPC_TRACING_OTLP_ENDPOINT ?? "http://localhost:4318/v1/traces"
19498
- };
19499
- this.tracingEnabled = tracingConfig.enabled;
19500
- if (this.tracingEnabled) {
19501
- initializeTracing(tracingConfig);
19502
- }
19503
- } catch {
19504
- this.tracingEnabled = false;
19505
- }
19506
- }
19507
- /**
19508
- * Convert toolNameToDetailList to MCP Tool format for sampling
19509
- */
19510
- convertToMcpTools() {
19511
- return this.toolNameToDetailList.map(([name, detail]) => ({
19512
- name,
19513
- description: detail.description || `Tool: ${name}`,
19514
- inputSchema: {
19515
- type: "object",
19516
- ...detail.inputSchema
19517
- }
19518
- }));
19519
- }
19520
- /**
19521
- * Check if client supports sampling with tools
19522
- */
19523
- supportsSamplingTools() {
19524
- const capabilities = this.server.getClientCapabilities();
19525
- return !!capabilities?.sampling?.tools;
19526
- }
19527
- /**
19528
- * Check if response contains tool use
19529
- */
19530
- isToolUseResponse(response) {
19531
- if (!response.content) return false;
19532
- const content = Array.isArray(response.content) ? response.content : [
19533
- response.content
19534
- ];
19535
- return content.some((block) => block.type === "tool_use");
18138
+ return {
18139
+ content: [
18140
+ {
18141
+ type: "text",
18142
+ text: schemas.length > 0 ? schemas.join("\n\n") : "No schemas found for requested tools."
18143
+ }
18144
+ ]
18145
+ };
19536
18146
  }
19537
18147
  /**
19538
- * Extract tool calls from response
18148
+ * Execute a tool with runtime validation
19539
18149
  */
19540
- extractToolCalls(response) {
19541
- if (!response.content) return [];
19542
- const content = Array.isArray(response.content) ? response.content : [
19543
- response.content
19544
- ];
19545
- return content.filter((block) => block.type === "tool_use").map((block) => "id" in block && "name" in block && "input" in block ? {
19546
- id: block.id,
19547
- name: block.name,
19548
- input: block.input || {}
19549
- } : {
19550
- id: "",
19551
- name: "",
19552
- input: {}
19553
- });
19554
- }
19555
- async runSamplingLoop(systemPrompt, schema, state) {
19556
- const useTools = this.supportsSamplingTools();
19557
- this.logger.debug({
19558
- message: "Sampling mode determined",
19559
- useTools,
19560
- mode: useTools ? "native_tools" : "json_fallback"
19561
- });
19562
- this.conversationHistory = [
19563
- {
19564
- // Failed: 400 {"error":{"message":"messages: at least one message is required","code":"invalid_request_body"}}
19565
- role: "user",
19566
- content: {
19567
- type: "text",
19568
- text: `start`
19569
- }
18150
+ async executeTool(tool2, toolArgs, executeSpan) {
18151
+ const externalTool = this.toolNameToDetailList.find(([name]) => name === tool2);
18152
+ if (externalTool) {
18153
+ const [, toolDetail] = externalTool;
18154
+ if (executeSpan) {
18155
+ executeSpan.setAttributes({
18156
+ toolType: "external",
18157
+ selectedTool: tool2
18158
+ });
19570
18159
  }
19571
- ];
19572
- const loopSpan = this.tracingEnabled ? startSpan("mcpc.sampling_loop", {
19573
- agent: this.name,
19574
- maxIterations: this.maxIterations,
19575
- systemPrompt: systemPrompt()
19576
- }) : null;
19577
- try {
19578
- for (this.currentIteration = 0; this.currentIteration < this.maxIterations; this.currentIteration++) {
19579
- let iterationSpan = null;
19580
- try {
19581
- let createMessageParams;
19582
- if (useTools) {
19583
- createMessageParams = {
19584
- systemPrompt: systemPrompt(),
19585
- messages: this.conversationHistory,
19586
- maxTokens: 55e3,
19587
- tools: this.convertToMcpTools(),
19588
- toolChoice: {
19589
- mode: "auto"
19590
- }
19591
- };
19592
- } else {
19593
- createMessageParams = {
19594
- systemPrompt: systemPrompt(),
19595
- messages: this.conversationHistory,
19596
- maxTokens: 55e3
19597
- };
19598
- }
19599
- const response = await this.server.createMessage(createMessageParams);
19600
- const model = response.model;
19601
- const stopReason = response.stopReason;
19602
- const role = response.role;
19603
- if (useTools && this.isToolUseResponse(response)) {
19604
- const toolCalls = this.extractToolCalls(response);
19605
- if (toolCalls.length === 0) {
19606
- const contentArray = Array.isArray(response.content) ? response.content : [
19607
- response.content
19608
- ];
19609
- const textBlock = contentArray.find((c) => c.type === "text");
19610
- const textContent2 = textBlock && "text" in textBlock ? textBlock.text : void 0;
19611
- if (textContent2) {
19612
- return await this.createCompletionResult(textContent2, loopSpan);
19613
- }
19614
- continue;
19615
- }
19616
- iterationSpan = this.tracingEnabled ? startSpan("mcpc.sampling_iteration.tool_use", {
19617
- iteration: this.currentIteration + 1,
19618
- agent: this.name,
19619
- toolCalls: toolCalls.length,
19620
- maxIterations: this.maxIterations
19621
- }, loopSpan ?? void 0) : null;
19622
- this.conversationHistory.push({
19623
- role: "assistant",
19624
- content: response.content
19625
- });
19626
- const toolResults = [];
19627
- for (const toolCall of toolCalls) {
19628
- try {
19629
- const result2 = await this.server.callTool(toolCall.name, toolCall.input);
19630
- toolResults.push({
19631
- type: "tool_result",
19632
- toolUseId: toolCall.id,
19633
- content: result2.content || [],
19634
- isError: result2.isError
19635
- });
19636
- } catch (error2) {
19637
- toolResults.push({
19638
- type: "tool_result",
19639
- toolUseId: toolCall.id,
19640
- content: [
19641
- {
19642
- type: "text",
19643
- text: `Error: ${error2 instanceof Error ? error2.message : String(error2)}`
19644
- }
19645
- ],
19646
- isError: true
19647
- });
19648
- }
19649
- }
19650
- this.conversationHistory.push({
19651
- role: "user",
19652
- content: toolResults
19653
- });
19654
- if (iterationSpan) {
19655
- iterationSpan.setAttributes({
19656
- toolExecutions: toolResults.length,
19657
- hasErrors: toolResults.some((r) => r.isError)
19658
- });
19659
- endSpan(iterationSpan);
19660
- }
19661
- continue;
19662
- }
19663
- const content = Array.isArray(response.content) ? response.content : [
19664
- response.content
19665
- ];
19666
- const textContent = content.find((c) => c.type === "text");
19667
- const responseContent = textContent?.text || "{}";
19668
- let parsedData;
19669
- try {
19670
- parsedData = parseJSON(responseContent.trim(), true);
19671
- } catch (parseError) {
19672
- iterationSpan = this.tracingEnabled ? startSpan("mcpc.sampling_iteration.parse_error", {
19673
- iteration: this.currentIteration + 1,
19674
- agent: this.name,
19675
- error: String(parseError),
19676
- maxIterations: this.maxIterations
19677
- }, loopSpan ?? void 0) : null;
19678
- this.addParsingErrorToHistory(responseContent, parseError);
19679
- if (iterationSpan) endSpan(iterationSpan);
19680
- continue;
19681
- }
19682
- this.conversationHistory.push({
19683
- role: "assistant",
19684
- content: {
19685
- type: "text",
19686
- text: JSON.stringify(parsedData, null, 2)
19687
- }
19688
- });
19689
- const decision = parsedData["decision"];
19690
- const useTool = parsedData["useTool"];
19691
- const actionStr = decision === "complete" ? "completion" : useTool && typeof useTool === "string" ? String(useTool) : "unknown_action";
19692
- const spanName = `mcpc.sampling_iteration.${actionStr}`;
19693
- iterationSpan = this.tracingEnabled ? startSpan(spanName, {
19694
- iteration: this.currentIteration + 1,
19695
- agent: this.name,
19696
- action: actionStr,
19697
- systemPrompt: systemPrompt(),
19698
- maxTokens: String(Number.MAX_SAFE_INTEGER),
19699
- maxIterations: this.maxIterations,
19700
- messages: JSON.stringify(this.conversationHistory)
19701
- }, loopSpan ?? void 0) : null;
19702
- const result = await this.processAction(parsedData, schema, state, iterationSpan);
19703
- this.logIterationProgress(parsedData, result, model, stopReason, role);
19704
- if (iterationSpan) {
19705
- let rawJson = "{}";
19706
- try {
19707
- rawJson = parsedData ? JSON.stringify(parsedData) : "{}";
19708
- } catch {
19709
- }
19710
- const attr = {
19711
- isError: !!result.isError,
19712
- isComplete: !!result.isComplete,
19713
- iteration: this.currentIteration + 1,
19714
- maxIterations: this.maxIterations,
19715
- parsed: rawJson,
19716
- action: typeof useTool === "string" ? useTool : String(useTool),
19717
- decision: typeof decision === "string" ? decision : String(decision),
19718
- samplingResponse: responseContent,
19719
- toolResult: JSON.stringify(result),
19720
- model,
19721
- role
19722
- };
19723
- if (stopReason) {
19724
- attr.stopReason = stopReason;
19725
- }
19726
- iterationSpan.setAttributes(attr);
19727
- }
19728
- if (result.isError) {
19729
- const errorText = result.content?.[0] && "text" in result.content[0] ? result.content[0].text : "Unknown error";
19730
- this.conversationHistory.push({
19731
- role: "user",
19732
- content: {
19733
- type: "text",
19734
- text: errorText
19735
- }
18160
+ if (toolDetail.inputSchema) {
18161
+ const rawSchema = extractJsonSchema(toolDetail.inputSchema);
18162
+ const validation = validateSchema(toolArgs, rawSchema);
18163
+ if (!validation.valid) {
18164
+ if (executeSpan) {
18165
+ executeSpan.setAttributes({
18166
+ validationError: true,
18167
+ errorMessage: validation.error
19736
18168
  });
19737
- if (iterationSpan) endSpan(iterationSpan);
19738
- continue;
19739
- }
19740
- if (result.isComplete) {
19741
- if (iterationSpan) endSpan(iterationSpan);
19742
- if (loopSpan) endSpan(loopSpan);
19743
- return result;
19744
- }
19745
- if (iterationSpan) endSpan(iterationSpan);
19746
- } catch (iterError) {
19747
- if (iterationSpan) endSpan(iterationSpan, iterError);
19748
- throw iterError;
19749
- }
19750
- }
19751
- if (loopSpan) endSpan(loopSpan);
19752
- return await this.createMaxIterationsError(loopSpan);
19753
- } catch (error2) {
19754
- if (loopSpan) endSpan(loopSpan, error2);
19755
- return await this.createExecutionError(error2, loopSpan);
19756
- }
19757
- }
19758
- addParsingErrorToHistory(_responseText, parseError) {
19759
- const errorMsg = parseError instanceof Error ? parseError.message : String(parseError);
19760
- this.conversationHistory.push({
19761
- role: "user",
19762
- content: {
19763
- type: "text",
19764
- text: `Invalid JSON: ${errorMsg}
19765
-
19766
- Respond with valid JSON.`
19767
- }
19768
- });
19769
- }
19770
- async createMaxIterationsError(parentSpan) {
19771
- const result = await this.createCompletionResult(`Reached max iterations (${this.maxIterations}). Try a more specific request.`, parentSpan);
19772
- result.isError = true;
19773
- result.isComplete = false;
19774
- return result;
19775
- }
19776
- async createExecutionError(error2, parentSpan) {
19777
- const result = await this.createCompletionResult(`Execution error: ${error2 instanceof Error ? error2.message : String(error2)}`, parentSpan);
19778
- result.isError = true;
19779
- result.isComplete = false;
19780
- return result;
19781
- }
19782
- async createCompletionResult(text, parentSpan) {
19783
- const summary = this.summarize ? await this.summarizeConversation(parentSpan) : this.formatConversation();
19784
- return {
19785
- content: [
19786
- {
19787
- type: "text",
19788
- text: `${text}
19789
-
19790
- **Execution Summary:**
19791
- - Iterations used: ${this.currentIteration + 1}/${this.maxIterations}
19792
- - Agent: ${this.name}
19793
- ${summary}`
19794
- }
19795
- ],
19796
- isError: false,
19797
- isComplete: true
19798
- };
19799
- }
19800
- // Use LLM to create high-signal summary for parent agent
19801
- async summarizeConversation(parentSpan) {
19802
- if (this.conversationHistory.length === 0) {
19803
- return "\n\n**No conversation history**";
19804
- }
19805
- if (this.conversationHistory.length <= 3) {
19806
- return this.formatConversation();
19807
- }
19808
- const summarizeSpan = this.tracingEnabled ? startSpan("mcpc.sampling_summarize", {
19809
- agent: this.name,
19810
- messageCount: this.conversationHistory.length
19811
- }, parentSpan ?? void 0) : null;
19812
- try {
19813
- this.logger.debug({
19814
- message: "Starting conversation summarization",
19815
- messageCount: this.conversationHistory.length
19816
- });
19817
- const history = this.conversationHistory.map((msg, i) => {
19818
- const prefix = `[${i + 1}] ${msg.role.toUpperCase()}`;
19819
- const contentArray = Array.isArray(msg.content) ? msg.content : [
19820
- msg.content
19821
- ];
19822
- const textBlock = contentArray.find((c) => c.type === "text");
19823
- const text = textBlock?.text || "(No text content)";
19824
- return `${prefix}:
19825
- ${text}`;
19826
- }).join("\n\n---\n\n");
19827
- const response = await this.server.createMessage({
19828
- systemPrompt: `Summarize this agent execution:
19829
-
19830
- Final Decision: (include complete JSON if present)
19831
- Key Findings: (most important)
19832
- Actions Taken: (high-level flow)
19833
- Errors/Warnings: (if any)
19834
-
19835
- ${history}`,
19836
- messages: [
19837
- {
19838
- role: "user",
19839
- content: {
19840
- type: "text",
19841
- text: "Please provide a concise summary."
19842
- }
18169
+ endSpan(executeSpan);
19843
18170
  }
19844
- ],
19845
- maxTokens: 3e3
19846
- });
19847
- const summaryContent = Array.isArray(response.content) ? response.content.find((c) => c.type === "text") : response.content;
19848
- const summary = "\n\n" + (summaryContent?.text || "No summary available");
18171
+ return {
18172
+ content: [
18173
+ {
18174
+ type: "text",
18175
+ text: `Parameter validation failed for "${tool2}": ${validation.error}`
18176
+ }
18177
+ ],
18178
+ isError: true
18179
+ };
18180
+ }
18181
+ }
19849
18182
  this.logger.debug({
19850
- message: "Summarization completed",
19851
- summaryLength: summary.length
18183
+ message: "Executing external tool",
18184
+ tool: tool2
19852
18185
  });
19853
- if (summarizeSpan) {
19854
- summarizeSpan.setAttributes({
19855
- summaryLength: summary.length,
19856
- summary,
19857
- success: true
18186
+ const result = await toolDetail.execute(toolArgs);
18187
+ if (executeSpan) {
18188
+ executeSpan.setAttributes({
18189
+ success: true,
18190
+ isError: !!result.isError,
18191
+ resultContentLength: result.content?.length || 0
19858
18192
  });
19859
- endSpan(summarizeSpan);
19860
- }
19861
- return summary;
19862
- } catch (error2) {
19863
- this.logger.warning({
19864
- message: "Summarization failed, falling back to full history",
19865
- error: String(error2)
19866
- });
19867
- if (summarizeSpan) {
19868
- endSpan(summarizeSpan, error2);
18193
+ endSpan(executeSpan);
19869
18194
  }
19870
- return this.formatConversation();
19871
- }
19872
- }
19873
- // Format full conversation history (for debugging)
19874
- formatConversation() {
19875
- if (this.conversationHistory.length === 0) {
19876
- return "\n\n**No conversation history**";
18195
+ return result;
19877
18196
  }
19878
- const messages = this.conversationHistory.map((msg, i) => {
19879
- const header = `### Message ${i + 1}: ${msg.role}`;
19880
- const contentArray = Array.isArray(msg.content) ? msg.content : [
19881
- msg.content
19882
- ];
19883
- const textBlock = contentArray.find((c) => c.type === "text");
19884
- const contentText = textBlock?.text;
19885
- if (!contentText) {
19886
- return `${header}\\n(No text content)`;
18197
+ if (this.allToolNames.includes(tool2)) {
18198
+ if (executeSpan) {
18199
+ executeSpan.setAttributes({
18200
+ toolType: "internal",
18201
+ selectedTool: tool2
18202
+ });
19887
18203
  }
18204
+ this.logger.debug({
18205
+ message: "Executing internal tool",
18206
+ tool: tool2
18207
+ });
19888
18208
  try {
19889
- const parsed = JSON.parse(contentText);
19890
- if (JSON.stringify(parsed).length < 100) {
19891
- return `${header}\\n${JSON.stringify(parsed)}`;
18209
+ const result = await this.server.callTool(tool2, toolArgs);
18210
+ const callToolResult = result ?? {
18211
+ content: []
18212
+ };
18213
+ if (executeSpan) {
18214
+ executeSpan.setAttributes({
18215
+ success: true,
18216
+ isError: !!callToolResult.isError,
18217
+ resultContentLength: callToolResult.content?.length || 0
18218
+ });
18219
+ endSpan(executeSpan);
19892
18220
  }
19893
- return `${header}\\n\`\`\`json\\n${JSON.stringify(parsed, null, 2)}\\n\`\`\``;
19894
- } catch {
19895
- return `${header}\\n${contentText}`;
18221
+ return callToolResult;
18222
+ } catch (error2) {
18223
+ if (executeSpan) {
18224
+ endSpan(executeSpan, error2);
18225
+ }
18226
+ this.logger.error({
18227
+ message: "Error executing internal tool",
18228
+ tool: tool2,
18229
+ error: String(error2)
18230
+ });
18231
+ return {
18232
+ content: [
18233
+ {
18234
+ type: "text",
18235
+ text: `Error executing tool "${tool2}": ${error2 instanceof Error ? error2.message : String(error2)}`
18236
+ }
18237
+ ],
18238
+ isError: true
18239
+ };
19896
18240
  }
19897
- });
19898
- return "\n\n**Conversation History:**\n" + messages.join("\n\n");
19899
- }
19900
- logIterationProgress(parsedData, result, model, stopReason, role) {
19901
- this.logger.debug({
19902
- iteration: `${this.currentIteration + 1}/${this.maxIterations}`,
19903
- parsedData,
19904
- isError: result.isError,
19905
- isComplete: result.isComplete,
19906
- model,
19907
- stopReason,
19908
- role,
19909
- result
19910
- });
19911
- }
19912
- formatPromptForMode({ prompt, schema, schemaPrefix = "JSON schema:", schemaSuffix = `STRICT REQUIREMENTS:
19913
- 1. Return ONE AND ONLY ONE raw JSON object that passes JSON.parse() - no markdown, code blocks, explanatory text, or multiple JSON objects
19914
- 2. Include ALL required fields with correct data types and satisfy ALL schema constraints (anyOf, oneOf, allOf, not, enum, pattern, min/max, conditionals)
19915
- 3. Your response must be a single JSON object, nothing else
19916
-
19917
- INVALID: \`\`\`json{"key":"value"}\`\`\` or "Here is: {"key":"value"}" or {"key":"value"}{"key":"value"}
19918
- VALID: {"key":"value"}` }) {
19919
- if (this.supportsSamplingTools()) {
19920
- return prompt && prompt.length > 0 ? prompt : "";
19921
18241
  }
19922
- return [
19923
- prompt != null && prompt.length > 0 ? prompt : void 0,
19924
- prompt != null && prompt.length > 0 ? "" : void 0,
19925
- schemaPrefix,
19926
- schema != null ? JSON.stringify(createModelCompatibleJSONSchema(schema), null, 2) : void 0,
19927
- schemaSuffix
19928
- ].filter((line) => line != null).join("\n");
19929
- }
19930
- // Validate arguments using JSON schema
19931
- validateInput(args, schema) {
18242
+ if (executeSpan) {
18243
+ executeSpan.setAttributes({
18244
+ toolType: "not_found",
18245
+ tool: tool2
18246
+ });
18247
+ endSpan(executeSpan);
18248
+ }
18249
+ return {
18250
+ content: [
18251
+ {
18252
+ type: "text",
18253
+ text: `Tool "${tool2}" not found. Available tools: ${this.allToolNames.join(", ")}`
18254
+ }
18255
+ ],
18256
+ isError: true
18257
+ };
18258
+ }
18259
+ validate(args, schema) {
19932
18260
  return validateSchema(args, schema);
19933
18261
  }
19934
18262
  };
19935
18263
 
19936
- // __mcpc__core_latest/node_modules/@mcpc/core/src/executors/sampling/agentic-sampling-executor.js
19937
- var SamplingExecutor = class extends BaseSamplingExecutor {
19938
- agenticExecutor;
19939
- constructor(name, description, allToolNames, toolNameToDetailList, server, config2) {
19940
- super(name, description, allToolNames, toolNameToDetailList, server, config2);
19941
- this.agenticExecutor = new AgenticExecutor(name, allToolNames, toolNameToDetailList, server);
19942
- }
19943
- buildDepGroups() {
19944
- const depGroups = {};
19945
- this.toolNameToDetailList.forEach(([toolName, tool2]) => {
19946
- if (tool2?.inputSchema) {
19947
- depGroups[toolName] = {
19948
- type: "object",
19949
- description: tool2.description || `Tool: ${toolName}`,
19950
- ...tool2.inputSchema
19951
- };
19952
- } else {
19953
- const toolSchema = this.server.getHiddenToolSchema(toolName);
19954
- if (toolSchema) {
19955
- depGroups[toolName] = {
19956
- ...toolSchema.schema,
19957
- description: toolSchema.description
19958
- };
19959
- }
19960
- }
19961
- });
19962
- return depGroups;
19963
- }
19964
- executeSampling(args, schema) {
19965
- const validationResult = validateSchema(args, schema);
19966
- if (!validationResult.valid) {
18264
+ // __mcpc__core_latest/node_modules/@mcpc/core/src/factories/args-def-factory.js
18265
+ function createArgsDefFactory(_name, _allToolNames, _depGroups, _predefinedSteps, _ensureStepActions) {
18266
+ return {
18267
+ forSampling: function() {
19967
18268
  return {
19968
- content: [
19969
- {
19970
- type: "text",
19971
- text: CompiledPrompts.errorResponse({
19972
- errorMessage: validationResult.error || "Validation failed"
19973
- })
18269
+ type: "object",
18270
+ description: "Provide prompt for autonomous tool execution",
18271
+ properties: {
18272
+ prompt: {
18273
+ type: "string",
18274
+ description: "The task to be completed autonomously by the agentic system using available tools"
18275
+ },
18276
+ context: {
18277
+ type: "object",
18278
+ description: "Execution context, e.g., { cwd: '/path/to/dir' }. Any relevant fields allowed.",
18279
+ additionalProperties: true
19974
18280
  }
18281
+ },
18282
+ required: [
18283
+ "prompt",
18284
+ "context"
19975
18285
  ],
19976
- isError: true
19977
- };
19978
- }
19979
- const createArgsDef = createArgsDefFactory(this.name, this.allToolNames, this.buildDepGroups(), void 0, void 0);
19980
- const agenticSchema = createArgsDef.forAgentic(this.toolNameToDetailList, true);
19981
- const systemPrompt = this.buildSystemPrompt(args.userRequest, agenticSchema, args.context && typeof args.context === "object" ? args.context : void 0);
19982
- return this.runSamplingLoop(() => systemPrompt, agenticSchema);
19983
- }
19984
- async processAction(parsedData, schema, _state, parentSpan) {
19985
- const toolCallData = parsedData;
19986
- if (toolCallData.decision === "complete") {
19987
- return await this.createCompletionResult("Task completed", parentSpan);
19988
- }
19989
- try {
19990
- const { action: _action, decision: _decision, ..._toolArgs } = toolCallData;
19991
- const toolResult = await this.agenticExecutor.execute(toolCallData, schema, parentSpan);
19992
- const resultText = toolResult.content?.filter((content) => content.type === "text")?.map((content) => content.text)?.join("\n") || "No result";
19993
- this.conversationHistory.push({
19994
- role: "assistant",
19995
- content: {
19996
- type: "text",
19997
- text: resultText
18286
+ errorMessage: {
18287
+ required: {
18288
+ prompt: "Missing required field 'prompt'. Please provide a clear task description.",
18289
+ context: "Missing required field 'context'. Please provide relevant context (e.g., { cwd: '...' })."
18290
+ }
19998
18291
  }
19999
- });
20000
- return toolResult;
20001
- } catch (error2) {
20002
- return this.createExecutionError(error2, parentSpan);
20003
- }
20004
- }
20005
- buildSystemPrompt(userRequest, agenticSchema, context2) {
20006
- const toolList = this.allToolNames.map((name) => {
20007
- const tool2 = this.toolNameToDetailList.find(([toolName]) => toolName === name);
20008
- const toolSchema = this.server.getHiddenToolSchema(name);
20009
- if (tool2 && tool2[1]) {
20010
- return `- ${name}: ${tool2[1].description || `Tool: ${name}`}`;
20011
- } else if (toolSchema) {
20012
- return `- ${name}: ${toolSchema.description}`;
20013
- }
20014
- return `- ${name}`;
20015
- }).join("\n");
20016
- let contextInfo = "";
20017
- if (context2 && typeof context2 === "object" && Object.keys(context2).length > 0) {
20018
- contextInfo = `
20019
-
20020
- Context:
20021
- ${JSON.stringify(context2, null, 2)}`;
20022
- }
20023
- const basePrompt = this.supportsSamplingTools() ? CompiledPrompts.samplingExecutionTools({
20024
- toolName: this.name,
20025
- description: this.description,
20026
- toolList
20027
- }) : CompiledPrompts.samplingExecution({
20028
- toolName: this.name,
20029
- description: this.description,
20030
- toolList
20031
- });
20032
- const taskPrompt = `
20033
-
20034
- ## Current Task
20035
- You will now use agentic sampling to complete the following task: "${userRequest}"${contextInfo}
20036
-
20037
- When you need to use a tool, specify the tool name in 'useTool' and provide tool-specific parameters as additional properties.`;
20038
- return this.formatPromptForMode({
20039
- prompt: basePrompt + taskPrompt,
20040
- schema: agenticSchema
20041
- });
20042
- }
20043
- };
20044
-
20045
- // __mcpc__core_latest/node_modules/@mcpc/core/src/executors/agentic/agentic-sampling-registrar.js
20046
- function registerAgenticSamplingTool(server, { description, name, allToolNames, depGroups, toolNameToDetailList, samplingConfig }) {
20047
- const createArgsDef = createArgsDefFactory(name, allToolNames, depGroups, void 0, void 0);
20048
- const samplingExecutor = new SamplingExecutor(name, description, allToolNames, toolNameToDetailList, server, samplingConfig);
20049
- const toolDescription = CompiledPrompts.samplingToolDescription({
20050
- description,
20051
- toolList: allToolNames.map((name2) => `- ${name2}`).join("\n")
20052
- });
20053
- const argsDef = createArgsDef.forSampling();
20054
- const schema = allToolNames.length > 0 ? argsDef : {
20055
- type: "object",
20056
- properties: {}
20057
- };
20058
- server.tool(name, toolDescription, jsonSchema(createModelCompatibleJSONSchema(schema)), async (args) => {
20059
- return await samplingExecutor.executeSampling(args, schema);
20060
- });
20061
- }
20062
-
20063
- // __mcpc__core_latest/node_modules/@mcpc/core/src/plugins/built-in/mode-agentic-sampling-plugin.js
20064
- var createAgenticSamplingModePlugin = () => ({
20065
- name: "mode-agentic-sampling",
20066
- version: "1.0.0",
20067
- // Only apply to agentic_sampling mode
20068
- apply: "agentic_sampling",
20069
- // Register the agent tool with sampling
20070
- registerAgentTool: (context2) => {
20071
- registerAgenticSamplingTool(context2.server, {
20072
- description: context2.description,
20073
- name: context2.name,
20074
- allToolNames: context2.allToolNames,
20075
- depGroups: context2.depGroups,
20076
- toolNameToDetailList: context2.toolNameToDetailList,
20077
- samplingConfig: context2.options.samplingConfig
20078
- });
20079
- }
20080
- });
20081
- var mode_agentic_sampling_plugin_default = createAgenticSamplingModePlugin();
20082
-
20083
- // __mcpc__core_latest/node_modules/@mcpc/core/src/executors/sampling/workflow-sampling-executor.js
20084
- var WorkflowSamplingExecutor = class extends BaseSamplingExecutor {
20085
- createArgsDef;
20086
- predefinedSteps;
20087
- workflowExecutor;
20088
- constructor(name, description, allToolNames, toolNameToDetailList, createArgsDef, server, predefinedSteps, config2) {
20089
- super(name, description, allToolNames, toolNameToDetailList, server, config2), this.createArgsDef = createArgsDef, this.predefinedSteps = predefinedSteps;
20090
- this.workflowExecutor = new WorkflowExecutor(name, allToolNames, toolNameToDetailList, createArgsDef, server, predefinedSteps);
20091
- }
20092
- async executeWorkflowSampling(args, schema, state) {
20093
- const validationResult = validateSchema(args, schema);
20094
- if (!validationResult.valid) {
18292
+ };
18293
+ },
18294
+ /**
18295
+ * Agentic schema - simplified Unix-style interface
18296
+ *
18297
+ * Only two fields:
18298
+ * - `tool`: which tool to execute (enum includes "man" + all tool names)
18299
+ * - `args`: parameters for the tool (array for "man", object for others)
18300
+ */
18301
+ forAgentic: function(allToolNames) {
18302
+ const toolEnum = [
18303
+ "man",
18304
+ ...allToolNames
18305
+ ];
20095
18306
  return {
20096
- content: [
20097
- {
20098
- type: "text",
20099
- text: CompiledPrompts.workflowErrorResponse({
20100
- errorMessage: validationResult.error || "Validation failed"
20101
- })
18307
+ type: "object",
18308
+ properties: {
18309
+ tool: {
18310
+ type: "string",
18311
+ enum: toolEnum,
18312
+ description: 'Which tool to execute. Use "man" to get tool schemas, or a tool name to execute.',
18313
+ errorMessage: {
18314
+ enum: `Invalid tool. Available: ${toolEnum.join(", ")}`
18315
+ }
18316
+ },
18317
+ args: {
18318
+ description: 'For "man": array of tool names ["tool1", "tool2"]. For other tools: object with parameters.'
20102
18319
  }
18320
+ },
18321
+ required: [
18322
+ "tool"
20103
18323
  ],
20104
- isError: true
18324
+ additionalProperties: false
20105
18325
  };
20106
18326
  }
20107
- return await this.runSamplingLoop(() => this.buildWorkflowSystemPrompt(args, state), schema, state);
20108
- }
20109
- async processAction(parsedData, _schema, state, parentSpan) {
20110
- const workflowState = state;
20111
- if (!workflowState) {
20112
- throw new Error("WorkflowState is required for workflow");
20113
- }
20114
- const toolCallData = parsedData;
20115
- if (toolCallData.decision === "complete") {
20116
- return await this.createCompletionResult("Task completed", parentSpan);
20117
- }
20118
- try {
20119
- const workflowResult = await this.workflowExecutor.execute(parsedData, workflowState);
20120
- const resultText = workflowResult.content?.filter((content) => content.type === "text")?.map((content) => content.text)?.join("\n") || "No result";
20121
- this.conversationHistory.push({
20122
- role: "assistant",
20123
- content: {
20124
- type: "text",
20125
- text: resultText
20126
- }
20127
- });
20128
- return workflowResult;
20129
- } catch (error2) {
20130
- return this.createExecutionError(error2, parentSpan);
20131
- }
20132
- }
20133
- buildWorkflowSystemPrompt(args, state) {
20134
- const workflowSchema = this.createArgsDef.forCurrentState(state);
20135
- const basePrompt = this.supportsSamplingTools() ? CompiledPrompts.samplingWorkflowExecutionTools({
20136
- toolName: this.name,
20137
- description: this.description,
20138
- workflowSchema: `${JSON.stringify(workflowSchema, null, 2)}`
20139
- }) : CompiledPrompts.samplingWorkflowExecution({
20140
- toolName: this.name,
20141
- description: this.description,
20142
- workflowSchema: `${JSON.stringify(workflowSchema, null, 2)}`
20143
- });
20144
- let contextInfo = "";
20145
- if (args.context && typeof args.context === "object" && Object.keys(args.context).length > 0) {
20146
- contextInfo = `
20147
-
20148
- Context:
20149
- ${JSON.stringify(args.context, null, 2)}`;
20150
- }
20151
- const workflowPrompt = `
20152
-
20153
- Current Task: <user_request>${args.userRequest}</user_request>${contextInfo}`;
20154
- return this.formatPromptForMode({
20155
- prompt: basePrompt + workflowPrompt,
20156
- schema: workflowSchema
20157
- });
20158
- }
20159
- };
18327
+ };
18328
+ }
20160
18329
 
20161
- // __mcpc__core_latest/node_modules/@mcpc/core/src/executors/workflow/workflow-sampling-registrar.js
20162
- function registerWorkflowSamplingTool(server, { description, name, allToolNames, depGroups, toolNameToDetailList, predefinedSteps, samplingConfig, ensureStepActions, toolNameToIdMapping: _toolNameToIdMapping }) {
20163
- const createArgsDef = createArgsDefFactory(name, allToolNames, depGroups, predefinedSteps, ensureStepActions);
20164
- const workflowSamplingExecutor = new WorkflowSamplingExecutor(name, description, allToolNames, toolNameToDetailList, createArgsDef, server, predefinedSteps, samplingConfig);
20165
- const workflowState = new WorkflowState();
20166
- const baseDescription = CompiledPrompts.samplingExecution({
18330
+ // __mcpc__core_latest/node_modules/@mcpc/core/src/executors/agentic/agentic-tool-registrar.js
18331
+ function registerAgenticTool(server, { description, name, allToolNames, depGroups, toolNameToDetailList }) {
18332
+ const createArgsDef = createArgsDefFactory(name, allToolNames, depGroups, void 0, void 0);
18333
+ const agenticExecutor = new AgenticExecutor(name, allToolNames, toolNameToDetailList, server);
18334
+ description = CompiledPrompts.autonomousExecution({
20167
18335
  toolName: name,
20168
- description,
20169
- toolList: allToolNames.map((name2) => `- ${name2}`).join("\n")
18336
+ description
20170
18337
  });
20171
- const argsDef = createArgsDef.forSampling();
18338
+ const agenticArgsDef = createArgsDef.forAgentic(allToolNames);
18339
+ const argsDef = agenticArgsDef;
20172
18340
  const schema = allToolNames.length > 0 ? argsDef : {
20173
18341
  type: "object",
20174
18342
  properties: {}
20175
18343
  };
20176
- server.tool(name, baseDescription, jsonSchema(createModelCompatibleJSONSchema(schema)), async (args) => {
20177
- try {
20178
- return await workflowSamplingExecutor.executeWorkflowSampling(args, schema, workflowState);
20179
- } catch (error2) {
20180
- workflowState.reset();
20181
- return {
20182
- content: [
20183
- {
20184
- type: "text",
20185
- text: `Workflow execution error: ${error2.message}`
20186
- }
20187
- ],
20188
- isError: true
20189
- };
20190
- }
18344
+ server.tool(name, description, jsonSchema(createModelCompatibleJSONSchema(schema)), async (args) => {
18345
+ return await agenticExecutor.execute(args, schema);
20191
18346
  });
20192
18347
  }
20193
18348
 
20194
- // __mcpc__core_latest/node_modules/@mcpc/core/src/plugins/built-in/mode-workflow-sampling-plugin.js
20195
- var createWorkflowSamplingModePlugin = () => ({
20196
- name: "mode-agentic-workflow-sampling",
20197
- version: "1.0.0",
20198
- // Only apply to agentic_workflow_sampling mode
20199
- apply: "agentic_workflow_sampling",
20200
- // Register the agent tool with sampling
18349
+ // __mcpc__core_latest/node_modules/@mcpc/core/src/plugins/built-in/mode-agentic-plugin.js
18350
+ var createAgenticModePlugin = () => ({
18351
+ name: "mode-agentic",
18352
+ version: "2.0.0",
18353
+ // Only apply to agentic mode
18354
+ apply: "agentic",
18355
+ // Register the agent tool
20201
18356
  registerAgentTool: (context2) => {
20202
- registerWorkflowSamplingTool(context2.server, {
18357
+ registerAgenticTool(context2.server, {
20203
18358
  description: context2.description,
20204
18359
  name: context2.name,
20205
18360
  allToolNames: context2.allToolNames,
20206
18361
  depGroups: context2.depGroups,
20207
- toolNameToDetailList: context2.toolNameToDetailList,
20208
- predefinedSteps: context2.options.steps,
20209
- samplingConfig: context2.options.samplingConfig,
20210
- ensureStepActions: context2.options.ensureStepActions,
20211
- toolNameToIdMapping: context2.toolNameToIdMapping
18362
+ toolNameToDetailList: context2.toolNameToDetailList
20212
18363
  });
20213
18364
  }
20214
18365
  });
20215
- var mode_workflow_sampling_plugin_default = createWorkflowSamplingModePlugin();
18366
+ var mode_agentic_plugin_default = createAgenticModePlugin();
20216
18367
 
20217
18368
  // __mcpc__core_latest/node_modules/@jsr/mcpc__mcp-sampling-ai-provider/src/utils.js
20218
18369
  function convertAISDKToMCPMessages(prompt) {
@@ -20269,6 +18420,7 @@ function convertMCPStopReasonToAISDK(stopReason) {
20269
18420
  }
20270
18421
 
20271
18422
  // __mcpc__core_latest/node_modules/@jsr/mcpc__mcp-sampling-ai-provider/src/language-model.js
18423
+ var DEFAULT_MAX_TOKENS = 128e3;
20272
18424
  var MCPSamplingLanguageModel = class {
20273
18425
  specificationVersion = "v2";
20274
18426
  provider;
@@ -20276,11 +18428,13 @@ var MCPSamplingLanguageModel = class {
20276
18428
  supportedUrls = {};
20277
18429
  server;
20278
18430
  modelPreferences;
18431
+ maxTokens;
20279
18432
  constructor(config2) {
20280
18433
  this.server = config2.server;
20281
18434
  this.modelId = "";
20282
18435
  this.provider = "mcp-client";
20283
18436
  this.modelPreferences = config2.modelPreferences;
18437
+ this.maxTokens = config2.maxTokens ?? DEFAULT_MAX_TOKENS;
20284
18438
  }
20285
18439
  /**
20286
18440
  * Generate a response using MCP's createMessage capability
@@ -20312,7 +18466,7 @@ var MCPSamplingLanguageModel = class {
20312
18466
  const createMessageParams = {
20313
18467
  systemPrompt,
20314
18468
  messages,
20315
- maxTokens: options.maxOutputTokens ?? 55e3,
18469
+ maxTokens: options.maxOutputTokens ?? this.maxTokens,
20316
18470
  modelPreferences: this.modelPreferences
20317
18471
  };
20318
18472
  if (useNativeTools && options.tools && options.tools.length > 0) {
@@ -20690,7 +18844,8 @@ var MCPSamplingProvider = class {
20690
18844
  languageModel(options) {
20691
18845
  return new MCPSamplingLanguageModel({
20692
18846
  server: this.config.server,
20693
- modelPreferences: options?.modelPreferences
18847
+ modelPreferences: options?.modelPreferences,
18848
+ maxTokens: this.config.maxTokens
20694
18849
  });
20695
18850
  }
20696
18851
  /**
@@ -20751,7 +18906,7 @@ var BaseAIExecutor = class {
20751
18906
  messages: [
20752
18907
  {
20753
18908
  role: "user",
20754
- content: args.userRequest
18909
+ content: args.prompt
20755
18910
  }
20756
18911
  ],
20757
18912
  tools: this.buildTools(),
@@ -20796,19 +18951,12 @@ var BaseAIExecutor = class {
20796
18951
  }
20797
18952
  }
20798
18953
  buildSystemPrompt(args) {
20799
- return `Agent \`${this.config.name}\` that completes tasks by calling tools.
20800
-
20801
- <manual>
20802
- ${this.config.description}
20803
- </manual>
20804
-
20805
- <rules>
20806
- ${this.getRules()}
20807
- </rules>
20808
-
20809
- <tools>
20810
- ${this.getToolListDescription()}
20811
- </tools>${args.context ? this.formatContext(args.context) : ""}`;
18954
+ return CompiledPrompts.aiLoopSystem({
18955
+ toolName: this.config.name,
18956
+ description: this.config.description,
18957
+ rules: this.getRules(),
18958
+ context: this.formatContext(args.context)
18959
+ });
20812
18960
  }
20813
18961
  getRules() {
20814
18962
  return `1. Use tools to complete the user's request
@@ -20817,10 +18965,10 @@ ${this.getToolListDescription()}
20817
18965
  4. Continue until task is complete
20818
18966
  5. When complete, provide a summary WITHOUT calling more tools`;
20819
18967
  }
20820
- getToolListDescription() {
20821
- return "Tools will be provided by AI SDK";
20822
- }
20823
18968
  formatContext(context2) {
18969
+ if (!context2 || Object.keys(context2).length === 0) {
18970
+ return "";
18971
+ }
20824
18972
  return `
20825
18973
 
20826
18974
  <context>
@@ -20828,11 +18976,12 @@ ${JSON.stringify(context2, null, 2)}
20828
18976
  </context>`;
20829
18977
  }
20830
18978
  convertToAISDKTool(name, toolDetail, execute) {
18979
+ const cleanedSchema = toolDetail.inputSchema ? cleanToolSchema(toolDetail.inputSchema) : {
18980
+ type: "object"
18981
+ };
20831
18982
  return tool({
20832
18983
  description: toolDetail.description || `Tool: ${name}`,
20833
- inputSchema: jsonSchema2(toolDetail.inputSchema || {
20834
- type: "object"
20835
- }),
18984
+ inputSchema: jsonSchema2(cleanedSchema),
20836
18985
  execute
20837
18986
  });
20838
18987
  }
@@ -20843,17 +18992,20 @@ var AISamplingExecutor = class extends BaseAIExecutor {
20843
18992
  server;
20844
18993
  tools;
20845
18994
  providerOptions;
18995
+ maxTokens;
20846
18996
  model = null;
20847
18997
  constructor(config2) {
20848
18998
  super(config2, "callTool" in config2.server ? config2.server : void 0);
20849
18999
  this.server = config2.server;
20850
19000
  this.tools = config2.tools;
20851
19001
  this.providerOptions = config2.providerOptions;
19002
+ this.maxTokens = config2.maxTokens;
20852
19003
  }
20853
19004
  initProvider() {
20854
19005
  if (!this.model) {
20855
19006
  const provider = new MCPSamplingProvider({
20856
- server: this.server
19007
+ server: this.server,
19008
+ maxTokens: this.maxTokens
20857
19009
  });
20858
19010
  this.model = provider.languageModel(this.providerOptions);
20859
19011
  }
@@ -20866,9 +19018,6 @@ var AISamplingExecutor = class extends BaseAIExecutor {
20866
19018
  getExecutorType() {
20867
19019
  return "mcp";
20868
19020
  }
20869
- getToolListDescription() {
20870
- return this.tools.map(([name, detail]) => `- ${name}: ${detail.description || "No description"}`).join("\n");
20871
- }
20872
19021
  buildTools() {
20873
19022
  const aiTools = {};
20874
19023
  for (const [name, detail] of this.tools) {
@@ -20899,7 +19048,7 @@ var AISamplingExecutor = class extends BaseAIExecutor {
20899
19048
 
20900
19049
  // __mcpc__core_latest/node_modules/@mcpc/core/src/executors/ai/ai-sampling-registrar.js
20901
19050
  function registerAISamplingTool(server, params) {
20902
- const { name, description, allToolNames, depGroups, toolNameToDetailList, providerOptions, maxSteps = 50, tracingEnabled = false } = params;
19051
+ const { name, description, allToolNames, depGroups, toolNameToDetailList, providerOptions, maxSteps = 50, tracingEnabled = false, maxTokens } = params;
20903
19052
  const createArgsDef = createArgsDefFactory(name, allToolNames, depGroups, void 0, void 0);
20904
19053
  const executor = new AISamplingExecutor({
20905
19054
  name,
@@ -20908,7 +19057,8 @@ function registerAISamplingTool(server, params) {
20908
19057
  tools: toolNameToDetailList,
20909
19058
  providerOptions,
20910
19059
  maxSteps,
20911
- tracingEnabled
19060
+ tracingEnabled,
19061
+ maxTokens
20912
19062
  });
20913
19063
  const toolDescription = CompiledPrompts.samplingToolDescription({
20914
19064
  toolName: name,
@@ -20921,9 +19071,23 @@ function registerAISamplingTool(server, params) {
20921
19071
  properties: {}
20922
19072
  };
20923
19073
  server.tool(name, toolDescription, jsonSchema(createModelCompatibleJSONSchema(schema)), (args) => {
20924
- const userRequest = typeof args.userRequest === "string" ? args.userRequest : JSON.stringify(args);
19074
+ const validationResult = validateSchema(args, schema);
19075
+ if (!validationResult.valid) {
19076
+ return {
19077
+ content: [
19078
+ {
19079
+ type: "text",
19080
+ text: CompiledPrompts.errorResponse({
19081
+ errorMessage: validationResult.error || "Validation failed"
19082
+ })
19083
+ }
19084
+ ],
19085
+ isError: true
19086
+ };
19087
+ }
19088
+ const prompt = typeof args.prompt === "string" ? args.prompt : JSON.stringify(args);
20925
19089
  return executor.execute({
20926
- userRequest,
19090
+ prompt,
20927
19091
  context: args.context
20928
19092
  });
20929
19093
  });
@@ -20944,7 +19108,8 @@ var createAISamplingModePlugin = () => ({
20944
19108
  toolNameToDetailList: context2.toolNameToDetailList,
20945
19109
  providerOptions: opts.providerOptions,
20946
19110
  maxSteps: opts.maxSteps,
20947
- tracingEnabled: opts.tracingEnabled
19111
+ tracingEnabled: opts.tracingEnabled,
19112
+ maxTokens: opts.maxTokens
20948
19113
  });
20949
19114
  }
20950
19115
  });
@@ -20976,12 +19141,6 @@ var AIACPExecutor = class extends BaseAIExecutor {
20976
19141
  getExecutorType() {
20977
19142
  return "acp";
20978
19143
  }
20979
- getToolListDescription() {
20980
- if (this.tools.length === 0) {
20981
- return "Tools will be provided by ACP agent";
20982
- }
20983
- return this.tools.map(([name, detail]) => `- ${name}: ${detail.description || "No description"}`).join("\n");
20984
- }
20985
19144
  buildTools() {
20986
19145
  const aiTools = {};
20987
19146
  for (const [name, detail] of this.tools) {
@@ -21033,9 +19192,23 @@ function registerAIACPTool(server, params) {
21033
19192
  properties: {}
21034
19193
  };
21035
19194
  server.tool(name, toolDescription, jsonSchema(createModelCompatibleJSONSchema(schema)), (args) => {
21036
- const userRequest = typeof args.userRequest === "string" ? args.userRequest : JSON.stringify(args);
19195
+ const validationResult = validateSchema(args, schema);
19196
+ if (!validationResult.valid) {
19197
+ return {
19198
+ content: [
19199
+ {
19200
+ type: "text",
19201
+ text: CompiledPrompts.errorResponse({
19202
+ errorMessage: validationResult.error || "Validation failed"
19203
+ })
19204
+ }
19205
+ ],
19206
+ isError: true
19207
+ };
19208
+ }
19209
+ const prompt = typeof args.prompt === "string" ? args.prompt : JSON.stringify(args);
21037
19210
  return executor.execute({
21038
- userRequest,
19211
+ prompt,
21039
19212
  context: args.context
21040
19213
  });
21041
19214
  });
@@ -21072,9 +19245,6 @@ function getBuiltInPlugins() {
21072
19245
  tool_name_mapping_plugin_default,
21073
19246
  config_plugin_default,
21074
19247
  mode_agentic_plugin_default,
21075
- mode_workflow_plugin_default,
21076
- mode_agentic_sampling_plugin_default,
21077
- mode_workflow_sampling_plugin_default,
21078
19248
  mode_ai_sampling_plugin_default,
21079
19249
  mode_ai_acp_plugin_default,
21080
19250
  logging_plugin_default
@@ -22051,14 +20221,6 @@ var ComposableMCPServer = class extends Server {
22051
20221
  if (!this.toolNameMapping.has(internalName)) {
22052
20222
  this.toolManager.setToolNameMapping(internalName, toolId);
22053
20223
  }
22054
- const matchingStep = options.steps?.find((step) => step.actions.includes(toolNameWithScope));
22055
- if (matchingStep) {
22056
- const actionIndex = matchingStep.actions.indexOf(toolNameWithScope);
22057
- if (actionIndex !== -1) {
22058
- matchingStep.actions[actionIndex] = toolId;
22059
- }
22060
- return true;
22061
- }
22062
20224
  return tagToResults.tool.find((tool2) => {
22063
20225
  const selectAll = tool2.attribs.name === `${mcpName}.${ALL_TOOLS_PLACEHOLDER2}` || tool2.attribs.name === `${mcpName}`;
22064
20226
  if (selectAll) {
@@ -22177,13 +20339,13 @@ var ComposableMCPServer = class extends Server {
22177
20339
  };
22178
20340
 
22179
20341
  // __mcpc__core_latest/node_modules/@mcpc/core/src/utils/common/env.js
22180
- import process8 from "node:process";
22181
- var isProdEnv = () => process8.env.NODE_ENV === "production";
22182
- var isSCF = () => Boolean(process8.env.SCF_RUNTIME || process8.env.PROD_SCF);
20342
+ import process7 from "node:process";
20343
+ var isProdEnv = () => process7.env.NODE_ENV === "production";
20344
+ var isSCF = () => Boolean(process7.env.SCF_RUNTIME || process7.env.PROD_SCF);
22183
20345
  if (isSCF()) {
22184
20346
  console.log({
22185
20347
  isSCF: isSCF(),
22186
- SCF_RUNTIME: process8.env.SCF_RUNTIME
20348
+ SCF_RUNTIME: process7.env.SCF_RUNTIME
22187
20349
  });
22188
20350
  }
22189
20351
 
@@ -22241,7 +20403,7 @@ export {
22241
20403
  jsonSchema,
22242
20404
  mcpc,
22243
20405
  optionalObject,
22244
- parseJSON2 as parseJSON,
20406
+ parseJSON,
22245
20407
  parseMcpcConfigs,
22246
20408
  truncateJSON
22247
20409
  };