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