@mcpc-tech/cli 0.1.28 → 0.1.30

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/bin/mcpc.cjs CHANGED
@@ -389,7 +389,7 @@ var require_parse = __commonJS({
389
389
  "use strict";
390
390
  var path = require("path");
391
391
  var resolveCommand = require_resolveCommand();
392
- var escape2 = require_escape();
392
+ var escape = require_escape();
393
393
  var readShebang = require_readShebang();
394
394
  var isWin = process.platform === "win32";
395
395
  var isExecutableRegExp = /\.(?:com|exe)$/i;
@@ -413,8 +413,8 @@ var require_parse = __commonJS({
413
413
  if (parsed.options.forceShell || needsShell) {
414
414
  const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
415
415
  parsed.command = path.normalize(parsed.command);
416
- parsed.command = escape2.command(parsed.command);
417
- parsed.args = parsed.args.map((arg) => escape2.argument(arg, needsDoubleEscapeMetaChars));
416
+ parsed.command = escape.command(parsed.command);
417
+ parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));
418
418
  const shellCommand = [parsed.command].concat(parsed.args).join(" ");
419
419
  parsed.args = ["/d", "/s", "/c", `"${shellCommand}"`];
420
420
  parsed.command = process.env.comspec || "cmd.exe";
@@ -2035,8 +2035,8 @@ var UrlElicitationRequiredError = class extends McpError {
2035
2035
 
2036
2036
  // __mcpc__cli_latest/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js
2037
2037
  var ReadBuffer = class {
2038
- append(chunk2) {
2039
- this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk2]) : chunk2;
2038
+ append(chunk) {
2039
+ this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk;
2040
2040
  }
2041
2041
  readMessage() {
2042
2042
  if (!this._buffer) {
@@ -2068,8 +2068,8 @@ var StdioServerTransport = class {
2068
2068
  this._stdout = _stdout;
2069
2069
  this._readBuffer = new ReadBuffer();
2070
2070
  this._started = false;
2071
- this._ondata = (chunk2) => {
2072
- this._readBuffer.append(chunk2);
2071
+ this._ondata = (chunk) => {
2072
+ this._readBuffer.append(chunk);
2073
2073
  this.processReadBuffer();
2074
2074
  };
2075
2075
  this._onerror = (error) => {
@@ -2508,9 +2508,8 @@ OPTIONS:
2508
2508
  --mode <mode> Set execution mode for all agents
2509
2509
  Supported modes:
2510
2510
  - agentic: Fully autonomous agent mode (default)
2511
- - agentic_workflow: Agent workflow mode with dynamic or predefined steps
2512
- - agentic_sampling: Autonomous sampling mode for agentic execution
2513
- - agentic_workflow_sampling: Autonomous sampling mode for workflow execution
2511
+ - ai_sampling: AI SDK sampling mode for autonomous execution
2512
+ - ai_acp: AI SDK ACP mode for coding agents
2514
2513
  - code_execution: Code execution mode for most efficient token usage
2515
2514
  --add Add MCP servers to ~/.mcpc/config.json and exit
2516
2515
  Then run 'mcpc' to start the server with saved config
@@ -2563,7 +2562,7 @@ EXAMPLES:
2563
2562
  mcpc --config-file ./my-config.json
2564
2563
 
2565
2564
  # Override execution mode for all agents
2566
- mcpc --config-file ./my-config.json --mode agentic_workflow
2565
+ mcpc --config-file ./my-config.json --mode ai_sampling
2567
2566
 
2568
2567
  # Using environment variable
2569
2568
  export MCPC_CONFIG='[{"name":"agent","description":"..."}]'
@@ -3074,11 +3073,11 @@ var Protocol = class {
3074
3073
  const controller = this._requestHandlerAbortControllers.get(notification.params.requestId);
3075
3074
  controller?.abort(notification.params.reason);
3076
3075
  }
3077
- _setupTimeout(messageId, timeout2, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) {
3076
+ _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) {
3078
3077
  this._timeoutInfo.set(messageId, {
3079
- timeoutId: setTimeout(onTimeout, timeout2),
3078
+ timeoutId: setTimeout(onTimeout, timeout),
3080
3079
  startTime: Date.now(),
3081
- timeout: timeout2,
3080
+ timeout,
3082
3081
  maxTotalTimeout,
3083
3082
  resetTimeoutOnProgress,
3084
3083
  onTimeout
@@ -3522,9 +3521,9 @@ var Protocol = class {
3522
3521
  options?.signal?.addEventListener("abort", () => {
3523
3522
  cancel(options?.signal?.reason);
3524
3523
  });
3525
- const timeout2 = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC;
3526
- const timeoutHandler = () => cancel(McpError.fromError(ErrorCode.RequestTimeout, "Request timed out", { timeout: timeout2 }));
3527
- this._setupTimeout(messageId, timeout2, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false);
3524
+ const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC;
3525
+ const timeoutHandler = () => cancel(McpError.fromError(ErrorCode.RequestTimeout, "Request timed out", { timeout }));
3526
+ this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false);
3528
3527
  const relatedTaskId = relatedTask?.taskId;
3529
3528
  if (relatedTaskId) {
3530
3529
  const responseResolver = (response) => {
@@ -4429,71 +4428,6 @@ var Server = class extends Protocol {
4429
4428
 
4430
4429
  // __mcpc__cli_latest/node_modules/@jsr/mcpc__utils/src/json.js
4431
4430
  var import_jsonrepair = require("jsonrepair");
4432
- function stripMarkdownAndText(text) {
4433
- text = text.trim();
4434
- text = text.replace(/^```(?:json)?\s*\n?/i, "");
4435
- text = text.replace(/\n?```\s*$/, "");
4436
- text = text.replace(/^(?:here is|here's|response|result|output|json):\s*/i, "");
4437
- const firstJsonIndex = text.search(/[\{\[]/);
4438
- if (firstJsonIndex >= 0) {
4439
- text = text.slice(firstJsonIndex);
4440
- let depth = 0;
4441
- let inString = false;
4442
- let escapeNext = false;
4443
- const startChar = text[0];
4444
- const endChar = startChar === "{" ? "}" : "]";
4445
- for (let i = 0; i < text.length; i++) {
4446
- const char = text[i];
4447
- if (escapeNext) {
4448
- escapeNext = false;
4449
- continue;
4450
- }
4451
- if (char === "\\") {
4452
- escapeNext = true;
4453
- continue;
4454
- }
4455
- if (char === '"' && !inString) {
4456
- inString = true;
4457
- continue;
4458
- }
4459
- if (char === '"' && inString) {
4460
- inString = false;
4461
- continue;
4462
- }
4463
- if (inString) continue;
4464
- if (char === startChar) {
4465
- depth++;
4466
- } else if (char === endChar) {
4467
- depth--;
4468
- if (depth === 0) {
4469
- return text.slice(0, i + 1);
4470
- }
4471
- }
4472
- }
4473
- }
4474
- return text.trim();
4475
- }
4476
- function parseJSON(text, throwError) {
4477
- try {
4478
- return JSON.parse(text);
4479
- } catch (_error) {
4480
- try {
4481
- const cleanedText = stripMarkdownAndText(text);
4482
- try {
4483
- return JSON.parse(cleanedText);
4484
- } catch {
4485
- const repairedText = (0, import_jsonrepair.jsonrepair)(cleanedText);
4486
- console.warn(`Failed to parse JSON, cleaned and repaired. Original: ${text.slice(0, 100)}...`);
4487
- return JSON.parse(repairedText);
4488
- }
4489
- } catch (_repairError) {
4490
- if (throwError) {
4491
- throw new Error(`Failed to parse JSON after cleanup and repair. Original error: ${_error instanceof Error ? _error.message : String(_error)}`);
4492
- }
4493
- return null;
4494
- }
4495
- }
4496
- }
4497
4431
 
4498
4432
  // __mcpc__cli_latest/node_modules/@jsr/mcpc__utils/src/ai.js
4499
4433
  var p = (template, options = {}) => {
@@ -5299,8 +5233,8 @@ var StdioClientTransport = class {
5299
5233
  this._process.stdin?.on("error", (error) => {
5300
5234
  this.onerror?.(error);
5301
5235
  });
5302
- this._process.stdout?.on("data", (chunk2) => {
5303
- this._readBuffer.append(chunk2);
5236
+ this._process.stdout?.on("data", (chunk) => {
5237
+ this._readBuffer.append(chunk);
5304
5238
  this.processReadBuffer();
5305
5239
  });
5306
5240
  this._process.stdout?.on("error", (error) => {
@@ -5409,7 +5343,7 @@ function createParser(callbacks) {
5409
5343
  const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks;
5410
5344
  let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = "";
5411
5345
  function feed(newChunk) {
5412
- const chunk2 = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk2}`);
5346
+ const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);
5413
5347
  for (const line of complete)
5414
5348
  parseLine(line);
5415
5349
  incompleteLine = incomplete, isFirstChunk = false;
@@ -5477,19 +5411,19 @@ function createParser(callbacks) {
5477
5411
  }
5478
5412
  return { feed, reset };
5479
5413
  }
5480
- function splitLines(chunk2) {
5414
+ function splitLines(chunk) {
5481
5415
  const lines = [];
5482
5416
  let incompleteLine = "", searchIndex = 0;
5483
- for (; searchIndex < chunk2.length; ) {
5484
- const crIndex = chunk2.indexOf("\r", searchIndex), lfIndex = chunk2.indexOf(`
5417
+ for (; searchIndex < chunk.length; ) {
5418
+ const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
5485
5419
  `, searchIndex);
5486
5420
  let lineEnd = -1;
5487
- 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) {
5488
- incompleteLine = chunk2.slice(searchIndex);
5421
+ 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) {
5422
+ incompleteLine = chunk.slice(searchIndex);
5489
5423
  break;
5490
5424
  } else {
5491
- const line = chunk2.slice(searchIndex, lineEnd);
5492
- lines.push(line), searchIndex = lineEnd + 1, chunk2[searchIndex - 1] === "\r" && chunk2[searchIndex] === `
5425
+ const line = chunk.slice(searchIndex, lineEnd);
5426
+ lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === `
5493
5427
  ` && searchIndex++;
5494
5428
  }
5495
5429
  }
@@ -6824,8 +6758,8 @@ var EventSourceParserStream = class extends TransformStream {
6824
6758
  onComment
6825
6759
  });
6826
6760
  },
6827
- transform(chunk2) {
6828
- parser.feed(chunk2);
6761
+ transform(chunk) {
6762
+ parser.feed(chunk);
6829
6763
  }
6830
6764
  });
6831
6765
  }
@@ -6933,14 +6867,14 @@ var StreamableHTTPClientTransport = class {
6933
6867
  * @param attempt Current reconnection attempt count for the specific stream
6934
6868
  * @returns Time to wait in milliseconds before next reconnection attempt
6935
6869
  */
6936
- _getNextReconnectionDelay(attempt2) {
6870
+ _getNextReconnectionDelay(attempt) {
6937
6871
  if (this._serverRetryMs !== void 0) {
6938
6872
  return this._serverRetryMs;
6939
6873
  }
6940
6874
  const initialDelay = this._reconnectionOptions.initialReconnectionDelay;
6941
6875
  const growFactor = this._reconnectionOptions.reconnectionDelayGrowFactor;
6942
6876
  const maxDelay = this._reconnectionOptions.maxReconnectionDelay;
6943
- return Math.min(initialDelay * Math.pow(growFactor, attempt2), maxDelay);
6877
+ return Math.min(initialDelay * Math.pow(growFactor, attempt), maxDelay);
6944
6878
  }
6945
6879
  /**
6946
6880
  * Schedule a reconnection attempt using server-provided retry interval or backoff
@@ -6954,13 +6888,13 @@ var StreamableHTTPClientTransport = class {
6954
6888
  this.onerror?.(new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`));
6955
6889
  return;
6956
6890
  }
6957
- const delay2 = this._getNextReconnectionDelay(attemptCount);
6891
+ const delay = this._getNextReconnectionDelay(attemptCount);
6958
6892
  this._reconnectionTimeout = setTimeout(() => {
6959
6893
  this._startOrAuthSse(options).catch((error) => {
6960
6894
  this.onerror?.(new Error(`Failed to reconnect SSE stream: ${error instanceof Error ? error.message : String(error)}`));
6961
6895
  this._scheduleReconnection(options, attemptCount + 1);
6962
6896
  });
6963
- }, delay2);
6897
+ }, delay);
6964
6898
  }
6965
6899
  _handleSseStream(stream, options, isReconnectable) {
6966
6900
  if (!stream) {
@@ -7294,8 +7228,8 @@ var createModelCompatibleJSONSchema = (schema) => {
7294
7228
  ]);
7295
7229
  let cleanSchema = schema;
7296
7230
  if (GEMINI_PREFERRED_FORMAT) {
7297
- const { oneOf: _oneOf, allOf: _allOf, anyOf: _anyOf, ...rest2 } = schema;
7298
- cleanSchema = rest2;
7231
+ const { oneOf: _oneOf, allOf: _allOf, anyOf: _anyOf, ...rest } = schema;
7232
+ cleanSchema = rest;
7299
7233
  }
7300
7234
  const cleanRecursively = (obj) => {
7301
7235
  if (Array.isArray(obj)) {
@@ -7314,6 +7248,34 @@ var createModelCompatibleJSONSchema = (schema) => {
7314
7248
  };
7315
7249
  return cleanRecursively(cleanSchema);
7316
7250
  };
7251
+ var INTERNAL_SCHEMA_KEYS = /* @__PURE__ */ new Set([
7252
+ "$schema",
7253
+ "_originalName",
7254
+ "_type",
7255
+ "annotations"
7256
+ ]);
7257
+ var cleanToolSchema = (schema) => {
7258
+ const cleanRecursively = (obj) => {
7259
+ if (Array.isArray(obj)) {
7260
+ return obj.map(cleanRecursively);
7261
+ }
7262
+ if (obj && typeof obj === "object") {
7263
+ const record2 = obj;
7264
+ if ("jsonSchema" in record2 && typeof record2.jsonSchema === "object" && record2.jsonSchema !== null) {
7265
+ return cleanRecursively(record2.jsonSchema);
7266
+ }
7267
+ const result = {};
7268
+ for (const [key, value] of Object.entries(record2)) {
7269
+ if (!INTERNAL_SCHEMA_KEYS.has(key)) {
7270
+ result[key] = cleanRecursively(value);
7271
+ }
7272
+ }
7273
+ return result;
7274
+ }
7275
+ return obj;
7276
+ };
7277
+ return cleanRecursively(schema);
7278
+ };
7317
7279
 
7318
7280
  // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/mcp.js
7319
7281
  var import_node_process5 = require("node:process");
@@ -7662,14 +7624,14 @@ function createLogger(name, server) {
7662
7624
 
7663
7625
  // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/logging-plugin.js
7664
7626
  var createLoggingPlugin = (options = {}) => {
7665
- const { enabled = true, verbose = false, compact: compact2 = true } = options;
7627
+ const { enabled = true, verbose = false, compact = true } = options;
7666
7628
  return {
7667
7629
  name: "built-in-logging",
7668
7630
  version: "1.0.0",
7669
7631
  composeEnd: async (context2) => {
7670
7632
  if (!enabled) return;
7671
7633
  const logger2 = createLogger("mcpc.plugin.logging", context2.server);
7672
- if (compact2) {
7634
+ if (compact) {
7673
7635
  const pluginCount = context2.pluginNames.length;
7674
7636
  const { stats } = context2;
7675
7637
  await logger2.info(`[${context2.toolName}] ${pluginCount} plugins \u2022 ${stats.publicTools} public \u2022 ${stats.hiddenTools} hidden`);
@@ -7709,296 +7671,85 @@ var logging_plugin_default = createLoggingPlugin({
7709
7671
  var SystemPrompts = {
7710
7672
  /**
7711
7673
  * Base system prompt for autonomous MCP execution
7674
+ *
7675
+ * Uses simplified Unix-style interface:
7676
+ * - `tool` + `args` for clean, consistent structure
7677
+ * - `man` command for fetching tool schemas (like Unix manual)
7678
+ * - No `hasDefinitions` - trusts model's context memory
7712
7679
  */
7713
- 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.
7680
+ AUTONOMOUS_EXECUTION: `Agentic tool \`{toolName}\` that executes complex tasks by iteratively selecting and calling tools.
7714
7681
 
7715
- You must follow the <manual/>, obey the <execution_rules/>, and use the <call_format/>.
7682
+ You must follow the <manual/>, obey the <rules/>, and use the <format/>.
7716
7683
 
7717
7684
  <manual>
7718
7685
  {description}
7719
7686
  </manual>
7720
7687
 
7721
7688
  <parameters>
7722
- \`useTool\` - Which tool to execute this iteration
7723
- \`hasDefinitions\` - Tool names whose schemas you already have
7724
- \`definitionsOf\` - Tool names whose schemas you need
7689
+ \`tool\` - Which tool to execute: "man" to get schemas, or a tool name to execute
7690
+ \`args\` - For "man": { tools: ["tool1", "tool2"] }. For other tools: tool parameters that strictly adhere to the tool's JSON schema.
7725
7691
  </parameters>
7726
7692
 
7727
- <execution_rules>
7728
- 1. **First call**: No tool definitions available\u2014you must request them via \`definitionsOf\`
7729
- 2. **When executing tools**: Must provide \`hasDefinitions\` with ALL tools you have schemas for (avoid duplicate requests and reduce tokens)
7730
- 3. **When requesting definitions**: Use \`definitionsOf\` to request tool schemas you need
7731
- 4. **Both together**: Execute tool AND request new definitions in one call for efficiency
7732
- 5. **Never request definitions you already have**
7733
- 6. **Select** one tool to execute per call using \`useTool\`
7734
- 7. **Provide** parameters matching the selected tool name
7735
- 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**
7736
- </execution_rules>
7737
-
7738
- <call_format>
7739
- Initial definition request:
7740
- \`\`\`json
7741
- {
7742
- "hasDefinitions": [],
7743
- "definitionsOf": ["tool1", "tool2"]
7744
- }
7745
- \`\`\`
7746
-
7747
- Execute tool + get new definitions:
7748
- \`\`\`json
7749
- {
7750
- "useTool": "tool1",
7751
- "tool1": { /* parameters */ },
7752
- "hasDefinitions": ["tool1", "tool2"],
7753
- "definitionsOf": ["tool3"]
7754
- }
7755
- \`\`\`
7756
- </call_format>`,
7757
- /**
7758
- * Workflow execution system prompt
7759
- */
7760
- WORKFLOW_EXECUTION: `Workflow tool \`{toolName}\` that executes multi-step workflows. Use this when your task requires sequential steps.
7761
-
7762
- <manual>
7763
- {description}
7764
- </manual>
7765
-
7766
- <rules>
7767
- 1. First call: {planningInstructions}
7768
- 2. Subsequent calls: Provide only current step parameters
7769
- 3. Use \`decision: "proceed"\` to advance, \`"retry"\` to retry, \`"complete"\` when done
7770
- 4. Include \`steps\` ONLY with \`init: true\`, never during execution
7771
- </rules>`,
7772
- /**
7773
- * Tool-based execution system prompt for autonomous sampling mode with native tools
7774
- *
7775
- * Note: Used when client supports sampling.tools capability
7776
- */
7777
- SAMPLING_EXECUTION_TOOLS: `Agent \`{toolName}\` that completes tasks by calling tools.
7778
-
7779
- <manual>
7780
- {description}
7781
- </manual>
7782
-
7783
- <rules>
7784
- 1. Execute one action per iteration
7785
- 2. Adapt based on results from previous actions
7786
- 3. Continue until task is complete
7787
- </rules>
7788
-
7789
- <tools>
7790
- {toolList}
7791
- </tools>`,
7792
- /**
7793
- * JSON-only execution system prompt for autonomous sampling mode
7794
- *
7795
- * Note: Sampling mode runs an internal LLM loop that autonomously calls tools until complete.
7796
- */
7797
- SAMPLING_EXECUTION: `Agent \`{toolName}\` that completes tasks by calling tools in an autonomous loop.
7798
-
7799
- <manual>
7800
- {description}
7801
- </manual>
7802
-
7803
7693
  <rules>
7804
- 1. **YOUR ENTIRE RESPONSE MUST BE A SINGLE JSON OBJECT** - no text before or after
7805
- 2. Execute one tool per iteration
7806
- 3. Specify which tool to use with \`useTool\`
7807
- 4. Adapt based on results from previous actions
7808
- 5. Continue until task is complete
7694
+ 1. **First call**: Use \`man\` to get tool schemas you need
7695
+ 2. **Execute tools**: Use tool name in \`tool\` and parameters in \`args\`
7696
+ 3. **Parallel calls**: If your client supports it, call \`man\` and execute tools simultaneously
7697
+ 4. Note: You are an agent exposed as an MCP tool
7809
7698
  </rules>
7810
7699
 
7811
7700
  <format>
7812
- CORRECT:
7813
- \`\`\`json
7814
- {"useTool": "tool_name", "decision": "proceed", "tool_name": {...}}
7815
- \`\`\`
7816
-
7817
- WRONG - No explanations:
7818
- \`\`\`
7819
- I will list the directory
7820
- {"useTool": "list_directory", ...}
7821
- \`\`\`
7822
-
7823
- During execution:
7701
+ Get tool schemas:
7824
7702
  \`\`\`json
7825
7703
  {
7826
- "useTool": "tool_name",
7827
- "decision": "proceed",
7828
- "tool_name": { /* tool parameters */ }
7704
+ "tool": "man",
7705
+ "args": { "tools": ["tool1", "tool2"] }
7829
7706
  }
7830
7707
  \`\`\`
7831
7708
 
7832
- When complete:
7709
+ Execute a tool:
7833
7710
  \`\`\`json
7834
- { "decision": "complete" }
7711
+ {
7712
+ "tool": "tool_name",
7713
+ "args": { /* tool parameters */ }
7714
+ }
7835
7715
  \`\`\`
7836
-
7837
- Decisions:
7838
- - \`proceed\` = action succeeded, continue
7839
- - \`retry\` = action failed, try again
7840
- - \`complete\` = task finished
7841
- </format>
7842
-
7843
- <tools>
7844
- {toolList}
7845
- </tools>`,
7716
+ </format>`,
7846
7717
  /**
7847
7718
  * Tool description for sampling tools (shown in MCP tools list)
7848
- * Explains how to use userRequest and context parameters
7719
+ * Explains how to use prompt and context parameters
7849
7720
  */
7850
- SAMPLING_TOOL_DESCRIPTION: `Subagent tool \`{toolName}\` that executes complex tasks.
7721
+ SAMPLING_TOOL_DESCRIPTION: `Subagent tool \`{toolName}\` that executes complex tasks.
7851
7722
 
7852
- <manual>
7853
- {description}
7854
- </manual>
7855
-
7856
- <rules>
7857
- Call this tool with:
7858
- - **userRequest**: The task you want completed (e.g., "organize my desktop files", "create a project structure")
7859
- - **context**: Relevant information needed for the task (e.g., working directory, file paths, preferences)
7860
- </rules>`,
7861
- /**
7862
- * Tool-based workflow execution system prompt for sampling mode with native tools
7863
- *
7864
- * Note: Used when client supports sampling.tools capability
7865
- */
7866
- SAMPLING_WORKFLOW_EXECUTION_TOOLS: `Workflow agent \`{toolName}\` that executes multi-step workflows.
7723
+ You must follow the <manual/>, obey the <rules/>, and use the <format/>.
7867
7724
 
7868
7725
  <manual>
7869
7726
  {description}
7870
7727
  </manual>
7871
7728
 
7729
+ <format>
7730
+ \`prompt\` - The task to be completed (e.g., "organize my desktop files")
7731
+ \`context\` - Execution context object (e.g., { cwd: "/path/to/dir" })
7732
+ </format>
7733
+
7872
7734
  <rules>
7873
- 1. First iteration: Plan workflow and initialize
7874
- 2. Subsequent iterations: Execute current step
7875
- 3. Adapt based on step results
7876
- 4. Continue until all steps complete
7735
+ 1. Always provide both \`prompt\` and \`context\` parameters
7736
+ 2. \`prompt\` must be a clear, actionable description
7737
+ 3. \`context\` must include relevant environment info (e.g., working directory)
7877
7738
  </rules>`,
7878
7739
  /**
7879
- * Sampling workflow execution system prompt combining sampling with workflow capabilities
7880
- *
7881
- * Note: Sampling mode runs an internal LLM loop that autonomously executes workflows.
7740
+ * System prompt for AI sampling loop (ai_sampling/ai_acp modes)
7741
+ * Used inside the execution loop when AI calls native tools.
7742
+ * Note: Tool schemas are passed via AI SDK native tool calling, not in prompt.
7882
7743
  */
7883
- SAMPLING_WORKFLOW_EXECUTION: `Workflow agent \`{toolName}\` that executes multi-step workflows autonomously.
7744
+ AI_LOOP_SYSTEM: `Agent \`{toolName}\` that completes tasks by calling tools.
7884
7745
 
7885
7746
  <manual>
7886
7747
  {description}
7887
7748
  </manual>
7888
7749
 
7889
7750
  <rules>
7890
- 1. Return valid JSON only
7891
- 2. First iteration: Plan workflow and initialize with \`init: true\`
7892
- 3. Subsequent iterations: Execute current step
7893
- 4. Adapt based on step results
7894
- 5. Continue until all steps complete
7895
- </rules>
7896
-
7897
- <format>
7898
- Initialize workflow (first iteration):
7899
- \`\`\`json
7900
- {
7901
- "action": "{toolName}",
7902
- "init": true,
7903
- "steps": [/* workflow steps */]
7904
- }
7905
- \`\`\`
7906
-
7907
- Execute step (subsequent iterations):
7908
- \`\`\`json
7909
- {
7910
- "action": "{toolName}",
7911
- "decision": "proceed|retry",
7912
- /* step parameters */
7913
- }
7914
- \`\`\`
7915
-
7916
- Complete workflow (omit action):
7917
- \`\`\`json
7918
- { "decision": "complete" }
7919
- \`\`\`
7920
-
7921
- Decisions:
7922
- - \`proceed\` = step succeeded, next step
7923
- - \`retry\` = step failed, retry current
7924
- - \`complete\` = workflow finished
7925
-
7926
- Rules:
7927
- - Include \`steps\` ONLY with \`init: true\`
7928
- - Omit \`steps\` during step execution
7929
- - Use \`decision: "retry"\` for failed steps
7930
- </format>`
7931
- };
7932
- var WorkflowPrompts = {
7933
- /**
7934
- * Workflow initialization instructions
7935
- */
7936
- WORKFLOW_INIT: `Workflow initialized with {stepCount} steps. Execute step 1: \`{currentStepDescription}\`
7937
-
7938
- Schema: {schemaDefinition}
7939
-
7940
- Call \`{toolName}\` with:
7941
- - Parameters matching schema above
7942
- - \`decision: "proceed"\` to advance, \`"retry"\` to retry, \`"complete"\` when done
7943
- - Omit \`steps\` (only used with \`init: true\`)
7944
-
7945
- {workflowSteps}`,
7946
- /**
7947
- * Tool description enhancement for workflow mode
7948
- */
7949
- WORKFLOW_TOOL_DESCRIPTION: `{description}
7950
- {initTitle}
7951
- {ensureStepActions}
7952
- {schemaDefinition}`,
7953
- /**
7954
- * Planning instructions for predefined workflows
7955
- */
7956
- PREDEFINED_WORKFLOW_PLANNING: `- Set \`init: true\` (steps are predefined)`,
7957
- /**
7958
- * Planning instructions for dynamic workflows
7959
- */
7960
- DYNAMIC_WORKFLOW_PLANNING: `- Set \`init: true\` and define complete \`steps\` array`,
7961
- /**
7962
- * Next step decision prompt
7963
- */
7964
- NEXT_STEP_DECISION: `Previous step completed.
7965
-
7966
- Choose action:
7967
- - RETRY: Call \`{toolName}\` with \`decision: "retry"\`
7968
- - PROCEED: Call \`{toolName}\` with \`decision: "proceed"\` and parameters below
7969
-
7970
- Next: \`{nextStepDescription}\`
7971
- {nextStepSchema}
7972
-
7973
- (Omit \`steps\` parameter)`,
7974
- /**
7975
- * Final step completion prompt
7976
- */
7977
- FINAL_STEP_COMPLETION: `Final step executed {statusIcon} - {statusText}
7978
-
7979
- Choose:
7980
- - RETRY: \`decision: "retry"\`
7981
- - COMPLETE: \`decision: "complete"\`
7982
- - NEW: \`init: true\`{newWorkflowInstructions}`,
7983
- /**
7984
- * Workflow completion success message
7985
- */
7986
- WORKFLOW_COMPLETED: `Workflow completed ({totalSteps} steps)
7987
-
7988
- Start new workflow: \`{toolName}\` with \`init: true\`{newWorkflowInstructions}`,
7989
- /**
7990
- * Error messages
7991
- */
7992
- ERRORS: {
7993
- NOT_INITIALIZED: {
7994
- WITH_PREDEFINED: "Error: Workflow not initialized. Please provide 'init' parameter to start a new workflow.",
7995
- WITHOUT_PREDEFINED: "Error: Workflow not initialized. Please provide 'init' and 'steps' parameter to start a new workflow."
7996
- },
7997
- ALREADY_AT_FINAL: "Error: Cannot proceed, already at the final step.",
7998
- 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.",
7999
- NO_STEPS_PROVIDED: "Error: No steps provided",
8000
- NO_CURRENT_STEP: "Error: No current step to execute"
8001
- }
7751
+ {rules}
7752
+ </rules>{context}`
8002
7753
  };
8003
7754
  var ResponseTemplates = {
8004
7755
  /**
@@ -8021,9 +7772,6 @@ Next: Execute \`{nextAction}\` by calling \`{toolName}\` again.`,
8021
7772
  ERROR_RESPONSE: `Validation failed: {errorMessage}
8022
7773
 
8023
7774
  Adjust parameters and retry.`,
8024
- WORKFLOW_ERROR_RESPONSE: `Step failed: {errorMessage}
8025
-
8026
- Fix parameters and call with \`decision: "retry"\``,
8027
7775
  /**
8028
7776
  * Completion message
8029
7777
  */
@@ -8042,78 +7790,116 @@ Fix parameters and call with \`decision: "retry"\``,
8042
7790
  };
8043
7791
  var CompiledPrompts = {
8044
7792
  autonomousExecution: p(SystemPrompts.AUTONOMOUS_EXECUTION),
8045
- workflowExecution: p(SystemPrompts.WORKFLOW_EXECUTION),
8046
- samplingExecution: p(SystemPrompts.SAMPLING_EXECUTION),
8047
- samplingExecutionTools: p(SystemPrompts.SAMPLING_EXECUTION_TOOLS),
8048
7793
  samplingToolDescription: p(SystemPrompts.SAMPLING_TOOL_DESCRIPTION),
8049
- samplingWorkflowExecution: p(SystemPrompts.SAMPLING_WORKFLOW_EXECUTION),
8050
- samplingWorkflowExecutionTools: p(SystemPrompts.SAMPLING_WORKFLOW_EXECUTION_TOOLS),
8051
- workflowInit: p(WorkflowPrompts.WORKFLOW_INIT),
8052
- workflowToolDescription: p(WorkflowPrompts.WORKFLOW_TOOL_DESCRIPTION),
8053
- nextStepDecision: p(WorkflowPrompts.NEXT_STEP_DECISION),
8054
- finalStepCompletion: p(WorkflowPrompts.FINAL_STEP_COMPLETION),
8055
- workflowCompleted: p(WorkflowPrompts.WORKFLOW_COMPLETED),
7794
+ aiLoopSystem: p(SystemPrompts.AI_LOOP_SYSTEM),
8056
7795
  actionSuccess: p(ResponseTemplates.ACTION_SUCCESS),
8057
7796
  planningPrompt: p(ResponseTemplates.PLANNING_PROMPT),
8058
7797
  errorResponse: p(ResponseTemplates.ERROR_RESPONSE),
8059
- workflowErrorResponse: p(ResponseTemplates.WORKFLOW_ERROR_RESPONSE),
8060
7798
  securityPassed: p(ResponseTemplates.SECURITY_VALIDATION.PASSED),
8061
7799
  securityFailed: p(ResponseTemplates.SECURITY_VALIDATION.FAILED),
8062
7800
  auditLog: p(ResponseTemplates.AUDIT_LOG),
8063
7801
  completionMessage: () => ResponseTemplates.COMPLETION_MESSAGE
8064
7802
  };
8065
- var PromptUtils = {
8066
- /**
8067
- * Generate tool list for descriptions
8068
- */
8069
- generateToolList: (tools) => {
8070
- return tools.filter((tool2) => !tool2.hide).map((tool2) => `<tool name="${tool2.name}"${tool2.description ? ` description="${tool2.description}"` : ""}/>`).join("\n");
8071
- },
8072
- /**
8073
- * Generate hidden tool list for descriptions
8074
- */
8075
- generateHiddenToolList: (tools) => {
8076
- return tools.filter((tool2) => tool2.hide).map((tool2) => `<tool name="${tool2.name}" hide/>`).join("\n");
8077
- },
8078
- /**
8079
- * Format workflow steps for display
8080
- */
8081
- formatWorkflowSteps: (steps) => {
8082
- if (!steps.length) return "";
8083
- return `## Workflow Steps
8084
- ${JSON.stringify(steps, null, 2)}`;
8085
- },
8086
- /**
8087
- * Format workflow progress display with status icons
8088
- */
8089
- formatWorkflowProgress: (progressData) => {
8090
- const statusIcons = {
8091
- pending: "[PENDING]",
8092
- running: "[RUNNING]",
8093
- completed: "[DONE]",
8094
- failed: "[FAILED]"
8095
- };
8096
- return progressData.steps.map((step, index) => {
8097
- const status = progressData.statuses[index] || "pending";
8098
- const icon = statusIcons[status] || "[PENDING]";
8099
- const current = index === progressData.currentStepIndex ? " **[CURRENT]**" : "";
8100
- const actions = step.actions.length > 0 ? ` | Action: ${step.actions.join(", ")}` : "";
8101
- return `${icon} **Step ${index + 1}:** ${step.description}${actions}${current}`;
8102
- }).join("\n");
8103
- },
8104
- /**
8105
- * Generate user info for audit logs
8106
- */
8107
- formatUserInfo: (user) => {
8108
- return user ? ` by ${user}` : "";
8109
- },
8110
- /**
8111
- * Format timestamp for logs
8112
- */
8113
- formatTimestamp: () => {
8114
- return (/* @__PURE__ */ new Date()).toISOString();
8115
- }
8116
- };
7803
+
7804
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/factories/args-def-factory.js
7805
+ function createArgsDefFactory(_name, _allToolNames, _depGroups, _predefinedSteps, _ensureStepActions) {
7806
+ return {
7807
+ forSampling: function() {
7808
+ return {
7809
+ type: "object",
7810
+ description: "Provide prompt for autonomous tool execution",
7811
+ properties: {
7812
+ prompt: {
7813
+ type: "string",
7814
+ description: "The task to be completed autonomously by the agentic system using available tools"
7815
+ },
7816
+ context: {
7817
+ type: "object",
7818
+ description: "Execution context, e.g., { cwd: '/path/to/dir' }. Any relevant fields allowed.",
7819
+ additionalProperties: true
7820
+ }
7821
+ },
7822
+ required: [
7823
+ "prompt",
7824
+ "context"
7825
+ ],
7826
+ errorMessage: {
7827
+ required: {
7828
+ prompt: "Missing required field 'prompt'. Please provide a clear task description.",
7829
+ context: "Missing required field 'context'. Please provide relevant context (e.g., { cwd: '...' })."
7830
+ }
7831
+ }
7832
+ };
7833
+ },
7834
+ /**
7835
+ * Agentic schema - simplified Unix-style interface
7836
+ *
7837
+ * Only two fields:
7838
+ * - `tool`: which tool to execute (enum includes "man" + all tool names)
7839
+ * - `args`: object with parameters. For "man": { tools: ["a", "b"] }. For others: tool parameters.
7840
+ */
7841
+ forAgentic: function(allToolNames) {
7842
+ const toolEnum = [
7843
+ "man",
7844
+ ...allToolNames
7845
+ ];
7846
+ return {
7847
+ type: "object",
7848
+ properties: {
7849
+ tool: {
7850
+ type: "string",
7851
+ enum: toolEnum,
7852
+ description: 'Which tool to execute. Use "man" to get tool schemas, or a tool name to execute.',
7853
+ errorMessage: {
7854
+ enum: `Invalid tool. Available: ${toolEnum.join(", ")}`
7855
+ }
7856
+ },
7857
+ args: {
7858
+ type: "object",
7859
+ description: `For "man": { tools: ["tool1", "tool2"] }. For other tools: tool parameters that strictly adhere to the tool's JSON schema.`
7860
+ }
7861
+ },
7862
+ required: [
7863
+ "tool"
7864
+ ],
7865
+ additionalProperties: false
7866
+ };
7867
+ },
7868
+ /**
7869
+ * Schema for "man" command args validation
7870
+ * Expected format: { tools: ["tool1", "tool2"] }
7871
+ */
7872
+ forMan: function(allToolNames) {
7873
+ return {
7874
+ type: "object",
7875
+ properties: {
7876
+ tools: {
7877
+ type: "array",
7878
+ items: {
7879
+ type: "string",
7880
+ enum: allToolNames,
7881
+ errorMessage: {
7882
+ enum: `Invalid tool name. Available: ${allToolNames.join(", ")}`
7883
+ }
7884
+ },
7885
+ minItems: 1,
7886
+ errorMessage: {
7887
+ minItems: "At least one tool name is required"
7888
+ }
7889
+ }
7890
+ },
7891
+ required: [
7892
+ "tools"
7893
+ ],
7894
+ errorMessage: {
7895
+ required: {
7896
+ tools: 'Missing "tools" field. Expected: { tools: ["tool1", "tool2"] }'
7897
+ }
7898
+ }
7899
+ };
7900
+ }
7901
+ };
7902
+ }
8117
7903
 
8118
7904
  // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/schema-validator.js
8119
7905
  var import_ajv2 = require("ajv");
@@ -8122,13 +7908,14 @@ var import_ajv_errors = __toESM(require("ajv-errors"), 1);
8122
7908
  var import_ajv_human_errors = require("@segment/ajv-human-errors");
8123
7909
  var ajv = new import_ajv2.Ajv({
8124
7910
  allErrors: true,
8125
- verbose: true
7911
+ verbose: true,
7912
+ strict: false
8126
7913
  });
8127
7914
  import_ajv_formats2.default.default(ajv);
8128
7915
  import_ajv_errors.default.default(ajv);
8129
- function validateSchema(args, schema) {
7916
+ function validateSchema(data, schema) {
8130
7917
  const validate = ajv.compile(schema);
8131
- if (!validate(args)) {
7918
+ if (!validate(data)) {
8132
7919
  const errors = validate.errors;
8133
7920
  const customErrors = errors.filter((err) => err.keyword === "errorMessage");
8134
7921
  if (customErrors.length > 0) {
@@ -8225,17 +8012,17 @@ var AgenticExecutor = class {
8225
8012
  allToolNames;
8226
8013
  toolNameToDetailList;
8227
8014
  server;
8228
- USE_TOOL_KEY;
8229
8015
  logger;
8230
8016
  tracingEnabled;
8231
- constructor(name, allToolNames, toolNameToDetailList, server, USE_TOOL_KEY = "useTool") {
8017
+ toolSchemaMap;
8018
+ constructor(name, allToolNames, toolNameToDetailList, server) {
8232
8019
  this.name = name;
8233
8020
  this.allToolNames = allToolNames;
8234
8021
  this.toolNameToDetailList = toolNameToDetailList;
8235
8022
  this.server = server;
8236
- this.USE_TOOL_KEY = USE_TOOL_KEY;
8237
8023
  this.tracingEnabled = false;
8238
8024
  this.logger = createLogger(`mcpc.agentic.${name}`, server);
8025
+ this.toolSchemaMap = new Map(toolNameToDetailList);
8239
8026
  try {
8240
8027
  this.tracingEnabled = import_node_process7.default.env.MCPC_TRACING_ENABLED === "true";
8241
8028
  if (this.tracingEnabled) {
@@ -8253,7 +8040,7 @@ var AgenticExecutor = class {
8253
8040
  async execute(args, schema, parentSpan) {
8254
8041
  const executeSpan = this.tracingEnabled ? startSpan("mcpc.agentic_execute", {
8255
8042
  agent: this.name,
8256
- selectTool: String(args[this.USE_TOOL_KEY] ?? "unknown"),
8043
+ tool: String(args.tool ?? "unknown"),
8257
8044
  args: JSON.stringify(args)
8258
8045
  }, parentSpan ?? void 0) : null;
8259
8046
  try {
@@ -8268,7 +8055,7 @@ var AgenticExecutor = class {
8268
8055
  }
8269
8056
  this.logger.warning({
8270
8057
  message: "Validation failed",
8271
- selectTool: args[this.USE_TOOL_KEY],
8058
+ tool: args.tool,
8272
8059
  error: validationResult.error
8273
8060
  });
8274
8061
  return {
@@ -8283,1852 +8070,237 @@ var AgenticExecutor = class {
8283
8070
  isError: true
8284
8071
  };
8285
8072
  }
8286
- const useTool = args[this.USE_TOOL_KEY];
8287
- const definitionsOf = args.definitionsOf || [];
8288
- const hasDefinitions = args.hasDefinitions || [];
8289
- if (!useTool) {
8290
- if (executeSpan) {
8291
- executeSpan.setAttributes({
8292
- toolType: "none",
8293
- completion: true
8294
- });
8295
- endSpan(executeSpan);
8296
- }
8297
- const result = {
8298
- content: []
8299
- };
8300
- this.appendToolSchemas(result, definitionsOf, hasDefinitions);
8301
- if (result.content.length === 0 && definitionsOf.length > 0) {
8302
- result.content.push({
8303
- type: "text",
8304
- text: `All requested tool schemas are already in hasDefinitions. You can now call a tool using "${this.USE_TOOL_KEY}".`
8305
- });
8073
+ const tool2 = args.tool;
8074
+ if (tool2 === "man") {
8075
+ const createArgsDef = createArgsDefFactory(this.name, this.allToolNames, {});
8076
+ const manSchema = createArgsDef.forMan(this.allToolNames);
8077
+ const manValidation = validateSchema(args.args ?? {}, manSchema);
8078
+ if (!manValidation.valid) {
8079
+ return {
8080
+ content: [
8081
+ {
8082
+ type: "text",
8083
+ text: `Invalid args for "man": ${manValidation.error}`
8084
+ }
8085
+ ],
8086
+ isError: true
8087
+ };
8306
8088
  }
8307
- return result;
8089
+ const argsObj = args.args;
8090
+ return this.handleManCommand(argsObj.tools, executeSpan);
8308
8091
  }
8092
+ const toolArgs = args.args || {};
8093
+ return await this.executeTool(tool2, toolArgs, executeSpan);
8094
+ } catch (error) {
8309
8095
  if (executeSpan) {
8310
- try {
8311
- const safeTool = String(useTool).replace(/\s+/g, "_");
8312
- if (typeof executeSpan.updateName === "function") {
8313
- executeSpan.updateName(`mcpc.agentic_execute.${safeTool}`);
8314
- }
8315
- } catch {
8316
- }
8096
+ endSpan(executeSpan, error);
8317
8097
  }
8318
- const currentTool = this.toolNameToDetailList.find(([name, _detail]) => name === useTool)?.[1];
8319
- if (currentTool) {
8320
- if (executeSpan) {
8321
- executeSpan.setAttributes({
8322
- toolType: "external",
8323
- selectedTool: useTool
8324
- });
8325
- }
8326
- this.logger.debug({
8327
- message: "Executing external tool",
8328
- selectTool: useTool
8329
- });
8330
- const currentResult = await currentTool.execute({
8331
- ...args[useTool]
8332
- });
8333
- this.appendToolSchemas(currentResult, definitionsOf, hasDefinitions);
8334
- if (executeSpan) {
8335
- executeSpan.setAttributes({
8336
- success: true,
8337
- isError: !!currentResult.isError,
8338
- resultContentLength: currentResult.content?.length || 0,
8339
- toolResult: JSON.stringify(currentResult)
8340
- });
8341
- endSpan(executeSpan);
8342
- }
8343
- return currentResult;
8344
- }
8345
- if (this.allToolNames.includes(useTool)) {
8346
- if (executeSpan) {
8347
- executeSpan.setAttributes({
8348
- toolType: "internal",
8349
- selectedTool: useTool
8350
- });
8351
- }
8352
- this.logger.debug({
8353
- message: "Executing internal tool",
8354
- selectTool: useTool
8355
- });
8356
- try {
8357
- const result = await this.server.callTool(useTool, args[useTool]);
8358
- const callToolResult = result ?? {
8359
- content: []
8360
- };
8361
- this.appendToolSchemas(callToolResult, definitionsOf, hasDefinitions);
8362
- if (executeSpan) {
8363
- executeSpan.setAttributes({
8364
- success: true,
8365
- isError: !!callToolResult.isError,
8366
- resultContentLength: callToolResult.content?.length || 0,
8367
- toolResult: JSON.stringify(callToolResult)
8368
- });
8369
- endSpan(executeSpan);
8370
- }
8371
- return callToolResult;
8372
- } catch (error) {
8373
- if (executeSpan) {
8374
- endSpan(executeSpan, error);
8375
- }
8376
- this.logger.error({
8377
- message: "Error executing internal tool",
8378
- useTool,
8379
- error: String(error)
8380
- });
8381
- return {
8382
- content: [
8383
- {
8384
- type: "text",
8385
- text: `Error executing internal tool ${useTool}: ${error instanceof Error ? error.message : String(error)}`
8386
- }
8387
- ],
8388
- isError: true
8389
- };
8390
- }
8391
- }
8392
- if (executeSpan) {
8393
- executeSpan.setAttributes({
8394
- toolType: "not_found",
8395
- useTool
8396
- });
8397
- endSpan(executeSpan);
8398
- }
8399
- return {
8400
- content: [
8401
- {
8402
- type: "text",
8403
- text: `Tool "${useTool}" not found. Available tools: ${this.allToolNames.join(", ")}.`
8404
- }
8405
- ],
8406
- isError: true
8407
- };
8408
- } catch (error) {
8409
- if (executeSpan) {
8410
- endSpan(executeSpan, error);
8411
- }
8412
- this.logger.error({
8413
- message: "Unexpected error in execute",
8414
- error: String(error)
8415
- });
8416
- return {
8417
- content: [
8418
- {
8419
- type: "text",
8420
- text: `Unexpected error: ${error instanceof Error ? error.message : String(error)}`
8421
- }
8422
- ],
8423
- isError: true
8424
- };
8425
- }
8426
- }
8427
- // Append tool schemas to result if requested
8428
- appendToolSchemas(result, definitionsOf, hasDefinitions) {
8429
- const schemasToProvide = definitionsOf.filter((toolName) => !hasDefinitions.includes(toolName));
8430
- if (schemasToProvide.length === 0) {
8431
- return;
8432
- }
8433
- const definitionTexts = [];
8434
- for (const toolName of schemasToProvide) {
8435
- const toolDetail = this.toolNameToDetailList.find(([name]) => name === toolName);
8436
- if (toolDetail) {
8437
- const [name, schema] = toolDetail;
8438
- const schemaJson = JSON.stringify(schema, null, 2);
8439
- definitionTexts.push(`<tool_definition name="${name}">
8440
- ${schemaJson}
8441
- </tool_definition>`);
8442
- }
8443
- }
8444
- if (definitionTexts.length > 0) {
8445
- result.content.push({
8446
- type: "text",
8447
- text: `${definitionTexts.join("\n\n")}`
8448
- });
8449
- }
8450
- }
8451
- // Validate arguments using JSON schema
8452
- validate(args, schema) {
8453
- return validateSchema(args, schema);
8454
- }
8455
- };
8456
-
8457
- // __mcpc__cli_latest/node_modules/@jsr/es-toolkit__es-toolkit/src/function/partial.js
8458
- function partial(func, ...partialArgs) {
8459
- return partialImpl(func, placeholderSymbol, ...partialArgs);
8460
- }
8461
- function partialImpl(func, placeholder, ...partialArgs) {
8462
- const partialed = function(...providedArgs) {
8463
- let providedArgsIndex = 0;
8464
- const substitutedArgs = partialArgs.slice().map((arg) => arg === placeholder ? providedArgs[providedArgsIndex++] : arg);
8465
- const remainingArgs = providedArgs.slice(providedArgsIndex);
8466
- return func.apply(this, substitutedArgs.concat(remainingArgs));
8467
- };
8468
- if (func.prototype) {
8469
- partialed.prototype = Object.create(func.prototype);
8470
- }
8471
- return partialed;
8472
- }
8473
- var placeholderSymbol = Symbol("partial.placeholder");
8474
- partial.placeholder = placeholderSymbol;
8475
-
8476
- // __mcpc__cli_latest/node_modules/@jsr/es-toolkit__es-toolkit/src/function/partialRight.js
8477
- function partialRight(func, ...partialArgs) {
8478
- return partialRightImpl(func, placeholderSymbol2, ...partialArgs);
8479
- }
8480
- function partialRightImpl(func, placeholder, ...partialArgs) {
8481
- const partialedRight = function(...providedArgs) {
8482
- const placeholderLength = partialArgs.filter((arg) => arg === placeholder).length;
8483
- const rangeLength = Math.max(providedArgs.length - placeholderLength, 0);
8484
- const remainingArgs = providedArgs.slice(0, rangeLength);
8485
- let providedArgsIndex = rangeLength;
8486
- const substitutedArgs = partialArgs.slice().map((arg) => arg === placeholder ? providedArgs[providedArgsIndex++] : arg);
8487
- return func.apply(this, remainingArgs.concat(substitutedArgs));
8488
- };
8489
- if (func.prototype) {
8490
- partialedRight.prototype = Object.create(func.prototype);
8491
- }
8492
- return partialedRight;
8493
- }
8494
- var placeholderSymbol2 = Symbol("partialRight.placeholder");
8495
- partialRight.placeholder = placeholderSymbol2;
8496
-
8497
- // __mcpc__cli_latest/node_modules/@jsr/es-toolkit__es-toolkit/src/function/retry.js
8498
- var DEFAULT_RETRIES = Number.POSITIVE_INFINITY;
8499
-
8500
- // __mcpc__cli_latest/node_modules/@jsr/es-toolkit__es-toolkit/src/object/pick.js
8501
- function pick(obj, keys) {
8502
- const result = {};
8503
- for (let i = 0; i < keys.length; i++) {
8504
- const key = keys[i];
8505
- if (Object.hasOwn(obj, key)) {
8506
- result[key] = obj[key];
8507
- }
8508
- }
8509
- return result;
8510
- }
8511
-
8512
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/factories/args-def-factory.js
8513
- var DECISION_OPTIONS = {
8514
- RETRY: "retry",
8515
- PROCEED: "proceed",
8516
- COMPLETE: "complete"
8517
- };
8518
- function createArgsDefFactory(name, allToolNames, depGroups, predefinedSteps, ensureStepActions) {
8519
- const formatEnsureStepActions = () => {
8520
- if (!ensureStepActions || ensureStepActions.length === 0) {
8521
- return "";
8522
- }
8523
- return `
8524
-
8525
- ## Required Actions
8526
- The workflow MUST include at least one of these actions:
8527
- ${ensureStepActions.map((action) => `- \`${action}\``).join("\n")}`;
8528
- };
8529
- return {
8530
- common: (extra, optionalFields = []) => {
8531
- const requiredFields = Object.keys(extra).filter((key) => !optionalFields.includes(key));
8532
- return {
8533
- type: "object",
8534
- description: `**Tool parameters dynamically update per workflow step**`,
8535
- properties: {
8536
- ...extra
8537
- },
8538
- required: requiredFields
8539
- };
8540
- },
8541
- steps: () => ({
8542
- type: "array",
8543
- description: `
8544
- Workflow step definitions - provide ONLY on initial call.
8545
-
8546
- **CRITICAL RULES:**
8547
- - **Sequential Dependency:** If Action B depends on Action A's result \u2192 separate steps
8548
- - **Concurrent Actions:** Independent actions can share one step
8549
- - **Complete Mapping:** Include ALL requested operations
8550
- - **Predefined Steps:** Leave unspecified if predefined steps exist
8551
-
8552
- **BEST PRACTICES:**
8553
- - Atomic, focused steps
8554
- - Idempotent actions for safe retries
8555
- - Clear step descriptions with input/output context`,
8556
- items: {
8557
- type: "object",
8558
- description: `A single step containing actions that execute concurrently. All actions in this step run simultaneously with no guaranteed order.`,
8559
- properties: {
8560
- description: {
8561
- type: "string",
8562
- description: `**Step purpose, required inputs, and expected outputs**`
8563
- },
8564
- actions: {
8565
- type: "array",
8566
- 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.`,
8567
- items: {
8568
- ...{
8569
- enum: allToolNames
8570
- },
8571
- type: "string",
8572
- description: `Individual action name from available tools. Must be exactly one of the allowed tool names.`
8573
- },
8574
- uniqueItems: true,
8575
- minItems: 0,
8576
- // TODO: remove this restriction when workflow planning is good enough
8577
- maxItems: 1
8578
- }
8579
- },
8580
- required: [
8581
- "description",
8582
- "actions"
8583
- ],
8584
- additionalProperties: false
8585
- },
8586
- default: predefinedSteps ? predefinedSteps : void 0,
8587
- minItems: 1
8588
- }),
8589
- init: () => ({
8590
- type: "boolean",
8591
- description: `Init a new workflow`,
8592
- enum: [
8593
- true
8594
- ]
8595
- }),
8596
- decision: () => ({
8597
- type: "string",
8598
- enum: Object.values(DECISION_OPTIONS),
8599
- description: `**Step control: \`${DECISION_OPTIONS.PROCEED}\` = next step, \`${DECISION_OPTIONS.RETRY}\` = retry/repeat current, \`${DECISION_OPTIONS.COMPLETE}\` = finish workflow**`,
8600
- errorMessage: {
8601
- enum: `Invalid decision. Must be one of: ${Object.values(DECISION_OPTIONS).join(", ")}.`
8602
- }
8603
- }),
8604
- action: () => ({
8605
- type: "string",
8606
- description: "Define the current workflow action to be performed",
8607
- enum: allToolNames,
8608
- required: [
8609
- "action"
8610
- ],
8611
- errorMessage: {
8612
- enum: `Invalid action. Must be one of: ${allToolNames.join(", ")}.`
8613
- }
8614
- }),
8615
- forTool: function() {
8616
- return this.common({});
8617
- },
8618
- forCurrentState: function(state) {
8619
- const currentStep = state.getCurrentStep();
8620
- if (!state.isWorkflowInitialized() || !currentStep) {
8621
- state.reset();
8622
- const initSchema = {
8623
- init: this.init()
8624
- };
8625
- if (!predefinedSteps) {
8626
- initSchema.steps = this.steps();
8627
- }
8628
- return this.common(initSchema);
8629
- }
8630
- const stepDependencies = {
8631
- ...pick(depGroups, currentStep.actions)
8632
- };
8633
- stepDependencies["decision"] = this.decision();
8634
- stepDependencies["action"] = this.action();
8635
- return this.common(stepDependencies);
8636
- },
8637
- forSampling: function() {
8638
- return {
8639
- type: "object",
8640
- description: "Provide user request for autonomous tool execution",
8641
- properties: {
8642
- userRequest: {
8643
- type: "string",
8644
- description: "The task or request that should be completed autonomously by the agentic system using available tools"
8645
- },
8646
- context: {
8647
- type: "object",
8648
- 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.",
8649
- additionalProperties: true
8650
- }
8651
- },
8652
- required: [
8653
- "userRequest",
8654
- "context"
8655
- ],
8656
- errorMessage: {
8657
- required: {
8658
- userRequest: "Missing required field 'userRequest'. Please provide a clear task description.",
8659
- context: "Missing required field 'context'. Please provide relevant context (e.g., current working directory)."
8660
- }
8661
- }
8662
- };
8663
- },
8664
- forAgentic: function(toolNameToDetailList, _sampling = false, USE_TOOL_KEY = "useTool") {
8665
- const allOf = [
8666
- // When a specific tool is selected, its parameters must be provided
8667
- ...toolNameToDetailList.map(([toolName, _toolDetail]) => {
8668
- return {
8669
- if: {
8670
- properties: {
8671
- [USE_TOOL_KEY]: {
8672
- const: toolName
8673
- }
8674
- },
8675
- required: [
8676
- USE_TOOL_KEY
8677
- ]
8678
- },
8679
- then: {
8680
- required: [
8681
- toolName
8682
- ],
8683
- errorMessage: {
8684
- required: {
8685
- [toolName]: `Tool "${toolName}" is selected but its parameters are missing. Please provide "${toolName}": { ...parameters }.`
8686
- }
8687
- }
8688
- }
8689
- };
8690
- })
8691
- ];
8692
- 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**`;
8693
- const toolItems = allToolNames.length > 0 ? {
8694
- type: "string",
8695
- enum: allToolNames
8696
- } : {
8697
- type: "string"
8698
- };
8699
- const baseProperties = {
8700
- [USE_TOOL_KEY]: {
8701
- type: "string",
8702
- enum: allToolNames,
8703
- description: useToolDescription,
8704
- errorMessage: {
8705
- enum: `Invalid tool name. Available tools: ${allToolNames.join(", ")}.`
8706
- }
8707
- },
8708
- hasDefinitions: {
8709
- type: "array",
8710
- items: toolItems,
8711
- description: "Tool names whose schemas you already have. List all tools you have schemas for to avoid duplicate schema requests and reduce token usage."
8712
- },
8713
- definitionsOf: {
8714
- type: "array",
8715
- items: toolItems,
8716
- description: "Tool names whose schemas you need. Request tool schemas before calling them to understand their parameters."
8717
- }
8718
- };
8719
- const requiredFields = [];
8720
- const schema = {
8721
- additionalProperties: true,
8722
- type: "object",
8723
- properties: baseProperties,
8724
- required: requiredFields
8725
- };
8726
- if (allOf.length > 0) {
8727
- schema.allOf = allOf;
8728
- }
8729
- if (allToolNames.length > 0) {
8730
- const thenClause = {
8731
- required: [
8732
- USE_TOOL_KEY
8733
- ],
8734
- errorMessage: {
8735
- required: {
8736
- [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.`
8737
- }
8738
- }
8739
- };
8740
- Object.assign(schema, {
8741
- if: {
8742
- // definitionsOf is not provided OR is empty array
8743
- anyOf: [
8744
- {
8745
- not: {
8746
- required: [
8747
- "definitionsOf"
8748
- ]
8749
- }
8750
- },
8751
- {
8752
- properties: {
8753
- definitionsOf: {
8754
- type: "array",
8755
- maxItems: 0
8756
- }
8757
- }
8758
- }
8759
- ]
8760
- },
8761
- then: thenClause
8762
- });
8763
- }
8764
- return schema;
8765
- },
8766
- forNextState: function(state) {
8767
- if (!state.isWorkflowInitialized() || !state.hasNextStep()) {
8768
- throw new Error(`Cannot get next state schema: no next step available`);
8769
- }
8770
- const currentStepIndex = state.getCurrentStepIndex();
8771
- const allSteps = state.getSteps();
8772
- const nextStep = allSteps[currentStepIndex + 1];
8773
- if (!nextStep) {
8774
- throw new Error(`Next step not found`);
8775
- }
8776
- const stepDependencies = {
8777
- ...pick(depGroups, nextStep.actions)
8778
- };
8779
- stepDependencies["decision"] = this.decision();
8780
- stepDependencies["action"] = this.action();
8781
- return this.common(stepDependencies);
8782
- },
8783
- forToolDescription: function(description, state) {
8784
- const enforceToolArgs = this.forCurrentState(state);
8785
- const initTitle = predefinedSteps ? `**YOU MUST execute this tool with following tool arguments to init the workflow**
8786
- NOTE: The \`steps\` has been predefined` : `**You MUST execute this tool with following tool arguments to plan and init the workflow**`;
8787
- return CompiledPrompts.workflowToolDescription({
8788
- description,
8789
- initTitle,
8790
- ensureStepActions: formatEnsureStepActions(),
8791
- schemaDefinition: JSON.stringify(enforceToolArgs, null, 2)
8792
- });
8793
- },
8794
- forInitialStepDescription: function(steps, state) {
8795
- return CompiledPrompts.workflowInit({
8796
- stepCount: steps.length.toString(),
8797
- currentStepDescription: state.getCurrentStep()?.description || "",
8798
- toolName: name,
8799
- schemaDefinition: JSON.stringify(this.forCurrentState(state), null, 2),
8800
- // Remove redundant workflow steps display
8801
- workflowSteps: ""
8802
- });
8803
- }
8804
- };
8805
- }
8806
-
8807
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/agentic/agentic-tool-registrar.js
8808
- function registerAgenticTool(server, { description, name, allToolNames, depGroups, toolNameToDetailList }) {
8809
- const createArgsDef = createArgsDefFactory(name, allToolNames, depGroups, void 0, void 0);
8810
- const agenticExecutor = new AgenticExecutor(name, allToolNames, toolNameToDetailList, server);
8811
- description = CompiledPrompts.autonomousExecution({
8812
- toolName: name,
8813
- description
8814
- });
8815
- const agenticArgsDef = createArgsDef.forAgentic(toolNameToDetailList, false);
8816
- const argsDef = agenticArgsDef;
8817
- const schema = allToolNames.length > 0 ? argsDef : {
8818
- type: "object",
8819
- properties: {}
8820
- };
8821
- server.tool(name, description, jsonSchema(createModelCompatibleJSONSchema(schema)), async (args) => {
8822
- return await agenticExecutor.execute(args, schema);
8823
- });
8824
- }
8825
-
8826
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/mode-agentic-plugin.js
8827
- var createAgenticModePlugin = () => ({
8828
- name: "mode-agentic",
8829
- version: "1.0.0",
8830
- // Only apply to agentic mode
8831
- apply: "agentic",
8832
- // Register the agent tool
8833
- registerAgentTool: (context2) => {
8834
- registerAgenticTool(context2.server, {
8835
- description: context2.description,
8836
- name: context2.name,
8837
- allToolNames: context2.allToolNames,
8838
- depGroups: context2.depGroups,
8839
- toolNameToDetailList: context2.toolNameToDetailList
8840
- });
8841
- }
8842
- });
8843
- var mode_agentic_plugin_default = createAgenticModePlugin();
8844
-
8845
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/state.js
8846
- var WorkflowState = class {
8847
- currentStepIndex = -1;
8848
- steps = [];
8849
- stepStatuses = [];
8850
- stepResults = [];
8851
- stepErrors = [];
8852
- isInitialized = false;
8853
- isStarted = false;
8854
- constructor(steps) {
8855
- if (steps) {
8856
- this.initialize(steps);
8857
- }
8858
- }
8859
- getCurrentStepIndex() {
8860
- return this.currentStepIndex;
8861
- }
8862
- getSteps() {
8863
- return this.steps;
8864
- }
8865
- isWorkflowInitialized() {
8866
- return this.isInitialized;
8867
- }
8868
- getCurrentStep() {
8869
- if (!this.isInitialized || this.currentStepIndex < 0) {
8870
- return null;
8871
- }
8872
- return this.steps[this.currentStepIndex] || null;
8873
- }
8874
- getNextStep() {
8875
- if (!this.isInitialized) return null;
8876
- const nextIndex = this.currentStepIndex + 1;
8877
- return this.steps[nextIndex] || null;
8878
- }
8879
- // Get the previous step in the workflow
8880
- getPreviousStep() {
8881
- if (!this.isInitialized) return null;
8882
- const prevIndex = this.currentStepIndex - 1;
8883
- return this.steps[prevIndex] || null;
8884
- }
8885
- hasNextStep() {
8886
- return this.getNextStep() !== null;
8887
- }
8888
- // Check if there is a previous step available
8889
- hasPreviousStep() {
8890
- return this.getPreviousStep() !== null;
8891
- }
8892
- // Check if currently at the first step
8893
- isAtFirstStep() {
8894
- return this.isInitialized && this.currentStepIndex === 0;
8895
- }
8896
- // Check if currently at the last step
8897
- isAtLastStep() {
8898
- return this.isInitialized && this.currentStepIndex >= this.steps.length - 1;
8899
- }
8900
- isWorkflowStarted() {
8901
- return this.isStarted;
8902
- }
8903
- isCompleted() {
8904
- return this.isInitialized && this.currentStepIndex > this.steps.length - 1;
8905
- }
8906
- // Mark workflow as completed by moving beyond the last step
8907
- markCompleted() {
8908
- if (this.isInitialized) {
8909
- this.currentStepIndex = this.steps.length;
8910
- }
8911
- }
8912
- initialize(steps) {
8913
- this.steps = steps;
8914
- this.stepStatuses = new Array(steps.length).fill("pending");
8915
- this.stepResults = new Array(steps.length).fill("");
8916
- this.stepErrors = new Array(steps.length).fill("");
8917
- this.currentStepIndex = 0;
8918
- this.isInitialized = true;
8919
- this.isStarted = false;
8920
- }
8921
- // Mark current step as running
8922
- markCurrentStepRunning() {
8923
- if (this.isInitialized && this.currentStepIndex >= 0 && this.currentStepIndex < this.steps.length) {
8924
- this.stepStatuses[this.currentStepIndex] = "running";
8925
- }
8926
- }
8927
- // Mark current step as completed
8928
- markCurrentStepCompleted(result) {
8929
- if (this.isInitialized && this.currentStepIndex >= 0 && this.currentStepIndex < this.steps.length) {
8930
- this.stepStatuses[this.currentStepIndex] = "completed";
8931
- if (result) {
8932
- this.stepResults[this.currentStepIndex] = result;
8933
- }
8934
- }
8935
- }
8936
- // Mark current step as failed
8937
- markCurrentStepFailed(error) {
8938
- if (this.isInitialized && this.currentStepIndex >= 0 && this.currentStepIndex < this.steps.length) {
8939
- this.stepStatuses[this.currentStepIndex] = "failed";
8940
- if (error) {
8941
- this.stepErrors[this.currentStepIndex] = error;
8942
- }
8943
- }
8944
- }
8945
- // Get steps with their status
8946
- getStepsWithStatus() {
8947
- return this.steps.map((step, index) => ({
8948
- ...step,
8949
- status: this.stepStatuses[index] || "pending",
8950
- result: this.stepResults[index] || void 0,
8951
- error: this.stepErrors[index] || void 0
8952
- }));
8953
- }
8954
- // Get basic workflow progress data for template rendering
8955
- getProgressData() {
8956
- return {
8957
- steps: this.steps,
8958
- statuses: this.stepStatuses,
8959
- results: this.stepResults,
8960
- errors: this.stepErrors,
8961
- currentStepIndex: this.currentStepIndex,
8962
- totalSteps: this.steps.length
8963
- };
8964
- }
8965
- start() {
8966
- this.isStarted = true;
8967
- }
8968
- moveToNextStep() {
8969
- if (!this.hasNextStep()) {
8970
- return false;
8971
- }
8972
- this.currentStepIndex++;
8973
- return true;
8974
- }
8975
- // Move to the previous step in the workflow
8976
- moveToPreviousStep() {
8977
- if (!this.hasPreviousStep()) {
8978
- return false;
8979
- }
8980
- this.currentStepIndex--;
8981
- return true;
8982
- }
8983
- // Move to a specific step by index (optional feature)
8984
- moveToStep(stepIndex) {
8985
- if (!this.isInitialized || stepIndex < 0 || stepIndex >= this.steps.length) {
8986
- return false;
8987
- }
8988
- this.currentStepIndex = stepIndex;
8989
- return true;
8990
- }
8991
- reset() {
8992
- this.currentStepIndex = -1;
8993
- this.steps = [];
8994
- this.stepStatuses = [];
8995
- this.stepResults = [];
8996
- this.stepErrors = [];
8997
- this.isInitialized = false;
8998
- this.isStarted = false;
8999
- }
9000
- getDebugInfo() {
9001
- return {
9002
- currentStepIndex: this.currentStepIndex,
9003
- totalSteps: this.steps.length,
9004
- isInitialized: this.isInitialized,
9005
- currentStep: this.getCurrentStep()?.description,
9006
- nextStep: this.getNextStep()?.description,
9007
- previousStep: this.getPreviousStep()?.description,
9008
- isAtFirstStep: this.isAtFirstStep(),
9009
- hasPreviousStep: this.hasPreviousStep()
9010
- };
9011
- }
9012
- };
9013
-
9014
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/workflow/workflow-executor.js
9015
- var WorkflowExecutor = class {
9016
- name;
9017
- allToolNames;
9018
- toolNameToDetailList;
9019
- createArgsDef;
9020
- server;
9021
- predefinedSteps;
9022
- ensureStepActions;
9023
- toolNameToIdMapping;
9024
- constructor(name, allToolNames, toolNameToDetailList, createArgsDef, server, predefinedSteps, ensureStepActions, toolNameToIdMapping) {
9025
- this.name = name;
9026
- this.allToolNames = allToolNames;
9027
- this.toolNameToDetailList = toolNameToDetailList;
9028
- this.createArgsDef = createArgsDef;
9029
- this.server = server;
9030
- this.predefinedSteps = predefinedSteps;
9031
- this.ensureStepActions = ensureStepActions;
9032
- this.toolNameToIdMapping = toolNameToIdMapping;
9033
- }
9034
- // Helper method to validate required actions are present in workflow steps
9035
- validateRequiredActions(steps) {
9036
- if (!this.ensureStepActions || this.ensureStepActions.length === 0) {
9037
- return {
9038
- valid: true,
9039
- missing: []
9040
- };
9041
- }
9042
- const allStepActions = /* @__PURE__ */ new Set();
9043
- steps.forEach((step) => {
9044
- step.actions.forEach((action) => allStepActions.add(action));
9045
- });
9046
- const missing = [];
9047
- for (const requiredAction of this.ensureStepActions) {
9048
- if (allStepActions.has(requiredAction)) {
9049
- continue;
9050
- }
9051
- if (this.toolNameToIdMapping) {
9052
- const mappedToolId = this.toolNameToIdMapping.get(requiredAction);
9053
- if (mappedToolId && allStepActions.has(mappedToolId)) {
9054
- continue;
9055
- }
9056
- }
9057
- missing.push(requiredAction);
9058
- }
9059
- return {
9060
- valid: missing.length === 0,
9061
- missing
9062
- };
9063
- }
9064
- // Helper method to format workflow progress
9065
- formatProgress(state) {
9066
- const progressData = state.getProgressData();
9067
- return PromptUtils.formatWorkflowProgress(progressData);
9068
- }
9069
- async execute(args, state) {
9070
- if (args.init) {
9071
- state.reset();
9072
- } else {
9073
- if (!state.isWorkflowInitialized() && !args.init) {
9074
- return {
9075
- content: [
9076
- {
9077
- type: "text",
9078
- text: this.predefinedSteps ? WorkflowPrompts.ERRORS.NOT_INITIALIZED.WITH_PREDEFINED : WorkflowPrompts.ERRORS.NOT_INITIALIZED.WITHOUT_PREDEFINED
9079
- }
9080
- ],
9081
- isError: true
9082
- };
9083
- }
9084
- const decision2 = args.decision;
9085
- if (decision2 === "proceed") {
9086
- if (state.isAtLastStep() && state.isWorkflowStarted()) {
9087
- state.markCompleted();
9088
- return {
9089
- content: [
9090
- {
9091
- type: "text",
9092
- text: `## Workflow Completed!
9093
-
9094
- ${this.formatProgress(state)}
9095
-
9096
- ${CompiledPrompts.workflowCompleted({
9097
- totalSteps: state.getSteps().length,
9098
- toolName: this.name,
9099
- newWorkflowInstructions: this.predefinedSteps ? "" : " and new `steps` array"
9100
- })}`
9101
- }
9102
- ],
9103
- isError: false
9104
- };
9105
- }
9106
- if (state.isCompleted()) {
9107
- return {
9108
- content: [
9109
- {
9110
- type: "text",
9111
- text: WorkflowPrompts.ERRORS.ALREADY_AT_FINAL
9112
- }
9113
- ],
9114
- isError: true
9115
- };
9116
- }
9117
- const currentStepIndex = state.getCurrentStepIndex();
9118
- const wasStarted = state.isWorkflowStarted();
9119
- if (state.isWorkflowStarted()) {
9120
- state.moveToNextStep();
9121
- } else {
9122
- state.start();
9123
- }
9124
- const nextStepValidationSchema = this.createArgsDef.forCurrentState(state);
9125
- const nextStepValidationResult = this.validateInput(args, nextStepValidationSchema);
9126
- if (!nextStepValidationResult.valid) {
9127
- if (wasStarted) {
9128
- state.moveToStep(currentStepIndex);
9129
- } else {
9130
- state.moveToStep(currentStepIndex);
9131
- }
9132
- return {
9133
- content: [
9134
- {
9135
- type: "text",
9136
- text: CompiledPrompts.workflowErrorResponse({
9137
- errorMessage: `Cannot proceed to next step: ${nextStepValidationResult.error || "Arguments validation failed"}`
9138
- })
9139
- }
9140
- ],
9141
- isError: true
9142
- };
9143
- }
9144
- } else if (decision2 === "complete") {
9145
- if (state.isAtLastStep() && state.isWorkflowStarted()) {
9146
- state.markCompleted();
9147
- return {
9148
- content: [
9149
- {
9150
- type: "text",
9151
- text: `## Workflow Completed!
9152
-
9153
- ${this.formatProgress(state)}
9154
-
9155
- ${CompiledPrompts.workflowCompleted({
9156
- totalSteps: state.getSteps().length,
9157
- toolName: this.name,
9158
- newWorkflowInstructions: this.predefinedSteps ? "" : " and new `steps` array"
9159
- })}`
9160
- }
9161
- ],
9162
- isError: false
9163
- };
9164
- } else {
9165
- return {
9166
- content: [
9167
- {
9168
- type: "text",
9169
- text: WorkflowPrompts.ERRORS.CANNOT_COMPLETE_NOT_AT_FINAL
9170
- }
9171
- ],
9172
- isError: true
9173
- };
9174
- }
9175
- }
9176
- }
9177
- const decision = args.decision;
9178
- if (decision !== "proceed") {
9179
- const validationSchema = this.createArgsDef.forCurrentState(state);
9180
- const validationResult = this.validateInput(args, validationSchema);
9181
- if (!validationResult.valid) {
9182
- return {
9183
- content: [
9184
- {
9185
- type: "text",
9186
- text: CompiledPrompts.workflowErrorResponse({
9187
- errorMessage: validationResult.error || "Arguments validation failed"
9188
- })
9189
- }
9190
- ],
9191
- isError: true
9192
- };
9193
- }
9194
- }
9195
- if (args.init) {
9196
- return this.initialize(args, state);
9197
- }
9198
- return await this.executeStep(args, state);
9199
- }
9200
- initialize(args, state) {
9201
- const steps = args.steps ?? this.predefinedSteps;
9202
- if (!steps || steps.length === 0) {
9203
- return {
9204
- content: [
9205
- {
9206
- type: "text",
9207
- text: WorkflowPrompts.ERRORS.NO_STEPS_PROVIDED
9208
- }
9209
- ],
9210
- isError: true
9211
- };
9212
- }
9213
- const validation = this.validateRequiredActions(steps);
9214
- if (!validation.valid) {
9215
- return {
9216
- content: [
9217
- {
9218
- type: "text",
9219
- text: `## Workflow Validation Failed \u274C
9220
-
9221
- **Missing Required Actions:** The following actions must be included in the workflow steps:
9222
-
9223
- ${validation.missing.map((action) => `- \`${this.toolNameToIdMapping?.get(action) ?? action}\``).join("\n")}`
9224
- }
9225
- ],
9226
- isError: true
9227
- };
9228
- }
9229
- state.initialize(steps);
9230
- return {
9231
- content: [
9232
- {
9233
- type: "text",
9234
- text: `## Workflow Initialized
9235
- ${this.formatProgress(state)}
9236
- ${this.createArgsDef.forInitialStepDescription(steps, state)}`
9237
- }
9238
- ],
9239
- isError: false
9240
- };
9241
- }
9242
- async executeStep(args, state) {
9243
- const currentStep = state.getCurrentStep();
9244
- if (!currentStep) {
9245
- return {
9246
- content: [
9247
- {
9248
- type: "text",
9249
- text: WorkflowPrompts.ERRORS.NO_CURRENT_STEP
9250
- }
9251
- ],
9252
- isError: true
9253
- };
9254
- }
9255
- state.markCurrentStepRunning();
9256
- const results = {
9257
- content: [],
9258
- isError: false
9259
- };
9260
- for (const action of currentStep.actions) {
9261
- try {
9262
- const actionArgs = args[action] || {};
9263
- const actionResult = await this.server.callTool(action, actionArgs);
9264
- if (!results.isError) {
9265
- results.isError = actionResult.isError;
9266
- }
9267
- results.content = results.content.concat(actionResult.content ?? []);
9268
- results.content.push({
9269
- type: "text",
9270
- text: `Action \`${action}\` executed ${actionResult.isError ? "\u274C **FAILED**" : "\u2705 **SUCCESS**"}:`
9271
- });
9272
- } catch (error) {
9273
- results.content.push({
9274
- type: "text",
9275
- text: `${error.message}`
9276
- });
9277
- results.content.push({
9278
- type: "text",
9279
- text: `Action \`${action}\` \u274C **FAILED** with error: `
9280
- });
9281
- results.isError = true;
9282
- }
9283
- }
9284
- if (results.isError) {
9285
- state.markCurrentStepFailed("Step execution failed");
9286
- } else {
9287
- state.markCurrentStepCompleted("Step completed successfully");
9288
- }
9289
- if (state.hasNextStep()) {
9290
- const nextStepArgsDef = this.createArgsDef.forNextState(state);
9291
- results.content.push({
9292
- type: "text",
9293
- text: CompiledPrompts.nextStepDecision({
9294
- toolName: this.name,
9295
- nextStepDescription: state.getNextStep()?.description || "Unknown step",
9296
- nextStepSchema: JSON.stringify(nextStepArgsDef, null, 2)
9297
- })
9298
- });
9299
- } else {
9300
- results.content.push({
9301
- type: "text",
9302
- text: CompiledPrompts.finalStepCompletion({
9303
- statusIcon: results.isError ? "\u274C" : "\u2705",
9304
- statusText: results.isError ? "with errors" : "successfully",
9305
- toolName: this.name,
9306
- newWorkflowInstructions: this.predefinedSteps ? "" : " and new `steps` array"
9307
- })
9308
- });
9309
- }
9310
- results.content.push({
9311
- type: "text",
9312
- text: `## Workflow Progress
9313
- ${this.formatProgress(state)}`
9314
- });
9315
- return results;
9316
- }
9317
- // Validate arguments using JSON schema
9318
- validateInput(args, schema) {
9319
- return validateSchema(args, schema);
9320
- }
9321
- };
9322
-
9323
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/workflow/workflow-tool-registrar.js
9324
- function registerAgenticWorkflowTool(server, { description, name, allToolNames, depGroups, toolNameToDetailList, predefinedSteps, ensureStepActions, toolNameToIdMapping }) {
9325
- const createArgsDef = createArgsDefFactory(name, allToolNames, depGroups, predefinedSteps, ensureStepActions);
9326
- const workflowExecutor = new WorkflowExecutor(name, allToolNames, toolNameToDetailList, createArgsDef, server, predefinedSteps, ensureStepActions, toolNameToIdMapping);
9327
- const workflowState = new WorkflowState();
9328
- const planningInstructions = predefinedSteps ? "- Set `init: true` (steps are predefined)" : "- Set `init: true` and define complete `steps` array";
9329
- const baseDescription = CompiledPrompts.workflowExecution({
9330
- toolName: name,
9331
- description,
9332
- planningInstructions
9333
- });
9334
- const argsDef = createArgsDef.forTool();
9335
- const toolDescription = createArgsDef.forToolDescription(baseDescription, workflowState);
9336
- server.tool(name, toolDescription, jsonSchema(createModelCompatibleJSONSchema(argsDef)), async (args) => {
9337
- try {
9338
- return await workflowExecutor.execute(args, workflowState);
9339
- } catch (error) {
9340
- workflowState.reset();
9341
- return {
9342
- content: [
9343
- {
9344
- type: "text",
9345
- text: `Workflow execution error: ${error.message}`
9346
- }
9347
- ],
9348
- isError: true
9349
- };
9350
- }
9351
- });
9352
- }
9353
-
9354
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/mode-workflow-plugin.js
9355
- var createWorkflowModePlugin = () => ({
9356
- name: "mode-workflow",
9357
- version: "1.0.0",
9358
- // Only apply to workflow mode
9359
- apply: "agentic_workflow",
9360
- // Register the agent tool
9361
- registerAgentTool: (context2) => {
9362
- registerAgenticWorkflowTool(context2.server, {
9363
- description: context2.description,
9364
- name: context2.name,
9365
- allToolNames: context2.allToolNames,
9366
- depGroups: context2.depGroups,
9367
- toolNameToDetailList: context2.toolNameToDetailList,
9368
- predefinedSteps: context2.options.steps,
9369
- ensureStepActions: context2.options.ensureStepActions,
9370
- toolNameToIdMapping: context2.toolNameToIdMapping
9371
- });
9372
- }
9373
- });
9374
- var mode_workflow_plugin_default = createWorkflowModePlugin();
9375
-
9376
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/sampling/base-sampling-executor.js
9377
- var import_node_process8 = __toESM(require("node:process"), 1);
9378
- var BaseSamplingExecutor = class {
9379
- name;
9380
- description;
9381
- allToolNames;
9382
- toolNameToDetailList;
9383
- server;
9384
- conversationHistory;
9385
- maxIterations;
9386
- currentIteration;
9387
- logger;
9388
- tracingEnabled;
9389
- summarize;
9390
- constructor(name, description, allToolNames, toolNameToDetailList, server, config) {
9391
- this.name = name;
9392
- this.description = description;
9393
- this.allToolNames = allToolNames;
9394
- this.toolNameToDetailList = toolNameToDetailList;
9395
- this.server = server;
9396
- this.conversationHistory = [];
9397
- this.maxIterations = 55;
9398
- this.currentIteration = 0;
9399
- this.tracingEnabled = false;
9400
- this.summarize = true;
9401
- if (config?.maxIterations) {
9402
- this.maxIterations = config.maxIterations;
9403
- }
9404
- if (config?.summarize !== void 0) {
9405
- this.summarize = config.summarize;
9406
- }
9407
- this.logger = createLogger(`mcpc.sampling.${name}`, server);
9408
- try {
9409
- const tracingConfig = {
9410
- enabled: import_node_process8.default.env.MCPC_TRACING_ENABLED === "true",
9411
- serviceName: `mcpc-sampling-${name}`,
9412
- exportTo: import_node_process8.default.env.MCPC_TRACING_EXPORT ?? "otlp",
9413
- otlpEndpoint: import_node_process8.default.env.MCPC_TRACING_OTLP_ENDPOINT ?? "http://localhost:4318/v1/traces"
9414
- };
9415
- this.tracingEnabled = tracingConfig.enabled;
9416
- if (this.tracingEnabled) {
9417
- initializeTracing(tracingConfig);
9418
- }
9419
- } catch {
9420
- this.tracingEnabled = false;
9421
- }
9422
- }
9423
- /**
9424
- * Convert toolNameToDetailList to MCP Tool format for sampling
9425
- */
9426
- convertToMcpTools() {
9427
- return this.toolNameToDetailList.map(([name, detail]) => ({
9428
- name,
9429
- description: detail.description || `Tool: ${name}`,
9430
- inputSchema: {
9431
- type: "object",
9432
- ...detail.inputSchema
9433
- }
9434
- }));
9435
- }
9436
- /**
9437
- * Check if client supports sampling with tools
9438
- */
9439
- supportsSamplingTools() {
9440
- const capabilities = this.server.getClientCapabilities();
9441
- return !!capabilities?.sampling?.tools;
9442
- }
9443
- /**
9444
- * Check if response contains tool use
9445
- */
9446
- isToolUseResponse(response) {
9447
- if (!response.content) return false;
9448
- const content = Array.isArray(response.content) ? response.content : [
9449
- response.content
9450
- ];
9451
- return content.some((block) => block.type === "tool_use");
9452
- }
9453
- /**
9454
- * Extract tool calls from response
9455
- */
9456
- extractToolCalls(response) {
9457
- if (!response.content) return [];
9458
- const content = Array.isArray(response.content) ? response.content : [
9459
- response.content
9460
- ];
9461
- return content.filter((block) => block.type === "tool_use").map((block) => "id" in block && "name" in block && "input" in block ? {
9462
- id: block.id,
9463
- name: block.name,
9464
- input: block.input || {}
9465
- } : {
9466
- id: "",
9467
- name: "",
9468
- input: {}
9469
- });
9470
- }
9471
- async runSamplingLoop(systemPrompt, schema, state) {
9472
- const useTools = this.supportsSamplingTools();
9473
- this.logger.debug({
9474
- message: "Sampling mode determined",
9475
- useTools,
9476
- mode: useTools ? "native_tools" : "json_fallback"
9477
- });
9478
- this.conversationHistory = [
9479
- {
9480
- // Failed: 400 {"error":{"message":"messages: at least one message is required","code":"invalid_request_body"}}
9481
- role: "user",
9482
- content: {
9483
- type: "text",
9484
- text: `start`
9485
- }
9486
- }
9487
- ];
9488
- const loopSpan = this.tracingEnabled ? startSpan("mcpc.sampling_loop", {
9489
- agent: this.name,
9490
- maxIterations: this.maxIterations,
9491
- systemPrompt: systemPrompt()
9492
- }) : null;
9493
- try {
9494
- for (this.currentIteration = 0; this.currentIteration < this.maxIterations; this.currentIteration++) {
9495
- let iterationSpan = null;
9496
- try {
9497
- let createMessageParams;
9498
- if (useTools) {
9499
- createMessageParams = {
9500
- systemPrompt: systemPrompt(),
9501
- messages: this.conversationHistory,
9502
- maxTokens: 55e3,
9503
- tools: this.convertToMcpTools(),
9504
- toolChoice: {
9505
- mode: "auto"
9506
- }
9507
- };
9508
- } else {
9509
- createMessageParams = {
9510
- systemPrompt: systemPrompt(),
9511
- messages: this.conversationHistory,
9512
- maxTokens: 55e3
9513
- };
9514
- }
9515
- const response = await this.server.createMessage(createMessageParams);
9516
- const model = response.model;
9517
- const stopReason = response.stopReason;
9518
- const role = response.role;
9519
- if (useTools && this.isToolUseResponse(response)) {
9520
- const toolCalls = this.extractToolCalls(response);
9521
- if (toolCalls.length === 0) {
9522
- const contentArray = Array.isArray(response.content) ? response.content : [
9523
- response.content
9524
- ];
9525
- const textBlock = contentArray.find((c) => c.type === "text");
9526
- const textContent2 = textBlock && "text" in textBlock ? textBlock.text : void 0;
9527
- if (textContent2) {
9528
- return await this.createCompletionResult(textContent2, loopSpan);
9529
- }
9530
- continue;
9531
- }
9532
- iterationSpan = this.tracingEnabled ? startSpan("mcpc.sampling_iteration.tool_use", {
9533
- iteration: this.currentIteration + 1,
9534
- agent: this.name,
9535
- toolCalls: toolCalls.length,
9536
- maxIterations: this.maxIterations
9537
- }, loopSpan ?? void 0) : null;
9538
- this.conversationHistory.push({
9539
- role: "assistant",
9540
- content: response.content
9541
- });
9542
- const toolResults = [];
9543
- for (const toolCall of toolCalls) {
9544
- try {
9545
- const result2 = await this.server.callTool(toolCall.name, toolCall.input);
9546
- toolResults.push({
9547
- type: "tool_result",
9548
- toolUseId: toolCall.id,
9549
- content: result2.content || [],
9550
- isError: result2.isError
9551
- });
9552
- } catch (error) {
9553
- toolResults.push({
9554
- type: "tool_result",
9555
- toolUseId: toolCall.id,
9556
- content: [
9557
- {
9558
- type: "text",
9559
- text: `Error: ${error instanceof Error ? error.message : String(error)}`
9560
- }
9561
- ],
9562
- isError: true
9563
- });
9564
- }
9565
- }
9566
- this.conversationHistory.push({
9567
- role: "user",
9568
- content: toolResults
9569
- });
9570
- if (iterationSpan) {
9571
- iterationSpan.setAttributes({
9572
- toolExecutions: toolResults.length,
9573
- hasErrors: toolResults.some((r) => r.isError)
9574
- });
9575
- endSpan(iterationSpan);
9576
- }
9577
- continue;
9578
- }
9579
- const content = Array.isArray(response.content) ? response.content : [
9580
- response.content
9581
- ];
9582
- const textContent = content.find((c) => c.type === "text");
9583
- const responseContent = textContent?.text || "{}";
9584
- let parsedData;
9585
- try {
9586
- parsedData = parseJSON(responseContent.trim(), true);
9587
- } catch (parseError) {
9588
- iterationSpan = this.tracingEnabled ? startSpan("mcpc.sampling_iteration.parse_error", {
9589
- iteration: this.currentIteration + 1,
9590
- agent: this.name,
9591
- error: String(parseError),
9592
- maxIterations: this.maxIterations
9593
- }, loopSpan ?? void 0) : null;
9594
- this.addParsingErrorToHistory(responseContent, parseError);
9595
- if (iterationSpan) endSpan(iterationSpan);
9596
- continue;
9597
- }
9598
- this.conversationHistory.push({
9599
- role: "assistant",
9600
- content: {
9601
- type: "text",
9602
- text: JSON.stringify(parsedData, null, 2)
9603
- }
9604
- });
9605
- const decision = parsedData["decision"];
9606
- const useTool = parsedData["useTool"];
9607
- const actionStr = decision === "complete" ? "completion" : useTool && typeof useTool === "string" ? String(useTool) : "unknown_action";
9608
- const spanName = `mcpc.sampling_iteration.${actionStr}`;
9609
- iterationSpan = this.tracingEnabled ? startSpan(spanName, {
9610
- iteration: this.currentIteration + 1,
9611
- agent: this.name,
9612
- action: actionStr,
9613
- systemPrompt: systemPrompt(),
9614
- maxTokens: String(Number.MAX_SAFE_INTEGER),
9615
- maxIterations: this.maxIterations,
9616
- messages: JSON.stringify(this.conversationHistory)
9617
- }, loopSpan ?? void 0) : null;
9618
- const result = await this.processAction(parsedData, schema, state, iterationSpan);
9619
- this.logIterationProgress(parsedData, result, model, stopReason, role);
9620
- if (iterationSpan) {
9621
- let rawJson = "{}";
9622
- try {
9623
- rawJson = parsedData ? JSON.stringify(parsedData) : "{}";
9624
- } catch {
9625
- }
9626
- const attr = {
9627
- isError: !!result.isError,
9628
- isComplete: !!result.isComplete,
9629
- iteration: this.currentIteration + 1,
9630
- maxIterations: this.maxIterations,
9631
- parsed: rawJson,
9632
- action: typeof useTool === "string" ? useTool : String(useTool),
9633
- decision: typeof decision === "string" ? decision : String(decision),
9634
- samplingResponse: responseContent,
9635
- toolResult: JSON.stringify(result),
9636
- model,
9637
- role
9638
- };
9639
- if (stopReason) {
9640
- attr.stopReason = stopReason;
9641
- }
9642
- iterationSpan.setAttributes(attr);
9643
- }
9644
- if (result.isError) {
9645
- const errorText = result.content?.[0] && "text" in result.content[0] ? result.content[0].text : "Unknown error";
9646
- this.conversationHistory.push({
9647
- role: "user",
9648
- content: {
9649
- type: "text",
9650
- text: errorText
9651
- }
9652
- });
9653
- if (iterationSpan) endSpan(iterationSpan);
9654
- continue;
9655
- }
9656
- if (result.isComplete) {
9657
- if (iterationSpan) endSpan(iterationSpan);
9658
- if (loopSpan) endSpan(loopSpan);
9659
- return result;
9660
- }
9661
- if (iterationSpan) endSpan(iterationSpan);
9662
- } catch (iterError) {
9663
- if (iterationSpan) endSpan(iterationSpan, iterError);
9664
- throw iterError;
9665
- }
9666
- }
9667
- if (loopSpan) endSpan(loopSpan);
9668
- return await this.createMaxIterationsError(loopSpan);
9669
- } catch (error) {
9670
- if (loopSpan) endSpan(loopSpan, error);
9671
- return await this.createExecutionError(error, loopSpan);
9672
- }
9673
- }
9674
- addParsingErrorToHistory(_responseText, parseError) {
9675
- const errorMsg = parseError instanceof Error ? parseError.message : String(parseError);
9676
- this.conversationHistory.push({
9677
- role: "user",
9678
- content: {
9679
- type: "text",
9680
- text: `Invalid JSON: ${errorMsg}
9681
-
9682
- Respond with valid JSON.`
9683
- }
9684
- });
9685
- }
9686
- async createMaxIterationsError(parentSpan) {
9687
- const result = await this.createCompletionResult(`Reached max iterations (${this.maxIterations}). Try a more specific request.`, parentSpan);
9688
- result.isError = true;
9689
- result.isComplete = false;
9690
- return result;
9691
- }
9692
- async createExecutionError(error, parentSpan) {
9693
- const result = await this.createCompletionResult(`Execution error: ${error instanceof Error ? error.message : String(error)}`, parentSpan);
9694
- result.isError = true;
9695
- result.isComplete = false;
9696
- return result;
9697
- }
9698
- async createCompletionResult(text, parentSpan) {
9699
- const summary = this.summarize ? await this.summarizeConversation(parentSpan) : this.formatConversation();
9700
- return {
9701
- content: [
9702
- {
9703
- type: "text",
9704
- text: `${text}
9705
-
9706
- **Execution Summary:**
9707
- - Iterations used: ${this.currentIteration + 1}/${this.maxIterations}
9708
- - Agent: ${this.name}
9709
- ${summary}`
9710
- }
9711
- ],
9712
- isError: false,
9713
- isComplete: true
9714
- };
9715
- }
9716
- // Use LLM to create high-signal summary for parent agent
9717
- async summarizeConversation(parentSpan) {
9718
- if (this.conversationHistory.length === 0) {
9719
- return "\n\n**No conversation history**";
9720
- }
9721
- if (this.conversationHistory.length <= 3) {
9722
- return this.formatConversation();
9723
- }
9724
- const summarizeSpan = this.tracingEnabled ? startSpan("mcpc.sampling_summarize", {
9725
- agent: this.name,
9726
- messageCount: this.conversationHistory.length
9727
- }, parentSpan ?? void 0) : null;
9728
- try {
9729
- this.logger.debug({
9730
- message: "Starting conversation summarization",
9731
- messageCount: this.conversationHistory.length
9732
- });
9733
- const history = this.conversationHistory.map((msg, i) => {
9734
- const prefix = `[${i + 1}] ${msg.role.toUpperCase()}`;
9735
- const contentArray = Array.isArray(msg.content) ? msg.content : [
9736
- msg.content
9737
- ];
9738
- const textBlock = contentArray.find((c) => c.type === "text");
9739
- const text = textBlock?.text || "(No text content)";
9740
- return `${prefix}:
9741
- ${text}`;
9742
- }).join("\n\n---\n\n");
9743
- const response = await this.server.createMessage({
9744
- systemPrompt: `Summarize this agent execution:
9745
-
9746
- Final Decision: (include complete JSON if present)
9747
- Key Findings: (most important)
9748
- Actions Taken: (high-level flow)
9749
- Errors/Warnings: (if any)
9750
-
9751
- ${history}`,
9752
- messages: [
9753
- {
9754
- role: "user",
9755
- content: {
9756
- type: "text",
9757
- text: "Please provide a concise summary."
9758
- }
9759
- }
9760
- ],
9761
- maxTokens: 3e3
9762
- });
9763
- const summaryContent = Array.isArray(response.content) ? response.content.find((c) => c.type === "text") : response.content;
9764
- const summary = "\n\n" + (summaryContent?.text || "No summary available");
9765
- this.logger.debug({
9766
- message: "Summarization completed",
9767
- summaryLength: summary.length
9768
- });
9769
- if (summarizeSpan) {
9770
- summarizeSpan.setAttributes({
9771
- summaryLength: summary.length,
9772
- summary,
9773
- success: true
9774
- });
9775
- endSpan(summarizeSpan);
9776
- }
9777
- return summary;
9778
- } catch (error) {
9779
- this.logger.warning({
9780
- message: "Summarization failed, falling back to full history",
8098
+ this.logger.error({
8099
+ message: "Unexpected error in execute",
9781
8100
  error: String(error)
9782
8101
  });
9783
- if (summarizeSpan) {
9784
- endSpan(summarizeSpan, error);
9785
- }
9786
- return this.formatConversation();
9787
- }
9788
- }
9789
- // Format full conversation history (for debugging)
9790
- formatConversation() {
9791
- if (this.conversationHistory.length === 0) {
9792
- return "\n\n**No conversation history**";
9793
- }
9794
- const messages = this.conversationHistory.map((msg, i) => {
9795
- const header = `### Message ${i + 1}: ${msg.role}`;
9796
- const contentArray = Array.isArray(msg.content) ? msg.content : [
9797
- msg.content
9798
- ];
9799
- const textBlock = contentArray.find((c) => c.type === "text");
9800
- const contentText = textBlock?.text;
9801
- if (!contentText) {
9802
- return `${header}\\n(No text content)`;
9803
- }
9804
- try {
9805
- const parsed = JSON.parse(contentText);
9806
- if (JSON.stringify(parsed).length < 100) {
9807
- return `${header}\\n${JSON.stringify(parsed)}`;
9808
- }
9809
- return `${header}\\n\`\`\`json\\n${JSON.stringify(parsed, null, 2)}\\n\`\`\``;
9810
- } catch {
9811
- return `${header}\\n${contentText}`;
9812
- }
9813
- });
9814
- return "\n\n**Conversation History:**\n" + messages.join("\n\n");
9815
- }
9816
- logIterationProgress(parsedData, result, model, stopReason, role) {
9817
- this.logger.debug({
9818
- iteration: `${this.currentIteration + 1}/${this.maxIterations}`,
9819
- parsedData,
9820
- isError: result.isError,
9821
- isComplete: result.isComplete,
9822
- model,
9823
- stopReason,
9824
- role,
9825
- result
9826
- });
9827
- }
9828
- formatPromptForMode({ prompt, schema, schemaPrefix = "JSON schema:", schemaSuffix = `STRICT REQUIREMENTS:
9829
- 1. Return ONE AND ONLY ONE raw JSON object that passes JSON.parse() - no markdown, code blocks, explanatory text, or multiple JSON objects
9830
- 2. Include ALL required fields with correct data types and satisfy ALL schema constraints (anyOf, oneOf, allOf, not, enum, pattern, min/max, conditionals)
9831
- 3. Your response must be a single JSON object, nothing else
9832
-
9833
- INVALID: \`\`\`json{"key":"value"}\`\`\` or "Here is: {"key":"value"}" or {"key":"value"}{"key":"value"}
9834
- VALID: {"key":"value"}` }) {
9835
- if (this.supportsSamplingTools()) {
9836
- return prompt && prompt.length > 0 ? prompt : "";
9837
- }
9838
- return [
9839
- prompt != null && prompt.length > 0 ? prompt : void 0,
9840
- prompt != null && prompt.length > 0 ? "" : void 0,
9841
- schemaPrefix,
9842
- schema != null ? JSON.stringify(createModelCompatibleJSONSchema(schema), null, 2) : void 0,
9843
- schemaSuffix
9844
- ].filter((line) => line != null).join("\n");
9845
- }
9846
- // Validate arguments using JSON schema
9847
- validateInput(args, schema) {
9848
- return validateSchema(args, schema);
9849
- }
9850
- };
9851
-
9852
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/sampling/agentic-sampling-executor.js
9853
- var SamplingExecutor = class extends BaseSamplingExecutor {
9854
- agenticExecutor;
9855
- constructor(name, description, allToolNames, toolNameToDetailList, server, config) {
9856
- super(name, description, allToolNames, toolNameToDetailList, server, config);
9857
- this.agenticExecutor = new AgenticExecutor(name, allToolNames, toolNameToDetailList, server);
9858
- }
9859
- buildDepGroups() {
9860
- const depGroups = {};
9861
- this.toolNameToDetailList.forEach(([toolName, tool2]) => {
9862
- if (tool2?.inputSchema) {
9863
- depGroups[toolName] = {
9864
- type: "object",
9865
- description: tool2.description || `Tool: ${toolName}`,
9866
- ...tool2.inputSchema
9867
- };
9868
- } else {
9869
- const toolSchema = this.server.getHiddenToolSchema(toolName);
9870
- if (toolSchema) {
9871
- depGroups[toolName] = {
9872
- ...toolSchema.schema,
9873
- description: toolSchema.description
9874
- };
9875
- }
9876
- }
9877
- });
9878
- return depGroups;
9879
- }
9880
- executeSampling(args, schema) {
9881
- const validationResult = validateSchema(args, schema);
9882
- if (!validationResult.valid) {
9883
8102
  return {
9884
8103
  content: [
9885
8104
  {
9886
8105
  type: "text",
9887
- text: CompiledPrompts.errorResponse({
9888
- errorMessage: validationResult.error || "Validation failed"
9889
- })
8106
+ text: `Unexpected error: ${error instanceof Error ? error.message : String(error)}`
9890
8107
  }
9891
8108
  ],
9892
8109
  isError: true
9893
8110
  };
9894
8111
  }
9895
- const createArgsDef = createArgsDefFactory(this.name, this.allToolNames, this.buildDepGroups(), void 0, void 0);
9896
- const agenticSchema = createArgsDef.forAgentic(this.toolNameToDetailList, true);
9897
- const systemPrompt = this.buildSystemPrompt(args.userRequest, agenticSchema, args.context && typeof args.context === "object" ? args.context : void 0);
9898
- return this.runSamplingLoop(() => systemPrompt, agenticSchema);
9899
8112
  }
9900
- async processAction(parsedData, schema, _state, parentSpan) {
9901
- const toolCallData = parsedData;
9902
- if (toolCallData.decision === "complete") {
9903
- return await this.createCompletionResult("Task completed", parentSpan);
8113
+ /**
8114
+ * Handle `man` command - return schemas for requested tools
8115
+ * @param requestedTools - Array of tool names (already validated via JSON Schema)
8116
+ */
8117
+ handleManCommand(requestedTools, executeSpan) {
8118
+ if (executeSpan) {
8119
+ executeSpan.setAttributes({
8120
+ toolType: "man",
8121
+ requestedTools: requestedTools.join(",")
8122
+ });
9904
8123
  }
9905
- try {
9906
- const { action: _action, decision: _decision, ..._toolArgs } = toolCallData;
9907
- const toolResult = await this.agenticExecutor.execute(toolCallData, schema, parentSpan);
9908
- const resultText = toolResult.content?.filter((content) => content.type === "text")?.map((content) => content.text)?.join("\n") || "No result";
9909
- this.conversationHistory.push({
9910
- role: "assistant",
9911
- content: {
8124
+ const schemas = requestedTools.map((toolName) => {
8125
+ const toolDetail = this.toolSchemaMap.get(toolName);
8126
+ if (toolDetail) {
8127
+ const cleanedSchema = cleanToolSchema(toolDetail);
8128
+ return `<tool_definition name="${toolName}">
8129
+ ${JSON.stringify(cleanedSchema, null, 2)}
8130
+ </tool_definition>`;
8131
+ }
8132
+ return null;
8133
+ }).filter(Boolean);
8134
+ if (executeSpan) {
8135
+ executeSpan.setAttributes({
8136
+ schemasReturned: schemas.length,
8137
+ success: true
8138
+ });
8139
+ endSpan(executeSpan);
8140
+ }
8141
+ return {
8142
+ content: [
8143
+ {
9912
8144
  type: "text",
9913
- text: resultText
8145
+ text: schemas.length > 0 ? schemas.join("\n\n") : "No schemas found for requested tools."
9914
8146
  }
9915
- });
9916
- return toolResult;
9917
- } catch (error) {
9918
- return this.createExecutionError(error, parentSpan);
9919
- }
9920
- }
9921
- buildSystemPrompt(userRequest, agenticSchema, context2) {
9922
- const toolList = this.allToolNames.map((name) => {
9923
- const tool2 = this.toolNameToDetailList.find(([toolName]) => toolName === name);
9924
- const toolSchema = this.server.getHiddenToolSchema(name);
9925
- if (tool2 && tool2[1]) {
9926
- return `- ${name}: ${tool2[1].description || `Tool: ${name}`}`;
9927
- } else if (toolSchema) {
9928
- return `- ${name}: ${toolSchema.description}`;
9929
- }
9930
- return `- ${name}`;
9931
- }).join("\n");
9932
- let contextInfo = "";
9933
- if (context2 && typeof context2 === "object" && Object.keys(context2).length > 0) {
9934
- contextInfo = `
9935
-
9936
- Context:
9937
- ${JSON.stringify(context2, null, 2)}`;
9938
- }
9939
- const basePrompt = this.supportsSamplingTools() ? CompiledPrompts.samplingExecutionTools({
9940
- toolName: this.name,
9941
- description: this.description,
9942
- toolList
9943
- }) : CompiledPrompts.samplingExecution({
9944
- toolName: this.name,
9945
- description: this.description,
9946
- toolList
9947
- });
9948
- const taskPrompt = `
9949
-
9950
- ## Current Task
9951
- You will now use agentic sampling to complete the following task: "${userRequest}"${contextInfo}
9952
-
9953
- When you need to use a tool, specify the tool name in 'useTool' and provide tool-specific parameters as additional properties.`;
9954
- return this.formatPromptForMode({
9955
- prompt: basePrompt + taskPrompt,
9956
- schema: agenticSchema
9957
- });
9958
- }
9959
- };
9960
-
9961
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/agentic/agentic-sampling-registrar.js
9962
- function registerAgenticSamplingTool(server, { description, name, allToolNames, depGroups, toolNameToDetailList, samplingConfig }) {
9963
- const createArgsDef = createArgsDefFactory(name, allToolNames, depGroups, void 0, void 0);
9964
- const samplingExecutor = new SamplingExecutor(name, description, allToolNames, toolNameToDetailList, server, samplingConfig);
9965
- const toolDescription = CompiledPrompts.samplingToolDescription({
9966
- description,
9967
- toolList: allToolNames.map((name2) => `- ${name2}`).join("\n")
9968
- });
9969
- const argsDef = createArgsDef.forSampling();
9970
- const schema = allToolNames.length > 0 ? argsDef : {
9971
- type: "object",
9972
- properties: {}
9973
- };
9974
- server.tool(name, toolDescription, jsonSchema(createModelCompatibleJSONSchema(schema)), async (args) => {
9975
- return await samplingExecutor.executeSampling(args, schema);
9976
- });
9977
- }
9978
-
9979
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/mode-agentic-sampling-plugin.js
9980
- var createAgenticSamplingModePlugin = () => ({
9981
- name: "mode-agentic-sampling",
9982
- version: "1.0.0",
9983
- // Only apply to agentic_sampling mode
9984
- apply: "agentic_sampling",
9985
- // Register the agent tool with sampling
9986
- registerAgentTool: (context2) => {
9987
- registerAgenticSamplingTool(context2.server, {
9988
- description: context2.description,
9989
- name: context2.name,
9990
- allToolNames: context2.allToolNames,
9991
- depGroups: context2.depGroups,
9992
- toolNameToDetailList: context2.toolNameToDetailList,
9993
- samplingConfig: context2.options.samplingConfig
9994
- });
9995
- }
9996
- });
9997
- var mode_agentic_sampling_plugin_default = createAgenticSamplingModePlugin();
9998
-
9999
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/sampling/workflow-sampling-executor.js
10000
- var WorkflowSamplingExecutor = class extends BaseSamplingExecutor {
10001
- createArgsDef;
10002
- predefinedSteps;
10003
- workflowExecutor;
10004
- constructor(name, description, allToolNames, toolNameToDetailList, createArgsDef, server, predefinedSteps, config) {
10005
- super(name, description, allToolNames, toolNameToDetailList, server, config), this.createArgsDef = createArgsDef, this.predefinedSteps = predefinedSteps;
10006
- this.workflowExecutor = new WorkflowExecutor(name, allToolNames, toolNameToDetailList, createArgsDef, server, predefinedSteps);
8147
+ ]
8148
+ };
10007
8149
  }
10008
- async executeWorkflowSampling(args, schema, state) {
10009
- const validationResult = validateSchema(args, schema);
10010
- if (!validationResult.valid) {
10011
- return {
10012
- content: [
10013
- {
10014
- type: "text",
10015
- text: CompiledPrompts.workflowErrorResponse({
10016
- errorMessage: validationResult.error || "Validation failed"
10017
- })
8150
+ /**
8151
+ * Execute a tool with runtime validation
8152
+ */
8153
+ async executeTool(tool2, toolArgs, executeSpan) {
8154
+ const externalTool = this.toolNameToDetailList.find(([name]) => name === tool2);
8155
+ if (externalTool) {
8156
+ const [, toolDetail] = externalTool;
8157
+ if (executeSpan) {
8158
+ executeSpan.setAttributes({
8159
+ toolType: "external",
8160
+ selectedTool: tool2
8161
+ });
8162
+ }
8163
+ if (toolDetail.inputSchema) {
8164
+ const rawSchema = extractJsonSchema(toolDetail.inputSchema);
8165
+ const validation = validateSchema(toolArgs, rawSchema);
8166
+ if (!validation.valid) {
8167
+ if (executeSpan) {
8168
+ executeSpan.setAttributes({
8169
+ validationError: true,
8170
+ errorMessage: validation.error
8171
+ });
8172
+ endSpan(executeSpan);
10018
8173
  }
10019
- ],
10020
- isError: true
10021
- };
8174
+ return {
8175
+ content: [
8176
+ {
8177
+ type: "text",
8178
+ text: `Parameter validation failed for "${tool2}": ${validation.error}`
8179
+ }
8180
+ ],
8181
+ isError: true
8182
+ };
8183
+ }
8184
+ }
8185
+ this.logger.debug({
8186
+ message: "Executing external tool",
8187
+ tool: tool2
8188
+ });
8189
+ const result = await toolDetail.execute(toolArgs);
8190
+ if (executeSpan) {
8191
+ executeSpan.setAttributes({
8192
+ success: true,
8193
+ isError: !!result.isError,
8194
+ resultContentLength: result.content?.length || 0
8195
+ });
8196
+ endSpan(executeSpan);
8197
+ }
8198
+ return result;
10022
8199
  }
10023
- return await this.runSamplingLoop(() => this.buildWorkflowSystemPrompt(args, state), schema, state);
10024
- }
10025
- async processAction(parsedData, _schema, state, parentSpan) {
10026
- const workflowState = state;
10027
- if (!workflowState) {
10028
- throw new Error("WorkflowState is required for workflow");
8200
+ if (this.allToolNames.includes(tool2)) {
8201
+ if (executeSpan) {
8202
+ executeSpan.setAttributes({
8203
+ toolType: "internal",
8204
+ selectedTool: tool2
8205
+ });
8206
+ }
8207
+ this.logger.debug({
8208
+ message: "Executing internal tool",
8209
+ tool: tool2
8210
+ });
8211
+ try {
8212
+ const result = await this.server.callTool(tool2, toolArgs);
8213
+ const callToolResult = result ?? {
8214
+ content: []
8215
+ };
8216
+ if (executeSpan) {
8217
+ executeSpan.setAttributes({
8218
+ success: true,
8219
+ isError: !!callToolResult.isError,
8220
+ resultContentLength: callToolResult.content?.length || 0
8221
+ });
8222
+ endSpan(executeSpan);
8223
+ }
8224
+ return callToolResult;
8225
+ } catch (error) {
8226
+ if (executeSpan) {
8227
+ endSpan(executeSpan, error);
8228
+ }
8229
+ this.logger.error({
8230
+ message: "Error executing internal tool",
8231
+ tool: tool2,
8232
+ error: String(error)
8233
+ });
8234
+ return {
8235
+ content: [
8236
+ {
8237
+ type: "text",
8238
+ text: `Error executing tool "${tool2}": ${error instanceof Error ? error.message : String(error)}`
8239
+ }
8240
+ ],
8241
+ isError: true
8242
+ };
8243
+ }
10029
8244
  }
10030
- const toolCallData = parsedData;
10031
- if (toolCallData.decision === "complete") {
10032
- return await this.createCompletionResult("Task completed", parentSpan);
8245
+ if (executeSpan) {
8246
+ executeSpan.setAttributes({
8247
+ toolType: "not_found",
8248
+ tool: tool2
8249
+ });
8250
+ endSpan(executeSpan);
10033
8251
  }
10034
- try {
10035
- const workflowResult = await this.workflowExecutor.execute(parsedData, workflowState);
10036
- const resultText = workflowResult.content?.filter((content) => content.type === "text")?.map((content) => content.text)?.join("\n") || "No result";
10037
- this.conversationHistory.push({
10038
- role: "assistant",
10039
- content: {
8252
+ return {
8253
+ content: [
8254
+ {
10040
8255
  type: "text",
10041
- text: resultText
8256
+ text: `Tool "${tool2}" not found. Available tools: ${this.allToolNames.join(", ")}`
10042
8257
  }
10043
- });
10044
- return workflowResult;
10045
- } catch (error) {
10046
- return this.createExecutionError(error, parentSpan);
10047
- }
10048
- }
10049
- buildWorkflowSystemPrompt(args, state) {
10050
- const workflowSchema = this.createArgsDef.forCurrentState(state);
10051
- const basePrompt = this.supportsSamplingTools() ? CompiledPrompts.samplingWorkflowExecutionTools({
10052
- toolName: this.name,
10053
- description: this.description,
10054
- workflowSchema: `${JSON.stringify(workflowSchema, null, 2)}`
10055
- }) : CompiledPrompts.samplingWorkflowExecution({
10056
- toolName: this.name,
10057
- description: this.description,
10058
- workflowSchema: `${JSON.stringify(workflowSchema, null, 2)}`
10059
- });
10060
- let contextInfo = "";
10061
- if (args.context && typeof args.context === "object" && Object.keys(args.context).length > 0) {
10062
- contextInfo = `
10063
-
10064
- Context:
10065
- ${JSON.stringify(args.context, null, 2)}`;
10066
- }
10067
- const workflowPrompt = `
10068
-
10069
- Current Task: <user_request>${args.userRequest}</user_request>${contextInfo}`;
10070
- return this.formatPromptForMode({
10071
- prompt: basePrompt + workflowPrompt,
10072
- schema: workflowSchema
10073
- });
8258
+ ],
8259
+ isError: true
8260
+ };
8261
+ }
8262
+ validate(args, schema) {
8263
+ return validateSchema(args, schema);
10074
8264
  }
10075
8265
  };
10076
8266
 
10077
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/workflow/workflow-sampling-registrar.js
10078
- function registerWorkflowSamplingTool(server, { description, name, allToolNames, depGroups, toolNameToDetailList, predefinedSteps, samplingConfig, ensureStepActions, toolNameToIdMapping: _toolNameToIdMapping }) {
10079
- const createArgsDef = createArgsDefFactory(name, allToolNames, depGroups, predefinedSteps, ensureStepActions);
10080
- const workflowSamplingExecutor = new WorkflowSamplingExecutor(name, description, allToolNames, toolNameToDetailList, createArgsDef, server, predefinedSteps, samplingConfig);
10081
- const workflowState = new WorkflowState();
10082
- const baseDescription = CompiledPrompts.samplingExecution({
8267
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/agentic/agentic-tool-registrar.js
8268
+ function registerAgenticTool(server, { description, name, allToolNames, depGroups, toolNameToDetailList }) {
8269
+ const createArgsDef = createArgsDefFactory(name, allToolNames, depGroups, void 0, void 0);
8270
+ const agenticExecutor = new AgenticExecutor(name, allToolNames, toolNameToDetailList, server);
8271
+ description = CompiledPrompts.autonomousExecution({
10083
8272
  toolName: name,
10084
- description,
10085
- toolList: allToolNames.map((name2) => `- ${name2}`).join("\n")
8273
+ description
10086
8274
  });
10087
- const argsDef = createArgsDef.forSampling();
8275
+ const agenticArgsDef = createArgsDef.forAgentic(allToolNames);
8276
+ const argsDef = agenticArgsDef;
10088
8277
  const schema = allToolNames.length > 0 ? argsDef : {
10089
8278
  type: "object",
10090
8279
  properties: {}
10091
8280
  };
10092
- server.tool(name, baseDescription, jsonSchema(createModelCompatibleJSONSchema(schema)), async (args) => {
10093
- try {
10094
- return await workflowSamplingExecutor.executeWorkflowSampling(args, schema, workflowState);
10095
- } catch (error) {
10096
- workflowState.reset();
10097
- return {
10098
- content: [
10099
- {
10100
- type: "text",
10101
- text: `Workflow execution error: ${error.message}`
10102
- }
10103
- ],
10104
- isError: true
10105
- };
10106
- }
8281
+ server.tool(name, description, jsonSchema(createModelCompatibleJSONSchema(schema)), async (args) => {
8282
+ return await agenticExecutor.execute(args, schema);
10107
8283
  });
10108
8284
  }
10109
8285
 
10110
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/mode-workflow-sampling-plugin.js
10111
- var createWorkflowSamplingModePlugin = () => ({
10112
- name: "mode-agentic-workflow-sampling",
10113
- version: "1.0.0",
10114
- // Only apply to agentic_workflow_sampling mode
10115
- apply: "agentic_workflow_sampling",
10116
- // Register the agent tool with sampling
8286
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/mode-agentic-plugin.js
8287
+ var createAgenticModePlugin = () => ({
8288
+ name: "mode-agentic",
8289
+ version: "2.0.0",
8290
+ // Only apply to agentic mode
8291
+ apply: "agentic",
8292
+ // Register the agent tool
10117
8293
  registerAgentTool: (context2) => {
10118
- registerWorkflowSamplingTool(context2.server, {
8294
+ registerAgenticTool(context2.server, {
10119
8295
  description: context2.description,
10120
8296
  name: context2.name,
10121
8297
  allToolNames: context2.allToolNames,
10122
8298
  depGroups: context2.depGroups,
10123
- toolNameToDetailList: context2.toolNameToDetailList,
10124
- predefinedSteps: context2.options.steps,
10125
- samplingConfig: context2.options.samplingConfig,
10126
- ensureStepActions: context2.options.ensureStepActions,
10127
- toolNameToIdMapping: context2.toolNameToIdMapping
8299
+ toolNameToDetailList: context2.toolNameToDetailList
10128
8300
  });
10129
8301
  }
10130
8302
  });
10131
- var mode_workflow_sampling_plugin_default = createWorkflowSamplingModePlugin();
8303
+ var mode_agentic_plugin_default = createAgenticModePlugin();
10132
8304
 
10133
8305
  // __mcpc__cli_latest/node_modules/@jsr/mcpc__mcp-sampling-ai-provider/src/utils.js
10134
8306
  function convertAISDKToMCPMessages(prompt) {
@@ -10185,6 +8357,7 @@ function convertMCPStopReasonToAISDK(stopReason) {
10185
8357
  }
10186
8358
 
10187
8359
  // __mcpc__cli_latest/node_modules/@jsr/mcpc__mcp-sampling-ai-provider/src/language-model.js
8360
+ var DEFAULT_MAX_TOKENS = 128e3;
10188
8361
  var MCPSamplingLanguageModel = class {
10189
8362
  specificationVersion = "v2";
10190
8363
  provider;
@@ -10192,11 +8365,13 @@ var MCPSamplingLanguageModel = class {
10192
8365
  supportedUrls = {};
10193
8366
  server;
10194
8367
  modelPreferences;
8368
+ maxTokens;
10195
8369
  constructor(config) {
10196
8370
  this.server = config.server;
10197
8371
  this.modelId = "";
10198
8372
  this.provider = "mcp-client";
10199
8373
  this.modelPreferences = config.modelPreferences;
8374
+ this.maxTokens = config.maxTokens ?? DEFAULT_MAX_TOKENS;
10200
8375
  }
10201
8376
  /**
10202
8377
  * Generate a response using MCP's createMessage capability
@@ -10228,7 +8403,7 @@ var MCPSamplingLanguageModel = class {
10228
8403
  const createMessageParams = {
10229
8404
  systemPrompt,
10230
8405
  messages,
10231
- maxTokens: options.maxOutputTokens ?? 55e3,
8406
+ maxTokens: options.maxOutputTokens ?? this.maxTokens,
10232
8407
  modelPreferences: this.modelPreferences
10233
8408
  };
10234
8409
  if (useNativeTools && options.tools && options.tools.length > 0) {
@@ -10606,7 +8781,8 @@ var MCPSamplingProvider = class {
10606
8781
  languageModel(options) {
10607
8782
  return new MCPSamplingLanguageModel({
10608
8783
  server: this.config.server,
10609
- modelPreferences: options?.modelPreferences
8784
+ modelPreferences: options?.modelPreferences,
8785
+ maxTokens: this.config.maxTokens
10610
8786
  });
10611
8787
  }
10612
8788
  /**
@@ -10667,7 +8843,7 @@ var BaseAIExecutor = class {
10667
8843
  messages: [
10668
8844
  {
10669
8845
  role: "user",
10670
- content: args.userRequest
8846
+ content: args.prompt
10671
8847
  }
10672
8848
  ],
10673
8849
  tools: this.buildTools(),
@@ -10712,19 +8888,12 @@ var BaseAIExecutor = class {
10712
8888
  }
10713
8889
  }
10714
8890
  buildSystemPrompt(args) {
10715
- return `Agent \`${this.config.name}\` that completes tasks by calling tools.
10716
-
10717
- <manual>
10718
- ${this.config.description}
10719
- </manual>
10720
-
10721
- <rules>
10722
- ${this.getRules()}
10723
- </rules>
10724
-
10725
- <tools>
10726
- ${this.getToolListDescription()}
10727
- </tools>${args.context ? this.formatContext(args.context) : ""}`;
8891
+ return CompiledPrompts.aiLoopSystem({
8892
+ toolName: this.config.name,
8893
+ description: this.config.description,
8894
+ rules: this.getRules(),
8895
+ context: this.formatContext(args.context)
8896
+ });
10728
8897
  }
10729
8898
  getRules() {
10730
8899
  return `1. Use tools to complete the user's request
@@ -10733,10 +8902,10 @@ ${this.getToolListDescription()}
10733
8902
  4. Continue until task is complete
10734
8903
  5. When complete, provide a summary WITHOUT calling more tools`;
10735
8904
  }
10736
- getToolListDescription() {
10737
- return "Tools will be provided by AI SDK";
10738
- }
10739
8905
  formatContext(context2) {
8906
+ if (!context2 || Object.keys(context2).length === 0) {
8907
+ return "";
8908
+ }
10740
8909
  return `
10741
8910
 
10742
8911
  <context>
@@ -10744,11 +8913,12 @@ ${JSON.stringify(context2, null, 2)}
10744
8913
  </context>`;
10745
8914
  }
10746
8915
  convertToAISDKTool(name, toolDetail, execute) {
8916
+ const cleanedSchema = toolDetail.inputSchema ? cleanToolSchema(toolDetail.inputSchema) : {
8917
+ type: "object"
8918
+ };
10747
8919
  return (0, import_ai.tool)({
10748
8920
  description: toolDetail.description || `Tool: ${name}`,
10749
- inputSchema: (0, import_ai.jsonSchema)(toolDetail.inputSchema || {
10750
- type: "object"
10751
- }),
8921
+ inputSchema: (0, import_ai.jsonSchema)(cleanedSchema),
10752
8922
  execute
10753
8923
  });
10754
8924
  }
@@ -10759,17 +8929,20 @@ var AISamplingExecutor = class extends BaseAIExecutor {
10759
8929
  server;
10760
8930
  tools;
10761
8931
  providerOptions;
8932
+ maxTokens;
10762
8933
  model = null;
10763
8934
  constructor(config) {
10764
8935
  super(config, "callTool" in config.server ? config.server : void 0);
10765
8936
  this.server = config.server;
10766
8937
  this.tools = config.tools;
10767
8938
  this.providerOptions = config.providerOptions;
8939
+ this.maxTokens = config.maxTokens;
10768
8940
  }
10769
8941
  initProvider() {
10770
8942
  if (!this.model) {
10771
8943
  const provider = new MCPSamplingProvider({
10772
- server: this.server
8944
+ server: this.server,
8945
+ maxTokens: this.maxTokens
10773
8946
  });
10774
8947
  this.model = provider.languageModel(this.providerOptions);
10775
8948
  }
@@ -10782,9 +8955,6 @@ var AISamplingExecutor = class extends BaseAIExecutor {
10782
8955
  getExecutorType() {
10783
8956
  return "mcp";
10784
8957
  }
10785
- getToolListDescription() {
10786
- return this.tools.map(([name, detail]) => `- ${name}: ${detail.description || "No description"}`).join("\n");
10787
- }
10788
8958
  buildTools() {
10789
8959
  const aiTools = {};
10790
8960
  for (const [name, detail] of this.tools) {
@@ -10815,7 +8985,7 @@ var AISamplingExecutor = class extends BaseAIExecutor {
10815
8985
 
10816
8986
  // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/ai/ai-sampling-registrar.js
10817
8987
  function registerAISamplingTool(server, params) {
10818
- const { name, description, allToolNames, depGroups, toolNameToDetailList, providerOptions, maxSteps = 50, tracingEnabled = false } = params;
8988
+ const { name, description, allToolNames, depGroups, toolNameToDetailList, providerOptions, maxSteps = 50, tracingEnabled = false, maxTokens } = params;
10819
8989
  const createArgsDef = createArgsDefFactory(name, allToolNames, depGroups, void 0, void 0);
10820
8990
  const executor = new AISamplingExecutor({
10821
8991
  name,
@@ -10824,7 +8994,8 @@ function registerAISamplingTool(server, params) {
10824
8994
  tools: toolNameToDetailList,
10825
8995
  providerOptions,
10826
8996
  maxSteps,
10827
- tracingEnabled
8997
+ tracingEnabled,
8998
+ maxTokens
10828
8999
  });
10829
9000
  const toolDescription = CompiledPrompts.samplingToolDescription({
10830
9001
  toolName: name,
@@ -10837,9 +9008,23 @@ function registerAISamplingTool(server, params) {
10837
9008
  properties: {}
10838
9009
  };
10839
9010
  server.tool(name, toolDescription, jsonSchema(createModelCompatibleJSONSchema(schema)), (args) => {
10840
- const userRequest = typeof args.userRequest === "string" ? args.userRequest : JSON.stringify(args);
9011
+ const validationResult = validateSchema(args, schema);
9012
+ if (!validationResult.valid) {
9013
+ return {
9014
+ content: [
9015
+ {
9016
+ type: "text",
9017
+ text: CompiledPrompts.errorResponse({
9018
+ errorMessage: validationResult.error || "Validation failed"
9019
+ })
9020
+ }
9021
+ ],
9022
+ isError: true
9023
+ };
9024
+ }
9025
+ const prompt = typeof args.prompt === "string" ? args.prompt : JSON.stringify(args);
10841
9026
  return executor.execute({
10842
- userRequest,
9027
+ prompt,
10843
9028
  context: args.context
10844
9029
  });
10845
9030
  });
@@ -10860,7 +9045,8 @@ var createAISamplingModePlugin = () => ({
10860
9045
  toolNameToDetailList: context2.toolNameToDetailList,
10861
9046
  providerOptions: opts.providerOptions,
10862
9047
  maxSteps: opts.maxSteps,
10863
- tracingEnabled: opts.tracingEnabled
9048
+ tracingEnabled: opts.tracingEnabled,
9049
+ maxTokens: opts.maxTokens
10864
9050
  });
10865
9051
  }
10866
9052
  });
@@ -10892,12 +9078,6 @@ var AIACPExecutor = class extends BaseAIExecutor {
10892
9078
  getExecutorType() {
10893
9079
  return "acp";
10894
9080
  }
10895
- getToolListDescription() {
10896
- if (this.tools.length === 0) {
10897
- return "Tools will be provided by ACP agent";
10898
- }
10899
- return this.tools.map(([name, detail]) => `- ${name}: ${detail.description || "No description"}`).join("\n");
10900
- }
10901
9081
  buildTools() {
10902
9082
  const aiTools = {};
10903
9083
  for (const [name, detail] of this.tools) {
@@ -10949,9 +9129,23 @@ function registerAIACPTool(server, params) {
10949
9129
  properties: {}
10950
9130
  };
10951
9131
  server.tool(name, toolDescription, jsonSchema(createModelCompatibleJSONSchema(schema)), (args) => {
10952
- const userRequest = typeof args.userRequest === "string" ? args.userRequest : JSON.stringify(args);
9132
+ const validationResult = validateSchema(args, schema);
9133
+ if (!validationResult.valid) {
9134
+ return {
9135
+ content: [
9136
+ {
9137
+ type: "text",
9138
+ text: CompiledPrompts.errorResponse({
9139
+ errorMessage: validationResult.error || "Validation failed"
9140
+ })
9141
+ }
9142
+ ],
9143
+ isError: true
9144
+ };
9145
+ }
9146
+ const prompt = typeof args.prompt === "string" ? args.prompt : JSON.stringify(args);
10953
9147
  return executor.execute({
10954
- userRequest,
9148
+ prompt,
10955
9149
  context: args.context
10956
9150
  });
10957
9151
  });
@@ -10988,9 +9182,6 @@ function getBuiltInPlugins() {
10988
9182
  tool_name_mapping_plugin_default,
10989
9183
  config_plugin_default,
10990
9184
  mode_agentic_plugin_default,
10991
- mode_workflow_plugin_default,
10992
- mode_agentic_sampling_plugin_default,
10993
- mode_workflow_sampling_plugin_default,
10994
9185
  mode_ai_sampling_plugin_default,
10995
9186
  mode_ai_acp_plugin_default,
10996
9187
  logging_plugin_default
@@ -11399,7 +9590,7 @@ var ToolManager = class {
11399
9590
  description,
11400
9591
  schema
11401
9592
  });
11402
- if (options.internal) {
9593
+ if (options.hidden) {
11403
9594
  this.toolConfigs.set(name, {
11404
9595
  visibility: {
11405
9596
  hidden: true
@@ -11419,6 +9610,11 @@ var ToolManager = class {
11419
9610
  inputSchema: schema
11420
9611
  });
11421
9612
  }
9613
+ this.toolConfigs.set(name, {
9614
+ visibility: {
9615
+ public: true
9616
+ }
9617
+ });
11422
9618
  }
11423
9619
  /**
11424
9620
  * Check if a tool is public (exposed to MCP clients)
@@ -11968,14 +10164,6 @@ var ComposableMCPServer = class extends Server {
11968
10164
  if (!this.toolNameMapping.has(internalName)) {
11969
10165
  this.toolManager.setToolNameMapping(internalName, toolId);
11970
10166
  }
11971
- const matchingStep = options.steps?.find((step) => step.actions.includes(toolNameWithScope));
11972
- if (matchingStep) {
11973
- const actionIndex = matchingStep.actions.indexOf(toolNameWithScope);
11974
- if (actionIndex !== -1) {
11975
- matchingStep.actions[actionIndex] = toolId;
11976
- }
11977
- return true;
11978
- }
11979
10167
  return tagToResults.tool.find((tool2) => {
11980
10168
  const selectAll = tool2.attribs.name === `${mcpName}.${ALL_TOOLS_PLACEHOLDER2}` || tool2.attribs.name === `${mcpName}`;
11981
10169
  if (selectAll) {
@@ -12035,11 +10223,11 @@ var ComposableMCPServer = class extends Server {
12035
10223
  const toolNameToDetailList = Object.entries(allTools);
12036
10224
  const publicToolNames = this.getPublicToolNames();
12037
10225
  const hiddenToolNames = this.getHiddenToolNames();
12038
- const contextToolNames = toolNameToDetailList.map(([name2]) => name2).filter((n) => !hiddenToolNames.includes(n));
10226
+ const contextToolNames = toolNameToDetailList.map(([name2]) => name2).filter((n) => !hiddenToolNames.includes(n) && !publicToolNames.includes(n));
12039
10227
  publicToolNames.forEach((toolId) => {
12040
10228
  const tool2 = allTools[toolId];
12041
10229
  if (!tool2) {
12042
- throw new Error(`Public tool ${toolId} not found in registry, available: ${Object.keys(allTools).join(", ")}`);
10230
+ return;
12043
10231
  }
12044
10232
  this.tool(toolId, tool2.description || "", jsonSchema(tool2.inputSchema), tool2.execute, {
12045
10233
  internal: false
@@ -12094,12 +10282,12 @@ var ComposableMCPServer = class extends Server {
12094
10282
  };
12095
10283
 
12096
10284
  // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/env.js
12097
- var import_node_process9 = __toESM(require("node:process"), 1);
12098
- var isSCF = () => Boolean(import_node_process9.default.env.SCF_RUNTIME || import_node_process9.default.env.PROD_SCF);
10285
+ var import_node_process8 = __toESM(require("node:process"), 1);
10286
+ var isSCF = () => Boolean(import_node_process8.default.env.SCF_RUNTIME || import_node_process8.default.env.PROD_SCF);
12099
10287
  if (isSCF()) {
12100
10288
  console.log({
12101
10289
  isSCF: isSCF(),
12102
- SCF_RUNTIME: import_node_process9.default.env.SCF_RUNTIME
10290
+ SCF_RUNTIME: import_node_process8.default.env.SCF_RUNTIME
12103
10291
  });
12104
10292
  }
12105
10293
 
@@ -12148,15 +10336,13 @@ function createSearchPlugin(options = {}) {
12148
10336
  const timeoutMs = options.timeoutMs || 3e4;
12149
10337
  const global2 = options.global ?? true;
12150
10338
  const agentName = options.agentName;
12151
- const toolName = agentName ? `${agentName}__search-tool-result` : "search-tool-result";
10339
+ const toolName = agentName ? `${agentName}__grep` : "mcpc__grep";
12152
10340
  const activeTimeouts = /* @__PURE__ */ new Set();
12153
10341
  return {
12154
10342
  name: "plugin-search",
12155
10343
  version: "1.0.0",
12156
10344
  configureServer: (server) => {
12157
- const defaultDescription = agentName ? `Search for text patterns in files for the "${agentName}" agent. Use this to find specific content within large tool results. Provide a simple literal string or a regular expression.
12158
- Only search within the allowed directory: ${allowedSearchDir}` : `Search for text patterns in files and directories. Use this to find specific content, code, or information within files. Provide a simple literal string or a regular expression. If your pattern is a regex, ensure it's valid; otherwise use quotes or escape special characters to treat it as a literal string.
12159
- Only search within the allowed directory: ${allowedSearchDir}`;
10345
+ const defaultDescription = agentName ? `Grep/search for text patterns within large tool result files for the "${agentName}" agent. **IMPORTANT**: You MUST execute the actual tool first and get a "Result too large, saved to file" response before using this grep tool. This tool searches within previously saved large results only. Provide a simple literal string or a regular expression. Only search within the allowed directory: ${allowedSearchDir}` : `Grep/search for text patterns within large tool result files. **IMPORTANT**: You MUST execute the actual tool first and get a "Result too large, saved to file" response before using this grep tool. This tool searches within previously saved large results only. Provide a simple literal string or a regular expression. If your pattern is a regex, ensure it's valid. Only search within the allowed directory: ${allowedSearchDir}`;
12160
10346
  const toolDescription = options.toolDescription || defaultDescription;
12161
10347
  server.tool(toolName, toolDescription, jsonSchema({
12162
10348
  type: "object",
@@ -12375,7 +10561,7 @@ function createLargeResultPlugin(options = {}) {
12375
10561
  let tempDir = options.tempDir || null;
12376
10562
  let serverRef = null;
12377
10563
  let agentName = null;
12378
- const defaultSearchDescription = `Search within large tool result files that were saved due to size limits. Use when: a tool result was saved to file because it exceeded the context limit. Do NOT use this tool before calling the actual tool first. Provide specific keywords or patterns related to the content you're looking for.`;
10564
+ const defaultSearchDescription = `Grep/search within large tool result files that were saved due to size limits. **IMPORTANT**: You MUST execute the actual tool first and get a "Result too large, saved to file" response before using this grep tool. This tool is ONLY for searching within previously saved large results, not for general file search. Provide specific keywords or regex patterns related to the content you're looking for.`;
12379
10565
  return {
12380
10566
  name: "plugin-large-result-handler",
12381
10567
  version: "1.0.0",
@@ -12390,7 +10576,7 @@ function createLargeResultPlugin(options = {}) {
12390
10576
  maxResults: options.search?.maxResults || 15,
12391
10577
  maxOutputSize: options.search?.maxOutputSize || 4e3,
12392
10578
  toolDescription: options.search?.toolDescription || defaultSearchDescription,
12393
- global: true,
10579
+ global: false,
12394
10580
  agentName
12395
10581
  };
12396
10582
  const searchPlugin = createSearchPlugin(searchConfig);
@@ -12399,7 +10585,7 @@ function createLargeResultPlugin(options = {}) {
12399
10585
  },
12400
10586
  transformTool: (tool2, context2) => {
12401
10587
  const originalExecute = tool2.execute;
12402
- const searchToolName = agentName ? `${agentName}__search-tool-result` : "search-tool-result";
10588
+ const searchToolName = agentName ? `${agentName}__grep` : "mcpc__grep";
12403
10589
  tool2.execute = async (args) => {
12404
10590
  try {
12405
10591
  const result = await originalExecute(args);