@mcpc-tech/cli 0.1.23 → 0.1.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/bin/mcpc.cjs +3195 -65
  2. package/bin/mcpc.mjs +3195 -65
  3. package/package.json +3 -1
package/bin/mcpc.mjs CHANGED
@@ -510,7 +510,7 @@ var require_cross_spawn = __commonJS({
510
510
  var cp = __require("child_process");
511
511
  var parse = require_parse();
512
512
  var enoent = require_enoent();
513
- function spawn2(command, args, options) {
513
+ function spawn3(command, args, options) {
514
514
  const parsed = parse(command, args, options);
515
515
  const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
516
516
  enoent.hookChildProcess(spawned, parsed);
@@ -522,8 +522,8 @@ var require_cross_spawn = __commonJS({
522
522
  result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
523
523
  return result;
524
524
  }
525
- module.exports = spawn2;
526
- module.exports.spawn = spawn2;
525
+ module.exports = spawn3;
526
+ module.exports.spawn = spawn3;
527
527
  module.exports.sync = spawnSync;
528
528
  module.exports._parse = parse;
529
529
  module.exports._enoent = enoent;
@@ -5169,17 +5169,17 @@ var Client = class extends Protocol {
5169
5169
  this._cachedToolOutputValidators.clear();
5170
5170
  this._cachedKnownTaskTools.clear();
5171
5171
  this._cachedRequiredTaskTools.clear();
5172
- for (const tool of tools) {
5173
- if (tool.outputSchema) {
5174
- const toolValidator = this._jsonSchemaValidator.getValidator(tool.outputSchema);
5175
- this._cachedToolOutputValidators.set(tool.name, toolValidator);
5172
+ for (const tool3 of tools) {
5173
+ if (tool3.outputSchema) {
5174
+ const toolValidator = this._jsonSchemaValidator.getValidator(tool3.outputSchema);
5175
+ this._cachedToolOutputValidators.set(tool3.name, toolValidator);
5176
5176
  }
5177
- const taskSupport = tool.execution?.taskSupport;
5177
+ const taskSupport = tool3.execution?.taskSupport;
5178
5178
  if (taskSupport === "required" || taskSupport === "optional") {
5179
- this._cachedKnownTaskTools.add(tool.name);
5179
+ this._cachedKnownTaskTools.add(tool3.name);
5180
5180
  }
5181
5181
  if (taskSupport === "required") {
5182
- this._cachedRequiredTaskTools.add(tool.name);
5182
+ this._cachedRequiredTaskTools.add(tool3.name);
5183
5183
  }
5184
5184
  }
5185
5185
  }
@@ -7476,14 +7476,14 @@ async function composeMcpDepTools(mcpConfig, filterIn) {
7476
7476
  acquiredKeys.push(defKey);
7477
7477
  allClients[serverId] = client;
7478
7478
  const { tools } = await client.listTools();
7479
- tools.forEach((tool) => {
7480
- const toolNameWithScope = `${name}.${tool.name}`;
7481
- const internalToolName = tool.name;
7479
+ tools.forEach((tool3) => {
7480
+ const toolNameWithScope = `${name}.${tool3.name}`;
7481
+ const internalToolName = tool3.name;
7482
7482
  const rawToolId = `${serverId}_${internalToolName}`;
7483
7483
  const toolId = sanitizePropertyKey(rawToolId);
7484
7484
  if (filterIn && !filterIn({
7485
7485
  action: internalToolName,
7486
- tool,
7486
+ tool: tool3,
7487
7487
  mcpName: name,
7488
7488
  toolNameWithScope,
7489
7489
  internalToolName,
@@ -7498,7 +7498,7 @@ async function composeMcpDepTools(mcpConfig, filterIn) {
7498
7498
  timeout: def.toolCallTimeout
7499
7499
  });
7500
7500
  allTools[toolId] = {
7501
- ...tool,
7501
+ ...tool3,
7502
7502
  execute,
7503
7503
  _originalName: toolNameWithScope
7504
7504
  };
@@ -7561,13 +7561,13 @@ var createConfigPlugin = () => ({
7561
7561
  name: "built-in-config",
7562
7562
  version: "1.0.0",
7563
7563
  enforce: "pre",
7564
- transformTool: (tool, context2) => {
7564
+ transformTool: (tool3, context2) => {
7565
7565
  const server = context2.server;
7566
7566
  const config = server.findToolConfig?.(context2.toolName);
7567
7567
  if (config?.description) {
7568
- tool.description = config.description;
7568
+ tool3.description = config.description;
7569
7569
  }
7570
- return tool;
7570
+ return tool3;
7571
7571
  }
7572
7572
  });
7573
7573
  var config_plugin_default = createConfigPlugin();
@@ -7577,10 +7577,10 @@ var createToolNameMappingPlugin = () => ({
7577
7577
  name: "built-in-tool-name-mapping",
7578
7578
  version: "1.0.0",
7579
7579
  enforce: "pre",
7580
- transformTool: (tool, context2) => {
7580
+ transformTool: (tool3, context2) => {
7581
7581
  const server = context2.server;
7582
7582
  const toolName = context2.toolName;
7583
- const originalName = tool._originalName || toolName;
7583
+ const originalName = tool3._originalName || toolName;
7584
7584
  const dotNotation = originalName.replace(/_/g, ".");
7585
7585
  const underscoreNotation = originalName.replace(/\./g, "_");
7586
7586
  if (dotNotation !== originalName && server.toolNameMapping) {
@@ -7592,7 +7592,7 @@ var createToolNameMappingPlugin = () => ({
7592
7592
  if (originalName !== toolName && server.toolNameMapping) {
7593
7593
  server.toolNameMapping.set(originalName, toolName);
7594
7594
  }
7595
- return tool;
7595
+ return tool3;
7596
7596
  }
7597
7597
  });
7598
7598
  var tool_name_mapping_plugin_default = createToolNameMappingPlugin();
@@ -8085,13 +8085,13 @@ var PromptUtils = {
8085
8085
  * Generate tool list for descriptions
8086
8086
  */
8087
8087
  generateToolList: (tools) => {
8088
- return tools.filter((tool) => !tool.hide).map((tool) => `<tool name="${tool.name}"${tool.description ? ` description="${tool.description}"` : ""}/>`).join("\n");
8088
+ return tools.filter((tool3) => !tool3.hide).map((tool3) => `<tool name="${tool3.name}"${tool3.description ? ` description="${tool3.description}"` : ""}/>`).join("\n");
8089
8089
  },
8090
8090
  /**
8091
8091
  * Generate hidden tool list for descriptions
8092
8092
  */
8093
8093
  generateHiddenToolList: (tools) => {
8094
- return tools.filter((tool) => tool.hide).map((tool) => `<tool name="${tool.name}" hide/>`).join("\n");
8094
+ return tools.filter((tool3) => tool3.hide).map((tool3) => `<tool name="${tool3.name}" hide/>`).join("\n");
8095
8095
  },
8096
8096
  /**
8097
8097
  * Format workflow steps for display
@@ -9876,12 +9876,12 @@ var SamplingExecutor = class extends BaseSamplingExecutor {
9876
9876
  }
9877
9877
  buildDepGroups() {
9878
9878
  const depGroups = {};
9879
- this.toolNameToDetailList.forEach(([toolName, tool]) => {
9880
- if (tool?.inputSchema) {
9879
+ this.toolNameToDetailList.forEach(([toolName, tool3]) => {
9880
+ if (tool3?.inputSchema) {
9881
9881
  depGroups[toolName] = {
9882
9882
  type: "object",
9883
- description: tool.description || `Tool: ${toolName}`,
9884
- ...tool.inputSchema
9883
+ description: tool3.description || `Tool: ${toolName}`,
9884
+ ...tool3.inputSchema
9885
9885
  };
9886
9886
  } else {
9887
9887
  const toolSchema = this.server.getHiddenToolSchema(toolName);
@@ -9938,10 +9938,10 @@ var SamplingExecutor = class extends BaseSamplingExecutor {
9938
9938
  }
9939
9939
  buildSystemPrompt(userRequest, agenticSchema, context2) {
9940
9940
  const toolList = this.allToolNames.map((name) => {
9941
- const tool = this.toolNameToDetailList.find(([toolName]) => toolName === name);
9941
+ const tool3 = this.toolNameToDetailList.find(([toolName]) => toolName === name);
9942
9942
  const toolSchema = this.server.getHiddenToolSchema(name);
9943
- if (tool && tool[1]) {
9944
- return `- ${name}: ${tool[1].description || `Tool: ${name}`}`;
9943
+ if (tool3 && tool3[1]) {
9944
+ return `- ${name}: ${tool3[1].description || `Tool: ${name}`}`;
9945
9945
  } else if (toolSchema) {
9946
9946
  return `- ${name}: ${toolSchema.description}`;
9947
9947
  }
@@ -10148,6 +10148,3134 @@ var createWorkflowSamplingModePlugin = () => ({
10148
10148
  });
10149
10149
  var mode_workflow_sampling_plugin_default = createWorkflowSamplingModePlugin();
10150
10150
 
10151
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__mcp-sampling-ai-provider/src/utils.js
10152
+ function convertAISDKToMCPMessages(prompt) {
10153
+ const messages = [];
10154
+ for (const msg of prompt) {
10155
+ if (msg.role === "system") continue;
10156
+ const role = msg.role === "assistant" ? "assistant" : "user";
10157
+ const textParts = msg.content.filter((c) => c.type === "text");
10158
+ const toolCalls = msg.content.filter((c) => c.type === "tool-call");
10159
+ const toolResults = msg.content.filter((c) => c.type === "tool-result");
10160
+ const parts = [];
10161
+ if (textParts.length > 0) {
10162
+ parts.push(textParts.map((c) => c.text).join("\n"));
10163
+ }
10164
+ if (toolCalls.length > 0) {
10165
+ const calls = toolCalls.map((c) => {
10166
+ const call = c;
10167
+ return `<use_tool tool="${call.toolName}">
10168
+ ${JSON.stringify(call.input || {})}
10169
+ </use_tool>`;
10170
+ });
10171
+ parts.push(calls.join("\n"));
10172
+ }
10173
+ if (toolResults.length > 0) {
10174
+ const results = toolResults.map((c) => {
10175
+ const result = c;
10176
+ const output = JSON.stringify(result.output || result.result || "undefined");
10177
+ return `Tool "${result.toolName}" result:
10178
+ ${output}`;
10179
+ });
10180
+ parts.push(results.join("\n\n"));
10181
+ }
10182
+ const text = parts.join("\n\n");
10183
+ if (text) {
10184
+ messages.push({
10185
+ role,
10186
+ content: {
10187
+ type: "text",
10188
+ text
10189
+ }
10190
+ });
10191
+ }
10192
+ }
10193
+ return messages;
10194
+ }
10195
+ function convertMCPStopReasonToAISDK(stopReason) {
10196
+ if (stopReason === "endTurn" || stopReason === "stopSequence") {
10197
+ return "stop";
10198
+ }
10199
+ if (stopReason === "maxTokens") return "length";
10200
+ return stopReason ?? "unknown";
10201
+ }
10202
+
10203
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__mcp-sampling-ai-provider/src/language-model.js
10204
+ var MCPSamplingLanguageModel = class {
10205
+ specificationVersion = "v2";
10206
+ provider;
10207
+ modelId;
10208
+ supportedUrls = {};
10209
+ server;
10210
+ modelPreferences;
10211
+ constructor(config) {
10212
+ this.server = config.server;
10213
+ this.modelId = "";
10214
+ this.provider = "mcp-client";
10215
+ this.modelPreferences = config.modelPreferences;
10216
+ }
10217
+ /**
10218
+ * Generate a response using MCP's createMessage capability
10219
+ */
10220
+ async doGenerate(options) {
10221
+ const messages = this.convertMessages(options.prompt);
10222
+ let systemPrompt;
10223
+ for (const msg of options.prompt) {
10224
+ if (msg.role === "system") {
10225
+ systemPrompt = msg.content;
10226
+ break;
10227
+ }
10228
+ }
10229
+ const useNativeTools = this.supportsSamplingTools();
10230
+ systemPrompt = this.injectResponseFormatInstructions(systemPrompt, options.responseFormat, useNativeTools);
10231
+ systemPrompt = this.injectToolInstructions(systemPrompt, options.tools, useNativeTools);
10232
+ const createMessageParams = {
10233
+ systemPrompt,
10234
+ messages,
10235
+ maxTokens: options.maxOutputTokens ?? 55e3,
10236
+ modelPreferences: this.modelPreferences
10237
+ };
10238
+ if (useNativeTools && options.tools && options.tools.length > 0) {
10239
+ createMessageParams.tools = this.convertAISDKToolsToMCP(options.tools);
10240
+ createMessageParams.toolChoice = {
10241
+ mode: "auto"
10242
+ };
10243
+ }
10244
+ const result = await this.server.createMessage(createMessageParams);
10245
+ const content = [];
10246
+ if (useNativeTools) {
10247
+ const contentArray = Array.isArray(result.content) ? result.content : [
10248
+ result.content
10249
+ ];
10250
+ for (const block of contentArray) {
10251
+ if (block.type === "text" && "text" in block) {
10252
+ content.push({
10253
+ type: "text",
10254
+ text: block.text
10255
+ });
10256
+ } else if (block.type === "tool_use" && "id" in block && "name" in block) {
10257
+ const toolInput = block.input || {};
10258
+ content.push({
10259
+ type: "tool-call",
10260
+ toolCallId: block.id,
10261
+ toolName: block.name,
10262
+ input: JSON.stringify(toolInput)
10263
+ });
10264
+ }
10265
+ }
10266
+ } else {
10267
+ if (result.content.type === "text" && result.content.text) {
10268
+ const { text, toolCalls } = this.extractToolCalls(result.content.text, options.tools);
10269
+ if (text.trim()) {
10270
+ const textContent = {
10271
+ type: "text",
10272
+ text
10273
+ };
10274
+ content.push(textContent);
10275
+ }
10276
+ content.push(...toolCalls);
10277
+ }
10278
+ }
10279
+ const finishReason = this.mapStopReason(result.stopReason);
10280
+ return {
10281
+ content,
10282
+ finishReason,
10283
+ usage: {
10284
+ inputTokens: void 0,
10285
+ outputTokens: void 0,
10286
+ totalTokens: 0
10287
+ },
10288
+ request: {
10289
+ body: JSON.stringify({
10290
+ systemPrompt,
10291
+ messages
10292
+ })
10293
+ },
10294
+ response: {
10295
+ modelId: result.model
10296
+ },
10297
+ warnings: []
10298
+ };
10299
+ }
10300
+ /**
10301
+ * Stream a response using MCP's createMessage capability
10302
+ *
10303
+ * Since MCP doesn't support native streaming, we generate the full response
10304
+ * and emit it as stream events following AI SDK's protocol.
10305
+ */
10306
+ async doStream(options) {
10307
+ const result = await this.doGenerate(options);
10308
+ const stream = new ReadableStream({
10309
+ start(controller) {
10310
+ if (result.response?.modelId) {
10311
+ controller.enqueue({
10312
+ type: "response-metadata",
10313
+ modelId: result.response.modelId,
10314
+ ...result.response.headers && {
10315
+ headers: result.response.headers
10316
+ }
10317
+ });
10318
+ }
10319
+ let textIndex = 0;
10320
+ for (const part of result.content) {
10321
+ if (part.type === "text") {
10322
+ const id = `text-${++textIndex}`;
10323
+ controller.enqueue({
10324
+ type: "text-start",
10325
+ id
10326
+ });
10327
+ controller.enqueue({
10328
+ type: "text-delta",
10329
+ id,
10330
+ delta: part.text
10331
+ });
10332
+ controller.enqueue({
10333
+ type: "text-end",
10334
+ id
10335
+ });
10336
+ } else if (part.type === "tool-call") {
10337
+ controller.enqueue({
10338
+ type: "tool-call",
10339
+ toolCallId: part.toolCallId,
10340
+ toolName: part.toolName,
10341
+ input: part.input
10342
+ });
10343
+ }
10344
+ }
10345
+ controller.enqueue({
10346
+ type: "finish",
10347
+ finishReason: result.finishReason,
10348
+ usage: result.usage
10349
+ });
10350
+ controller.close();
10351
+ }
10352
+ });
10353
+ return {
10354
+ stream,
10355
+ request: result.request,
10356
+ warnings: result.warnings
10357
+ };
10358
+ }
10359
+ /**
10360
+ * Convert AI SDK messages to MCP sampling format
10361
+ */
10362
+ convertMessages(prompt) {
10363
+ return convertAISDKToMCPMessages(prompt);
10364
+ }
10365
+ /**
10366
+ * Map MCP stop reason to AI SDK finish reason
10367
+ */
10368
+ mapStopReason(stopReason) {
10369
+ return convertMCPStopReasonToAISDK(stopReason);
10370
+ }
10371
+ /**
10372
+ * Check if client supports native tool use in sampling
10373
+ */
10374
+ supportsSamplingTools() {
10375
+ const capabilities = this.server.getClientCapabilities();
10376
+ return !!capabilities?.sampling?.tools;
10377
+ }
10378
+ /**
10379
+ * Convert AI SDK tools to MCP Tool format
10380
+ */
10381
+ convertAISDKToolsToMCP(tools) {
10382
+ if (!tools || tools.length === 0) return [];
10383
+ return tools.filter((tool3) => tool3.type === "function").map((tool3) => {
10384
+ const toolAny = tool3;
10385
+ return {
10386
+ name: tool3.name,
10387
+ description: toolAny.description || `Tool: ${tool3.name}`,
10388
+ inputSchema: {
10389
+ type: "object",
10390
+ ...toolAny.inputSchema || toolAny.parameters
10391
+ }
10392
+ };
10393
+ });
10394
+ }
10395
+ /**
10396
+ * Inject response format instructions into system prompt
10397
+ *
10398
+ * Only injects formatting instructions in JSON fallback mode.
10399
+ * In native tools mode, structured output is handled by the provider.
10400
+ */
10401
+ injectResponseFormatInstructions(systemPrompt, responseFormat, useNativeTools) {
10402
+ if (!responseFormat) {
10403
+ return systemPrompt;
10404
+ }
10405
+ if (useNativeTools) {
10406
+ return systemPrompt;
10407
+ }
10408
+ let enhanced = systemPrompt || "";
10409
+ if (responseFormat.type === "json") {
10410
+ const jsonPrompt = `
10411
+
10412
+ IMPORTANT: You MUST respond with valid JSON only. Do not include any text before or after the JSON.
10413
+ - Your response must be a valid JSON object
10414
+ - Do not wrap the JSON in markdown code blocks
10415
+ - Do not include explanations or comments
10416
+ - Ensure all JSON is properly formatted and parseable`;
10417
+ enhanced = enhanced ? `${enhanced}${jsonPrompt}` : jsonPrompt.trim();
10418
+ if (responseFormat.schema) {
10419
+ const schemaInfo = `
10420
+ - Follow this JSON schema structure: ${JSON.stringify(responseFormat.schema)}`;
10421
+ enhanced += schemaInfo;
10422
+ }
10423
+ }
10424
+ return enhanced || void 0;
10425
+ }
10426
+ /**
10427
+ * Inject tool definitions into system prompt
10428
+ *
10429
+ * WORKAROUND: MCP sampling currently doesn't support native tools parameter.
10430
+ * This method injects tool descriptions and usage instructions into the system prompt.
10431
+ *
10432
+ * TODO: Remove this workaround when MCP protocol adds native support for:
10433
+ * - tools parameter in createMessage
10434
+ * - Tool calling and function execution
10435
+ * - Structured tool responses
10436
+ */
10437
+ injectToolInstructions(systemPrompt, tools, useNativeTools) {
10438
+ if (!tools || tools.length === 0) {
10439
+ return systemPrompt;
10440
+ }
10441
+ if (useNativeTools) {
10442
+ return systemPrompt;
10443
+ }
10444
+ let enhanced = systemPrompt || "";
10445
+ const toolsPrompt = `
10446
+
10447
+ AVAILABLE TOOLS:
10448
+ You have access to the following tools. To use a tool, respond with this XML format:
10449
+ <use_tool tool="tool_name">
10450
+ {"param1": "value1", "param2": "value2"}
10451
+ </use_tool>
10452
+
10453
+ Follow the JSON schema definition for each tool's parameters.
10454
+ You can use multiple tools in one response. You can include text before tool calls, but do NOT include text after tool calls - wait for the tool results first.
10455
+
10456
+ Tools:`;
10457
+ const toolDescriptions = tools.map((tool3) => {
10458
+ if (tool3.type === "function") {
10459
+ const toolAny = tool3;
10460
+ const description = toolAny.description || "No description provided";
10461
+ const schema = toolAny.inputSchema || toolAny.parameters;
10462
+ const params = schema ? `
10463
+ JSON Schema: ${JSON.stringify(schema, null, 2)}` : "";
10464
+ return `
10465
+ - ${tool3.name}: ${description}${params}`;
10466
+ } else if (tool3.type === "provider-defined") {
10467
+ return `
10468
+ - ${tool3.name}: ${tool3.id || "No description provided"}`;
10469
+ }
10470
+ return "";
10471
+ }).filter(Boolean).join("");
10472
+ enhanced = enhanced ? `${enhanced}${toolsPrompt}${toolDescriptions}` : `${toolsPrompt}${toolDescriptions}`.trim();
10473
+ return enhanced || void 0;
10474
+ }
10475
+ /**
10476
+ * Extract tool calls from LLM response text
10477
+ *
10478
+ * Parses XML-style tool call tags from the response:
10479
+ * <use_tool tool="tool_name">{"arg": "value"}</use_tool>
10480
+ */
10481
+ extractToolCalls(responseText, tools) {
10482
+ if (!tools || tools.length === 0) {
10483
+ return {
10484
+ text: responseText,
10485
+ toolCalls: []
10486
+ };
10487
+ }
10488
+ const toolCalls = [];
10489
+ const toolCallRegex = /<use_tool\s+tool="([^"]+)">([\s\S]*?)<\/use_tool>/g;
10490
+ let match;
10491
+ let lastIndex = 0;
10492
+ const textParts = [];
10493
+ let callIndex = 0;
10494
+ while ((match = toolCallRegex.exec(responseText)) !== null) {
10495
+ textParts.push(responseText.slice(lastIndex, match.index));
10496
+ const toolName = match[1];
10497
+ const argsText = match[2].trim?.();
10498
+ toolCalls.push({
10499
+ type: "tool-call",
10500
+ toolCallId: `call_${Date.now()}_${callIndex++}`,
10501
+ toolName,
10502
+ input: argsText
10503
+ });
10504
+ lastIndex = match.index + match[0].length;
10505
+ }
10506
+ textParts.push(responseText.slice(lastIndex));
10507
+ const text = textParts.join("").trim();
10508
+ return {
10509
+ text,
10510
+ toolCalls
10511
+ };
10512
+ }
10513
+ };
10514
+
10515
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__mcp-sampling-ai-provider/src/provider.js
10516
+ var MCPSamplingProvider = class {
10517
+ config;
10518
+ constructor(config) {
10519
+ this.config = config;
10520
+ }
10521
+ /**
10522
+ * Create a language model instance for a specific MCP tool/agent
10523
+ *
10524
+ * @param options - Optional configuration overrides
10525
+ * @returns A LanguageModelV2 instance
10526
+ */
10527
+ languageModel(options) {
10528
+ return new MCPSamplingLanguageModel({
10529
+ server: this.config.server,
10530
+ modelPreferences: options?.modelPreferences
10531
+ });
10532
+ }
10533
+ /**
10534
+ * Shorthand for creating a language model
10535
+ */
10536
+ call(options) {
10537
+ return this.languageModel(options);
10538
+ }
10539
+ };
10540
+
10541
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/ai/base-ai-executor.js
10542
+ import { trace as trace2 } from "@opentelemetry/api";
10543
+ import { jsonSchema as jsonSchema2, stepCountIs, streamText, tool } from "ai";
10544
+ var BaseAIExecutor = class {
10545
+ config;
10546
+ tracer;
10547
+ logger;
10548
+ constructor(config, server) {
10549
+ this.config = {
10550
+ maxSteps: 50,
10551
+ tracingEnabled: true,
10552
+ ...config
10553
+ };
10554
+ this.tracer = trace2.getTracer(`mcpc.ai.${config.name}`);
10555
+ this.logger = createLogger(`mcpc.ai.${config.name}`, server);
10556
+ }
10557
+ execute(args) {
10558
+ if (this.config.tracingEnabled) {
10559
+ return this.executeWithTracing(args);
10560
+ }
10561
+ return this.executeCore(args);
10562
+ }
10563
+ executeWithTracing(args) {
10564
+ return this.tracer.startActiveSpan(`mcpc.ai.${this.config.name}`, async (span) => {
10565
+ try {
10566
+ span.setAttributes({
10567
+ "mcpc.executor": this.config.name,
10568
+ "mcpc.type": this.getExecutorType()
10569
+ });
10570
+ const result = await this.executeCore(args, span);
10571
+ span.setAttributes({
10572
+ "mcpc.error": !!result.isError
10573
+ });
10574
+ return result;
10575
+ } catch (error) {
10576
+ span.recordException(error);
10577
+ throw error;
10578
+ } finally {
10579
+ span.end();
10580
+ }
10581
+ });
10582
+ }
10583
+ async executeCore(args, span) {
10584
+ try {
10585
+ const result = streamText({
10586
+ model: this.getModel(),
10587
+ system: this.buildSystemPrompt(args),
10588
+ messages: [
10589
+ {
10590
+ role: "user",
10591
+ content: args.userRequest
10592
+ }
10593
+ ],
10594
+ tools: this.buildTools(),
10595
+ stopWhen: stepCountIs(this.config.maxSteps),
10596
+ experimental_telemetry: this.config.tracingEnabled ? {
10597
+ isEnabled: true,
10598
+ functionId: `mcpc.${this.config.name}`,
10599
+ tracer: this.tracer
10600
+ } : void 0,
10601
+ onStepFinish: (step) => {
10602
+ if (span) {
10603
+ span.addEvent("step", {
10604
+ tools: step.toolCalls?.length ?? 0,
10605
+ reason: step.finishReason ?? ""
10606
+ });
10607
+ }
10608
+ }
10609
+ });
10610
+ return {
10611
+ content: [
10612
+ {
10613
+ type: "text",
10614
+ text: await result.text || `Completed in ${(await result.steps)?.length ?? "unknown"} step(s).`
10615
+ }
10616
+ ],
10617
+ isError: false
10618
+ };
10619
+ } catch (error) {
10620
+ this.logger.error({
10621
+ message: "Execution error",
10622
+ error
10623
+ });
10624
+ return {
10625
+ content: [
10626
+ {
10627
+ type: "text",
10628
+ text: `Error: ${error instanceof Error ? error.message : String(error)}`
10629
+ }
10630
+ ],
10631
+ isError: true
10632
+ };
10633
+ }
10634
+ }
10635
+ buildSystemPrompt(args) {
10636
+ return `Agent \`${this.config.name}\` that completes tasks by calling tools.
10637
+
10638
+ <manual>
10639
+ ${this.config.description}
10640
+ </manual>
10641
+
10642
+ <rules>
10643
+ ${this.getRules()}
10644
+ </rules>
10645
+
10646
+ <tools>
10647
+ ${this.getToolListDescription()}
10648
+ </tools>${args.context ? this.formatContext(args.context) : ""}`;
10649
+ }
10650
+ getRules() {
10651
+ return `1. Use tools to complete the user's request
10652
+ 2. Review results after each tool call
10653
+ 3. Adapt your approach based on outcomes
10654
+ 4. Continue until task is complete
10655
+ 5. When complete, provide a summary WITHOUT calling more tools`;
10656
+ }
10657
+ getToolListDescription() {
10658
+ return "Tools will be provided by AI SDK";
10659
+ }
10660
+ formatContext(context2) {
10661
+ return `
10662
+
10663
+ <context>
10664
+ ${JSON.stringify(context2, null, 2)}
10665
+ </context>`;
10666
+ }
10667
+ convertToAISDKTool(name, toolDetail, execute) {
10668
+ return tool({
10669
+ description: toolDetail.description || `Tool: ${name}`,
10670
+ inputSchema: jsonSchema2(toolDetail.inputSchema || {
10671
+ type: "object"
10672
+ }),
10673
+ execute
10674
+ });
10675
+ }
10676
+ };
10677
+
10678
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/ai/ai-sampling-executor.js
10679
+ var AISamplingExecutor = class extends BaseAIExecutor {
10680
+ server;
10681
+ tools;
10682
+ providerOptions;
10683
+ model = null;
10684
+ constructor(config) {
10685
+ super(config, "callTool" in config.server ? config.server : void 0);
10686
+ this.server = config.server;
10687
+ this.tools = config.tools;
10688
+ this.providerOptions = config.providerOptions;
10689
+ }
10690
+ initProvider() {
10691
+ if (!this.model) {
10692
+ const provider = new MCPSamplingProvider({
10693
+ server: this.server
10694
+ });
10695
+ this.model = provider.languageModel(this.providerOptions);
10696
+ }
10697
+ return this.model;
10698
+ }
10699
+ getModel() {
10700
+ if (!this.model) throw new Error("Model not initialized");
10701
+ return this.model;
10702
+ }
10703
+ getExecutorType() {
10704
+ return "mcp";
10705
+ }
10706
+ getToolListDescription() {
10707
+ return this.tools.map(([name, detail]) => `- ${name}: ${detail.description || "No description"}`).join("\n");
10708
+ }
10709
+ buildTools() {
10710
+ const aiTools = {};
10711
+ for (const [name, detail] of this.tools) {
10712
+ aiTools[name] = this.convertToAISDKTool(name, detail, async (input) => {
10713
+ const result = await this.callTool(name, input);
10714
+ return this.formatResult(result);
10715
+ });
10716
+ }
10717
+ return aiTools;
10718
+ }
10719
+ async callTool(name, input) {
10720
+ if ("callTool" in this.server) {
10721
+ return await this.server.callTool(name, input);
10722
+ }
10723
+ const detail = this.tools.find(([n]) => n === name)?.[1];
10724
+ if (detail?.execute) return await detail.execute(input);
10725
+ throw new Error(`Cannot call tool "${name}"`);
10726
+ }
10727
+ formatResult(result) {
10728
+ const texts = result.content?.filter((c) => c.type === "text").map((c) => c.text);
10729
+ return texts?.length ? texts.join("\n") : JSON.stringify(result.content);
10730
+ }
10731
+ execute(args) {
10732
+ this.initProvider();
10733
+ return super.execute(args);
10734
+ }
10735
+ };
10736
+
10737
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/ai/ai-sampling-registrar.js
10738
+ function registerAISamplingTool(server, params) {
10739
+ const { name, description, allToolNames, depGroups, toolNameToDetailList, providerOptions, maxSteps = 50, tracingEnabled = false } = params;
10740
+ const createArgsDef = createArgsDefFactory(name, allToolNames, depGroups, void 0, void 0);
10741
+ const executor = new AISamplingExecutor({
10742
+ name,
10743
+ description,
10744
+ server,
10745
+ tools: toolNameToDetailList,
10746
+ providerOptions,
10747
+ maxSteps,
10748
+ tracingEnabled
10749
+ });
10750
+ const toolDescription = CompiledPrompts.samplingToolDescription({
10751
+ toolName: name,
10752
+ description,
10753
+ toolList: allToolNames.map((n) => `- ${n}`).join("\n")
10754
+ });
10755
+ const argsDef = createArgsDef.forSampling();
10756
+ const schema = allToolNames.length > 0 ? argsDef : {
10757
+ type: "object",
10758
+ properties: {}
10759
+ };
10760
+ server.tool(name, toolDescription, jsonSchema(createModelCompatibleJSONSchema(schema)), (args) => {
10761
+ const userRequest = typeof args.userRequest === "string" ? args.userRequest : JSON.stringify(args);
10762
+ return executor.execute({
10763
+ userRequest,
10764
+ context: args.context
10765
+ });
10766
+ });
10767
+ }
10768
+
10769
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/mode-ai-sampling-plugin.js
10770
+ var createAISamplingModePlugin = () => ({
10771
+ name: "mode-ai-sampling",
10772
+ version: "1.0.0",
10773
+ apply: "ai_sampling",
10774
+ registerAgentTool: (context2) => {
10775
+ const opts = context2.options;
10776
+ registerAISamplingTool(context2.server, {
10777
+ description: context2.description,
10778
+ name: context2.name,
10779
+ allToolNames: context2.allToolNames,
10780
+ depGroups: context2.depGroups,
10781
+ toolNameToDetailList: context2.toolNameToDetailList,
10782
+ providerOptions: opts.providerOptions,
10783
+ maxSteps: opts.maxSteps,
10784
+ tracingEnabled: opts.tracingEnabled
10785
+ });
10786
+ }
10787
+ });
10788
+ var mode_ai_sampling_plugin_default = createAISamplingModePlugin();
10789
+
10790
+ // __mcpc__cli_latest/node_modules/@agentclientprotocol/sdk/dist/acp.js
10791
+ import { z as z6 } from "zod";
10792
+
10793
+ // __mcpc__cli_latest/node_modules/@agentclientprotocol/sdk/dist/schema.js
10794
+ import { z as z5 } from "zod";
10795
+ var AGENT_METHODS = {
10796
+ authenticate: "authenticate",
10797
+ initialize: "initialize",
10798
+ session_cancel: "session/cancel",
10799
+ session_load: "session/load",
10800
+ session_new: "session/new",
10801
+ session_prompt: "session/prompt",
10802
+ session_set_mode: "session/set_mode",
10803
+ session_set_model: "session/set_model"
10804
+ };
10805
+ var CLIENT_METHODS = {
10806
+ fs_read_text_file: "fs/read_text_file",
10807
+ fs_write_text_file: "fs/write_text_file",
10808
+ session_request_permission: "session/request_permission",
10809
+ session_update: "session/update",
10810
+ terminal_create: "terminal/create",
10811
+ terminal_kill: "terminal/kill",
10812
+ terminal_output: "terminal/output",
10813
+ terminal_release: "terminal/release",
10814
+ terminal_wait_for_exit: "terminal/wait_for_exit"
10815
+ };
10816
+ var PROTOCOL_VERSION = 1;
10817
+ var writeTextFileRequestSchema = z5.object({
10818
+ _meta: z5.record(z5.unknown()).optional(),
10819
+ content: z5.string(),
10820
+ path: z5.string(),
10821
+ sessionId: z5.string()
10822
+ });
10823
+ var readTextFileRequestSchema = z5.object({
10824
+ _meta: z5.record(z5.unknown()).optional(),
10825
+ limit: z5.number().optional().nullable(),
10826
+ line: z5.number().optional().nullable(),
10827
+ path: z5.string(),
10828
+ sessionId: z5.string()
10829
+ });
10830
+ var terminalOutputRequestSchema = z5.object({
10831
+ _meta: z5.record(z5.unknown()).optional(),
10832
+ sessionId: z5.string(),
10833
+ terminalId: z5.string()
10834
+ });
10835
+ var releaseTerminalRequestSchema = z5.object({
10836
+ _meta: z5.record(z5.unknown()).optional(),
10837
+ sessionId: z5.string(),
10838
+ terminalId: z5.string()
10839
+ });
10840
+ var waitForTerminalExitRequestSchema = z5.object({
10841
+ _meta: z5.record(z5.unknown()).optional(),
10842
+ sessionId: z5.string(),
10843
+ terminalId: z5.string()
10844
+ });
10845
+ var killTerminalCommandRequestSchema = z5.object({
10846
+ _meta: z5.record(z5.unknown()).optional(),
10847
+ sessionId: z5.string(),
10848
+ terminalId: z5.string()
10849
+ });
10850
+ var extMethodRequestSchema = z5.record(z5.unknown());
10851
+ var roleSchema = z5.union([z5.literal("assistant"), z5.literal("user")]);
10852
+ var textResourceContentsSchema = z5.object({
10853
+ _meta: z5.record(z5.unknown()).optional(),
10854
+ mimeType: z5.string().optional().nullable(),
10855
+ text: z5.string(),
10856
+ uri: z5.string()
10857
+ });
10858
+ var blobResourceContentsSchema = z5.object({
10859
+ _meta: z5.record(z5.unknown()).optional(),
10860
+ blob: z5.string(),
10861
+ mimeType: z5.string().optional().nullable(),
10862
+ uri: z5.string()
10863
+ });
10864
+ var toolKindSchema = z5.union([
10865
+ z5.literal("read"),
10866
+ z5.literal("edit"),
10867
+ z5.literal("delete"),
10868
+ z5.literal("move"),
10869
+ z5.literal("search"),
10870
+ z5.literal("execute"),
10871
+ z5.literal("think"),
10872
+ z5.literal("fetch"),
10873
+ z5.literal("switch_mode"),
10874
+ z5.literal("other")
10875
+ ]);
10876
+ var toolCallStatusSchema = z5.union([
10877
+ z5.literal("pending"),
10878
+ z5.literal("in_progress"),
10879
+ z5.literal("completed"),
10880
+ z5.literal("failed")
10881
+ ]);
10882
+ var writeTextFileResponseSchema = z5.object({
10883
+ _meta: z5.record(z5.unknown()).optional()
10884
+ });
10885
+ var readTextFileResponseSchema = z5.object({
10886
+ _meta: z5.record(z5.unknown()).optional(),
10887
+ content: z5.string()
10888
+ });
10889
+ var requestPermissionResponseSchema = z5.object({
10890
+ _meta: z5.record(z5.unknown()).optional(),
10891
+ outcome: z5.union([
10892
+ z5.object({
10893
+ outcome: z5.literal("cancelled")
10894
+ }),
10895
+ z5.object({
10896
+ optionId: z5.string(),
10897
+ outcome: z5.literal("selected")
10898
+ })
10899
+ ])
10900
+ });
10901
+ var createTerminalResponseSchema = z5.object({
10902
+ _meta: z5.record(z5.unknown()).optional(),
10903
+ terminalId: z5.string()
10904
+ });
10905
+ var releaseTerminalResponseSchema = z5.object({
10906
+ _meta: z5.record(z5.unknown()).optional()
10907
+ });
10908
+ var waitForTerminalExitResponseSchema = z5.object({
10909
+ _meta: z5.record(z5.unknown()).optional(),
10910
+ exitCode: z5.number().optional().nullable(),
10911
+ signal: z5.string().optional().nullable()
10912
+ });
10913
+ var killTerminalResponseSchema = z5.object({
10914
+ _meta: z5.record(z5.unknown()).optional()
10915
+ });
10916
+ var extMethodResponseSchema = z5.record(z5.unknown());
10917
+ var cancelNotificationSchema = z5.object({
10918
+ _meta: z5.record(z5.unknown()).optional(),
10919
+ sessionId: z5.string()
10920
+ });
10921
+ var extNotificationSchema = z5.record(z5.unknown());
10922
+ var authenticateRequestSchema = z5.object({
10923
+ _meta: z5.record(z5.unknown()).optional(),
10924
+ methodId: z5.string()
10925
+ });
10926
+ var setSessionModeRequestSchema = z5.object({
10927
+ _meta: z5.record(z5.unknown()).optional(),
10928
+ modeId: z5.string(),
10929
+ sessionId: z5.string()
10930
+ });
10931
+ var setSessionModelRequestSchema = z5.object({
10932
+ _meta: z5.record(z5.unknown()).optional(),
10933
+ modelId: z5.string(),
10934
+ sessionId: z5.string()
10935
+ });
10936
+ var extMethodRequest1Schema = z5.record(z5.unknown());
10937
+ var httpHeaderSchema = z5.object({
10938
+ _meta: z5.record(z5.unknown()).optional(),
10939
+ name: z5.string(),
10940
+ value: z5.string()
10941
+ });
10942
+ var annotationsSchema = z5.object({
10943
+ _meta: z5.record(z5.unknown()).optional(),
10944
+ audience: z5.array(roleSchema).optional().nullable(),
10945
+ lastModified: z5.string().optional().nullable(),
10946
+ priority: z5.number().optional().nullable()
10947
+ });
10948
+ var embeddedResourceResourceSchema = z5.union([
10949
+ textResourceContentsSchema,
10950
+ blobResourceContentsSchema
10951
+ ]);
10952
+ var authenticateResponseSchema = z5.object({
10953
+ _meta: z5.record(z5.unknown()).optional()
10954
+ });
10955
+ var setSessionModeResponseSchema = z5.object({
10956
+ meta: z5.unknown().optional()
10957
+ });
10958
+ var promptResponseSchema = z5.object({
10959
+ _meta: z5.record(z5.unknown()).optional(),
10960
+ stopReason: z5.union([
10961
+ z5.literal("end_turn"),
10962
+ z5.literal("max_tokens"),
10963
+ z5.literal("max_turn_requests"),
10964
+ z5.literal("refusal"),
10965
+ z5.literal("cancelled")
10966
+ ])
10967
+ });
10968
+ var setSessionModelResponseSchema = z5.object({
10969
+ _meta: z5.record(z5.unknown()).optional()
10970
+ });
10971
+ var extMethodResponse1Schema = z5.record(z5.unknown());
10972
+ var sessionModeIdSchema = z5.string();
10973
+ var extNotification1Schema = z5.record(z5.unknown());
10974
+ var unstructuredCommandInputSchema = z5.object({
10975
+ hint: z5.string()
10976
+ });
10977
+ var permissionOptionSchema = z5.object({
10978
+ _meta: z5.record(z5.unknown()).optional(),
10979
+ kind: z5.union([
10980
+ z5.literal("allow_once"),
10981
+ z5.literal("allow_always"),
10982
+ z5.literal("reject_once"),
10983
+ z5.literal("reject_always")
10984
+ ]),
10985
+ name: z5.string(),
10986
+ optionId: z5.string()
10987
+ });
10988
+ var toolCallContentSchema = z5.union([
10989
+ z5.object({
10990
+ content: z5.union([
10991
+ z5.object({
10992
+ _meta: z5.record(z5.unknown()).optional(),
10993
+ annotations: annotationsSchema.optional().nullable(),
10994
+ text: z5.string(),
10995
+ type: z5.literal("text")
10996
+ }),
10997
+ z5.object({
10998
+ _meta: z5.record(z5.unknown()).optional(),
10999
+ annotations: annotationsSchema.optional().nullable(),
11000
+ data: z5.string(),
11001
+ mimeType: z5.string(),
11002
+ type: z5.literal("image"),
11003
+ uri: z5.string().optional().nullable()
11004
+ }),
11005
+ z5.object({
11006
+ _meta: z5.record(z5.unknown()).optional(),
11007
+ annotations: annotationsSchema.optional().nullable(),
11008
+ data: z5.string(),
11009
+ mimeType: z5.string(),
11010
+ type: z5.literal("audio")
11011
+ }),
11012
+ z5.object({
11013
+ _meta: z5.record(z5.unknown()).optional(),
11014
+ annotations: annotationsSchema.optional().nullable(),
11015
+ description: z5.string().optional().nullable(),
11016
+ mimeType: z5.string().optional().nullable(),
11017
+ name: z5.string(),
11018
+ size: z5.number().optional().nullable(),
11019
+ title: z5.string().optional().nullable(),
11020
+ type: z5.literal("resource_link"),
11021
+ uri: z5.string()
11022
+ }),
11023
+ z5.object({
11024
+ _meta: z5.record(z5.unknown()).optional(),
11025
+ annotations: annotationsSchema.optional().nullable(),
11026
+ resource: embeddedResourceResourceSchema,
11027
+ type: z5.literal("resource")
11028
+ })
11029
+ ]),
11030
+ type: z5.literal("content")
11031
+ }),
11032
+ z5.object({
11033
+ _meta: z5.record(z5.unknown()).optional(),
11034
+ newText: z5.string(),
11035
+ oldText: z5.string().optional().nullable(),
11036
+ path: z5.string(),
11037
+ type: z5.literal("diff")
11038
+ }),
11039
+ z5.object({
11040
+ terminalId: z5.string(),
11041
+ type: z5.literal("terminal")
11042
+ })
11043
+ ]);
11044
+ var toolCallLocationSchema = z5.object({
11045
+ _meta: z5.record(z5.unknown()).optional(),
11046
+ line: z5.number().optional().nullable(),
11047
+ path: z5.string()
11048
+ });
11049
+ var envVariableSchema = z5.object({
11050
+ _meta: z5.record(z5.unknown()).optional(),
11051
+ name: z5.string(),
11052
+ value: z5.string()
11053
+ });
11054
+ var terminalExitStatusSchema = z5.object({
11055
+ _meta: z5.record(z5.unknown()).optional(),
11056
+ exitCode: z5.number().optional().nullable(),
11057
+ signal: z5.string().optional().nullable()
11058
+ });
11059
+ var fileSystemCapabilitySchema = z5.object({
11060
+ _meta: z5.record(z5.unknown()).optional(),
11061
+ readTextFile: z5.boolean().optional(),
11062
+ writeTextFile: z5.boolean().optional()
11063
+ });
11064
+ var stdioSchema = z5.object({
11065
+ args: z5.array(z5.string()),
11066
+ command: z5.string(),
11067
+ env: z5.array(envVariableSchema),
11068
+ name: z5.string()
11069
+ });
11070
+ var mcpServerSchema = z5.union([
11071
+ z5.object({
11072
+ headers: z5.array(httpHeaderSchema),
11073
+ name: z5.string(),
11074
+ type: z5.literal("http"),
11075
+ url: z5.string()
11076
+ }),
11077
+ z5.object({
11078
+ headers: z5.array(httpHeaderSchema),
11079
+ name: z5.string(),
11080
+ type: z5.literal("sse"),
11081
+ url: z5.string()
11082
+ }),
11083
+ stdioSchema
11084
+ ]);
11085
+ var contentBlockSchema = z5.union([
11086
+ z5.object({
11087
+ _meta: z5.record(z5.unknown()).optional(),
11088
+ annotations: annotationsSchema.optional().nullable(),
11089
+ text: z5.string(),
11090
+ type: z5.literal("text")
11091
+ }),
11092
+ z5.object({
11093
+ _meta: z5.record(z5.unknown()).optional(),
11094
+ annotations: annotationsSchema.optional().nullable(),
11095
+ data: z5.string(),
11096
+ mimeType: z5.string(),
11097
+ type: z5.literal("image"),
11098
+ uri: z5.string().optional().nullable()
11099
+ }),
11100
+ z5.object({
11101
+ _meta: z5.record(z5.unknown()).optional(),
11102
+ annotations: annotationsSchema.optional().nullable(),
11103
+ data: z5.string(),
11104
+ mimeType: z5.string(),
11105
+ type: z5.literal("audio")
11106
+ }),
11107
+ z5.object({
11108
+ _meta: z5.record(z5.unknown()).optional(),
11109
+ annotations: annotationsSchema.optional().nullable(),
11110
+ description: z5.string().optional().nullable(),
11111
+ mimeType: z5.string().optional().nullable(),
11112
+ name: z5.string(),
11113
+ size: z5.number().optional().nullable(),
11114
+ title: z5.string().optional().nullable(),
11115
+ type: z5.literal("resource_link"),
11116
+ uri: z5.string()
11117
+ }),
11118
+ z5.object({
11119
+ _meta: z5.record(z5.unknown()).optional(),
11120
+ annotations: annotationsSchema.optional().nullable(),
11121
+ resource: embeddedResourceResourceSchema,
11122
+ type: z5.literal("resource")
11123
+ })
11124
+ ]);
11125
+ var authMethodSchema = z5.object({
11126
+ _meta: z5.record(z5.unknown()).optional(),
11127
+ description: z5.string().optional().nullable(),
11128
+ id: z5.string(),
11129
+ name: z5.string()
11130
+ });
11131
+ var mcpCapabilitiesSchema = z5.object({
11132
+ _meta: z5.record(z5.unknown()).optional(),
11133
+ http: z5.boolean().optional(),
11134
+ sse: z5.boolean().optional()
11135
+ });
11136
+ var promptCapabilitiesSchema = z5.object({
11137
+ _meta: z5.record(z5.unknown()).optional(),
11138
+ audio: z5.boolean().optional(),
11139
+ embeddedContext: z5.boolean().optional(),
11140
+ image: z5.boolean().optional()
11141
+ });
11142
+ var modelInfoSchema = z5.object({
11143
+ _meta: z5.record(z5.unknown()).optional(),
11144
+ description: z5.string().optional().nullable(),
11145
+ modelId: z5.string(),
11146
+ name: z5.string()
11147
+ });
11148
+ var sessionModeSchema = z5.object({
11149
+ _meta: z5.record(z5.unknown()).optional(),
11150
+ description: z5.string().optional().nullable(),
11151
+ id: sessionModeIdSchema,
11152
+ name: z5.string()
11153
+ });
11154
+ var sessionModelStateSchema = z5.object({
11155
+ _meta: z5.record(z5.unknown()).optional(),
11156
+ availableModels: z5.array(modelInfoSchema),
11157
+ currentModelId: z5.string()
11158
+ });
11159
+ var sessionModeStateSchema = z5.object({
11160
+ _meta: z5.record(z5.unknown()).optional(),
11161
+ availableModes: z5.array(sessionModeSchema),
11162
+ currentModeId: z5.string()
11163
+ });
11164
+ var planEntrySchema = z5.object({
11165
+ _meta: z5.record(z5.unknown()).optional(),
11166
+ content: z5.string(),
11167
+ priority: z5.union([z5.literal("high"), z5.literal("medium"), z5.literal("low")]),
11168
+ status: z5.union([
11169
+ z5.literal("pending"),
11170
+ z5.literal("in_progress"),
11171
+ z5.literal("completed")
11172
+ ])
11173
+ });
11174
+ var availableCommandInputSchema = unstructuredCommandInputSchema;
11175
+ var clientNotificationSchema = z5.union([
11176
+ cancelNotificationSchema,
11177
+ extNotificationSchema
11178
+ ]);
11179
+ var createTerminalRequestSchema = z5.object({
11180
+ _meta: z5.record(z5.unknown()).optional(),
11181
+ args: z5.array(z5.string()).optional(),
11182
+ command: z5.string(),
11183
+ cwd: z5.string().optional().nullable(),
11184
+ env: z5.array(envVariableSchema).optional(),
11185
+ outputByteLimit: z5.number().optional().nullable(),
11186
+ sessionId: z5.string()
11187
+ });
11188
+ var terminalOutputResponseSchema = z5.object({
11189
+ _meta: z5.record(z5.unknown()).optional(),
11190
+ exitStatus: terminalExitStatusSchema.optional().nullable(),
11191
+ output: z5.string(),
11192
+ truncated: z5.boolean()
11193
+ });
11194
+ var newSessionRequestSchema = z5.object({
11195
+ _meta: z5.record(z5.unknown()).optional(),
11196
+ cwd: z5.string(),
11197
+ mcpServers: z5.array(mcpServerSchema)
11198
+ });
11199
+ var loadSessionRequestSchema = z5.object({
11200
+ _meta: z5.record(z5.unknown()).optional(),
11201
+ cwd: z5.string(),
11202
+ mcpServers: z5.array(mcpServerSchema),
11203
+ sessionId: z5.string()
11204
+ });
11205
+ var promptRequestSchema = z5.object({
11206
+ _meta: z5.record(z5.unknown()).optional(),
11207
+ prompt: z5.array(contentBlockSchema),
11208
+ sessionId: z5.string()
11209
+ });
11210
+ var newSessionResponseSchema = z5.object({
11211
+ _meta: z5.record(z5.unknown()).optional(),
11212
+ models: sessionModelStateSchema.optional().nullable(),
11213
+ modes: sessionModeStateSchema.optional().nullable(),
11214
+ sessionId: z5.string()
11215
+ });
11216
+ var loadSessionResponseSchema = z5.object({
11217
+ _meta: z5.record(z5.unknown()).optional(),
11218
+ models: sessionModelStateSchema.optional().nullable(),
11219
+ modes: sessionModeStateSchema.optional().nullable()
11220
+ });
11221
+ var toolCallUpdateSchema = z5.object({
11222
+ _meta: z5.record(z5.unknown()).optional(),
11223
+ content: z5.array(toolCallContentSchema).optional().nullable(),
11224
+ kind: toolKindSchema.optional().nullable(),
11225
+ locations: z5.array(toolCallLocationSchema).optional().nullable(),
11226
+ rawInput: z5.record(z5.unknown()).optional(),
11227
+ rawOutput: z5.record(z5.unknown()).optional(),
11228
+ status: toolCallStatusSchema.optional().nullable(),
11229
+ title: z5.string().optional().nullable(),
11230
+ toolCallId: z5.string()
11231
+ });
11232
+ var clientCapabilitiesSchema = z5.object({
11233
+ _meta: z5.record(z5.unknown()).optional(),
11234
+ fs: fileSystemCapabilitySchema.optional(),
11235
+ terminal: z5.boolean().optional()
11236
+ });
11237
+ var agentCapabilitiesSchema = z5.object({
11238
+ _meta: z5.record(z5.unknown()).optional(),
11239
+ loadSession: z5.boolean().optional(),
11240
+ mcpCapabilities: mcpCapabilitiesSchema.optional(),
11241
+ promptCapabilities: promptCapabilitiesSchema.optional()
11242
+ });
11243
+ var availableCommandSchema = z5.object({
11244
+ _meta: z5.record(z5.unknown()).optional(),
11245
+ description: z5.string(),
11246
+ input: availableCommandInputSchema.optional().nullable(),
11247
+ name: z5.string()
11248
+ });
11249
+ var clientResponseSchema = z5.union([
11250
+ writeTextFileResponseSchema,
11251
+ readTextFileResponseSchema,
11252
+ requestPermissionResponseSchema,
11253
+ createTerminalResponseSchema,
11254
+ terminalOutputResponseSchema,
11255
+ releaseTerminalResponseSchema,
11256
+ waitForTerminalExitResponseSchema,
11257
+ killTerminalResponseSchema,
11258
+ extMethodResponseSchema
11259
+ ]);
11260
+ var requestPermissionRequestSchema = z5.object({
11261
+ _meta: z5.record(z5.unknown()).optional(),
11262
+ options: z5.array(permissionOptionSchema),
11263
+ sessionId: z5.string(),
11264
+ toolCall: toolCallUpdateSchema
11265
+ });
11266
+ var initializeRequestSchema = z5.object({
11267
+ _meta: z5.record(z5.unknown()).optional(),
11268
+ clientCapabilities: clientCapabilitiesSchema.optional(),
11269
+ protocolVersion: z5.number()
11270
+ });
11271
+ var initializeResponseSchema = z5.object({
11272
+ _meta: z5.record(z5.unknown()).optional(),
11273
+ agentCapabilities: agentCapabilitiesSchema.optional(),
11274
+ authMethods: z5.array(authMethodSchema).optional(),
11275
+ protocolVersion: z5.number()
11276
+ });
11277
+ var sessionNotificationSchema = z5.object({
11278
+ _meta: z5.record(z5.unknown()).optional(),
11279
+ sessionId: z5.string(),
11280
+ update: z5.union([
11281
+ z5.object({
11282
+ content: contentBlockSchema,
11283
+ sessionUpdate: z5.literal("user_message_chunk")
11284
+ }),
11285
+ z5.object({
11286
+ content: contentBlockSchema,
11287
+ sessionUpdate: z5.literal("agent_message_chunk")
11288
+ }),
11289
+ z5.object({
11290
+ content: contentBlockSchema,
11291
+ sessionUpdate: z5.literal("agent_thought_chunk")
11292
+ }),
11293
+ z5.object({
11294
+ _meta: z5.record(z5.unknown()).optional(),
11295
+ content: z5.array(toolCallContentSchema).optional(),
11296
+ kind: z5.union([
11297
+ z5.literal("read"),
11298
+ z5.literal("edit"),
11299
+ z5.literal("delete"),
11300
+ z5.literal("move"),
11301
+ z5.literal("search"),
11302
+ z5.literal("execute"),
11303
+ z5.literal("think"),
11304
+ z5.literal("fetch"),
11305
+ z5.literal("switch_mode"),
11306
+ z5.literal("other")
11307
+ ]).optional(),
11308
+ locations: z5.array(toolCallLocationSchema).optional(),
11309
+ rawInput: z5.record(z5.unknown()).optional(),
11310
+ rawOutput: z5.record(z5.unknown()).optional(),
11311
+ sessionUpdate: z5.literal("tool_call"),
11312
+ status: z5.union([
11313
+ z5.literal("pending"),
11314
+ z5.literal("in_progress"),
11315
+ z5.literal("completed"),
11316
+ z5.literal("failed")
11317
+ ]).optional(),
11318
+ title: z5.string(),
11319
+ toolCallId: z5.string()
11320
+ }),
11321
+ z5.object({
11322
+ _meta: z5.record(z5.unknown()).optional(),
11323
+ content: z5.array(toolCallContentSchema).optional().nullable(),
11324
+ kind: toolKindSchema.optional().nullable(),
11325
+ locations: z5.array(toolCallLocationSchema).optional().nullable(),
11326
+ rawInput: z5.record(z5.unknown()).optional(),
11327
+ rawOutput: z5.record(z5.unknown()).optional(),
11328
+ sessionUpdate: z5.literal("tool_call_update"),
11329
+ status: toolCallStatusSchema.optional().nullable(),
11330
+ title: z5.string().optional().nullable(),
11331
+ toolCallId: z5.string()
11332
+ }),
11333
+ z5.object({
11334
+ _meta: z5.record(z5.unknown()).optional(),
11335
+ entries: z5.array(planEntrySchema),
11336
+ sessionUpdate: z5.literal("plan")
11337
+ }),
11338
+ z5.object({
11339
+ availableCommands: z5.array(availableCommandSchema),
11340
+ sessionUpdate: z5.literal("available_commands_update")
11341
+ }),
11342
+ z5.object({
11343
+ currentModeId: sessionModeIdSchema,
11344
+ sessionUpdate: z5.literal("current_mode_update")
11345
+ })
11346
+ ])
11347
+ });
11348
+ var clientRequestSchema = z5.union([
11349
+ writeTextFileRequestSchema,
11350
+ readTextFileRequestSchema,
11351
+ requestPermissionRequestSchema,
11352
+ createTerminalRequestSchema,
11353
+ terminalOutputRequestSchema,
11354
+ releaseTerminalRequestSchema,
11355
+ waitForTerminalExitRequestSchema,
11356
+ killTerminalCommandRequestSchema,
11357
+ extMethodRequestSchema
11358
+ ]);
11359
+ var agentRequestSchema = z5.union([
11360
+ initializeRequestSchema,
11361
+ authenticateRequestSchema,
11362
+ newSessionRequestSchema,
11363
+ loadSessionRequestSchema,
11364
+ setSessionModeRequestSchema,
11365
+ promptRequestSchema,
11366
+ setSessionModelRequestSchema,
11367
+ extMethodRequest1Schema
11368
+ ]);
11369
+ var agentResponseSchema = z5.union([
11370
+ initializeResponseSchema,
11371
+ authenticateResponseSchema,
11372
+ newSessionResponseSchema,
11373
+ loadSessionResponseSchema,
11374
+ setSessionModeResponseSchema,
11375
+ promptResponseSchema,
11376
+ setSessionModelResponseSchema,
11377
+ extMethodResponse1Schema
11378
+ ]);
11379
+ var agentNotificationSchema = z5.union([
11380
+ sessionNotificationSchema,
11381
+ extNotification1Schema
11382
+ ]);
11383
+ var agentClientProtocolSchema = z5.union([
11384
+ clientRequestSchema,
11385
+ clientResponseSchema,
11386
+ clientNotificationSchema,
11387
+ agentRequestSchema,
11388
+ agentResponseSchema,
11389
+ agentNotificationSchema
11390
+ ]);
11391
+
11392
+ // __mcpc__cli_latest/node_modules/@agentclientprotocol/sdk/dist/stream.js
11393
+ function ndJsonStream(output, input) {
11394
+ const textEncoder = new TextEncoder();
11395
+ const textDecoder = new TextDecoder();
11396
+ const readable = new ReadableStream({
11397
+ async start(controller) {
11398
+ let content = "";
11399
+ const reader = input.getReader();
11400
+ try {
11401
+ while (true) {
11402
+ const { value, done } = await reader.read();
11403
+ if (done) {
11404
+ break;
11405
+ }
11406
+ if (!value) {
11407
+ continue;
11408
+ }
11409
+ content += textDecoder.decode(value, { stream: true });
11410
+ const lines = content.split("\n");
11411
+ content = lines.pop() || "";
11412
+ for (const line of lines) {
11413
+ const trimmedLine = line.trim();
11414
+ if (trimmedLine) {
11415
+ try {
11416
+ const message = JSON.parse(trimmedLine);
11417
+ controller.enqueue(message);
11418
+ } catch (err) {
11419
+ console.error("Failed to parse JSON message:", trimmedLine, err);
11420
+ }
11421
+ }
11422
+ }
11423
+ }
11424
+ } finally {
11425
+ reader.releaseLock();
11426
+ controller.close();
11427
+ }
11428
+ }
11429
+ });
11430
+ const writable = new WritableStream({
11431
+ async write(message) {
11432
+ const content = JSON.stringify(message) + "\n";
11433
+ const writer = output.getWriter();
11434
+ try {
11435
+ await writer.write(textEncoder.encode(content));
11436
+ } finally {
11437
+ writer.releaseLock();
11438
+ }
11439
+ }
11440
+ });
11441
+ return { readable, writable };
11442
+ }
11443
+
11444
+ // __mcpc__cli_latest/node_modules/@agentclientprotocol/sdk/dist/acp.js
11445
+ var ClientSideConnection = class {
11446
+ #connection;
11447
+ /**
11448
+ * Creates a new client-side connection to an agent.
11449
+ *
11450
+ * This establishes the communication channel between a client and agent
11451
+ * following the ACP specification.
11452
+ *
11453
+ * @param toClient - A function that creates a Client handler to process incoming agent requests
11454
+ * @param stream - The bidirectional message stream for communication. Typically created using
11455
+ * {@link ndJsonStream} for stdio-based connections.
11456
+ *
11457
+ * See protocol docs: [Communication Model](https://agentclientprotocol.com/protocol/overview#communication-model)
11458
+ */
11459
+ constructor(toClient, stream) {
11460
+ const client = toClient(this);
11461
+ const requestHandler = async (method, params) => {
11462
+ switch (method) {
11463
+ case CLIENT_METHODS.fs_write_text_file: {
11464
+ const validatedParams = writeTextFileRequestSchema.parse(params);
11465
+ return client.writeTextFile?.(validatedParams);
11466
+ }
11467
+ case CLIENT_METHODS.fs_read_text_file: {
11468
+ const validatedParams = readTextFileRequestSchema.parse(params);
11469
+ return client.readTextFile?.(validatedParams);
11470
+ }
11471
+ case CLIENT_METHODS.session_request_permission: {
11472
+ const validatedParams = requestPermissionRequestSchema.parse(params);
11473
+ return client.requestPermission(validatedParams);
11474
+ }
11475
+ case CLIENT_METHODS.terminal_create: {
11476
+ const validatedParams = createTerminalRequestSchema.parse(params);
11477
+ return client.createTerminal?.(validatedParams);
11478
+ }
11479
+ case CLIENT_METHODS.terminal_output: {
11480
+ const validatedParams = terminalOutputRequestSchema.parse(params);
11481
+ return client.terminalOutput?.(validatedParams);
11482
+ }
11483
+ case CLIENT_METHODS.terminal_release: {
11484
+ const validatedParams = releaseTerminalRequestSchema.parse(params);
11485
+ const result = await client.releaseTerminal?.(validatedParams);
11486
+ return result ?? {};
11487
+ }
11488
+ case CLIENT_METHODS.terminal_wait_for_exit: {
11489
+ const validatedParams = waitForTerminalExitRequestSchema.parse(params);
11490
+ return client.waitForTerminalExit?.(validatedParams);
11491
+ }
11492
+ case CLIENT_METHODS.terminal_kill: {
11493
+ const validatedParams = killTerminalCommandRequestSchema.parse(params);
11494
+ const result = await client.killTerminal?.(validatedParams);
11495
+ return result ?? {};
11496
+ }
11497
+ default:
11498
+ if (method.startsWith("_")) {
11499
+ const customMethod = method.substring(1);
11500
+ if (!client.extMethod) {
11501
+ throw RequestError.methodNotFound(method);
11502
+ }
11503
+ return client.extMethod(customMethod, params);
11504
+ }
11505
+ throw RequestError.methodNotFound(method);
11506
+ }
11507
+ };
11508
+ const notificationHandler = async (method, params) => {
11509
+ switch (method) {
11510
+ case CLIENT_METHODS.session_update: {
11511
+ const validatedParams = sessionNotificationSchema.parse(params);
11512
+ return client.sessionUpdate(validatedParams);
11513
+ }
11514
+ default:
11515
+ if (method.startsWith("_")) {
11516
+ const customMethod = method.substring(1);
11517
+ if (!client.extNotification) {
11518
+ return;
11519
+ }
11520
+ return client.extNotification(customMethod, params);
11521
+ }
11522
+ throw RequestError.methodNotFound(method);
11523
+ }
11524
+ };
11525
+ this.#connection = new Connection(requestHandler, notificationHandler, stream);
11526
+ }
11527
+ /**
11528
+ * Establishes the connection with a client and negotiates protocol capabilities.
11529
+ *
11530
+ * This method is called once at the beginning of the connection to:
11531
+ * - Negotiate the protocol version to use
11532
+ * - Exchange capability information between client and agent
11533
+ * - Determine available authentication methods
11534
+ *
11535
+ * The agent should respond with its supported protocol version and capabilities.
11536
+ *
11537
+ * See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/initialization)
11538
+ */
11539
+ async initialize(params) {
11540
+ return await this.#connection.sendRequest(AGENT_METHODS.initialize, params);
11541
+ }
11542
+ /**
11543
+ * Creates a new conversation session with the agent.
11544
+ *
11545
+ * Sessions represent independent conversation contexts with their own history and state.
11546
+ *
11547
+ * The agent should:
11548
+ * - Create a new session context
11549
+ * - Connect to any specified MCP servers
11550
+ * - Return a unique session ID for future requests
11551
+ *
11552
+ * May return an `auth_required` error if the agent requires authentication.
11553
+ *
11554
+ * See protocol docs: [Session Setup](https://agentclientprotocol.com/protocol/session-setup)
11555
+ */
11556
+ async newSession(params) {
11557
+ return await this.#connection.sendRequest(AGENT_METHODS.session_new, params);
11558
+ }
11559
+ /**
11560
+ * Loads an existing session to resume a previous conversation.
11561
+ *
11562
+ * This method is only available if the agent advertises the `loadSession` capability.
11563
+ *
11564
+ * The agent should:
11565
+ * - Restore the session context and conversation history
11566
+ * - Connect to the specified MCP servers
11567
+ * - Stream the entire conversation history back to the client via notifications
11568
+ *
11569
+ * See protocol docs: [Loading Sessions](https://agentclientprotocol.com/protocol/session-setup#loading-sessions)
11570
+ */
11571
+ async loadSession(params) {
11572
+ return await this.#connection.sendRequest(AGENT_METHODS.session_load, params) ?? {};
11573
+ }
11574
+ /**
11575
+ * Sets the operational mode for a session.
11576
+ *
11577
+ * Allows switching between different agent modes (e.g., "ask", "architect", "code")
11578
+ * that affect system prompts, tool availability, and permission behaviors.
11579
+ *
11580
+ * The mode must be one of the modes advertised in `availableModes` during session
11581
+ * creation or loading. Agents may also change modes autonomously and notify the
11582
+ * client via `current_mode_update` notifications.
11583
+ *
11584
+ * This method can be called at any time during a session, whether the Agent is
11585
+ * idle or actively generating a turn.
11586
+ *
11587
+ * See protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)
11588
+ */
11589
+ async setSessionMode(params) {
11590
+ return await this.#connection.sendRequest(AGENT_METHODS.session_set_mode, params) ?? {};
11591
+ }
11592
+ /**
11593
+ * **UNSTABLE**
11594
+ *
11595
+ * This capability is not part of the spec yet, and may be removed or changed at any point.
11596
+ *
11597
+ * Select a model for a given session.
11598
+ */
11599
+ async setSessionModel(params) {
11600
+ return await this.#connection.sendRequest(AGENT_METHODS.session_set_model, params) ?? {};
11601
+ }
11602
+ /**
11603
+ * Authenticates the client using the specified authentication method.
11604
+ *
11605
+ * Called when the agent requires authentication before allowing session creation.
11606
+ * The client provides the authentication method ID that was advertised during initialization.
11607
+ *
11608
+ * After successful authentication, the client can proceed to create sessions with
11609
+ * `newSession` without receiving an `auth_required` error.
11610
+ *
11611
+ * See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/initialization)
11612
+ */
11613
+ async authenticate(params) {
11614
+ return await this.#connection.sendRequest(AGENT_METHODS.authenticate, params) ?? {};
11615
+ }
11616
+ /**
11617
+ * Processes a user prompt within a session.
11618
+ *
11619
+ * This method handles the whole lifecycle of a prompt:
11620
+ * - Receives user messages with optional context (files, images, etc.)
11621
+ * - Processes the prompt using language models
11622
+ * - Reports language model content and tool calls to the Clients
11623
+ * - Requests permission to run tools
11624
+ * - Executes any requested tool calls
11625
+ * - Returns when the turn is complete with a stop reason
11626
+ *
11627
+ * See protocol docs: [Prompt Turn](https://agentclientprotocol.com/protocol/prompt-turn)
11628
+ */
11629
+ async prompt(params) {
11630
+ return await this.#connection.sendRequest(AGENT_METHODS.session_prompt, params);
11631
+ }
11632
+ /**
11633
+ * Cancels ongoing operations for a session.
11634
+ *
11635
+ * This is a notification sent by the client to cancel an ongoing prompt turn.
11636
+ *
11637
+ * Upon receiving this notification, the Agent SHOULD:
11638
+ * - Stop all language model requests as soon as possible
11639
+ * - Abort all tool call invocations in progress
11640
+ * - Send any pending `session/update` notifications
11641
+ * - Respond to the original `session/prompt` request with `StopReason::Cancelled`
11642
+ *
11643
+ * See protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/prompt-turn#cancellation)
11644
+ */
11645
+ async cancel(params) {
11646
+ return await this.#connection.sendNotification(AGENT_METHODS.session_cancel, params);
11647
+ }
11648
+ /**
11649
+ * Extension method
11650
+ *
11651
+ * Allows the Client to send an arbitrary request that is not part of the ACP spec.
11652
+ */
11653
+ async extMethod(method, params) {
11654
+ return await this.#connection.sendRequest(`_${method}`, params);
11655
+ }
11656
+ /**
11657
+ * Extension notification
11658
+ *
11659
+ * Allows the Client to send an arbitrary notification that is not part of the ACP spec.
11660
+ */
11661
+ async extNotification(method, params) {
11662
+ return await this.#connection.sendNotification(`_${method}`, params);
11663
+ }
11664
+ };
11665
+ var Connection = class {
11666
+ #pendingResponses = /* @__PURE__ */ new Map();
11667
+ #nextRequestId = 0;
11668
+ #requestHandler;
11669
+ #notificationHandler;
11670
+ #stream;
11671
+ #writeQueue = Promise.resolve();
11672
+ constructor(requestHandler, notificationHandler, stream) {
11673
+ this.#requestHandler = requestHandler;
11674
+ this.#notificationHandler = notificationHandler;
11675
+ this.#stream = stream;
11676
+ this.#receive();
11677
+ }
11678
+ async #receive() {
11679
+ const reader = this.#stream.readable.getReader();
11680
+ try {
11681
+ while (true) {
11682
+ const { value: message, done } = await reader.read();
11683
+ if (done) {
11684
+ break;
11685
+ }
11686
+ if (!message) {
11687
+ continue;
11688
+ }
11689
+ try {
11690
+ this.#processMessage(message);
11691
+ } catch (err) {
11692
+ console.error("Unexpected error during message processing:", message, err);
11693
+ if ("id" in message && message.id !== void 0) {
11694
+ this.#sendMessage({
11695
+ jsonrpc: "2.0",
11696
+ id: message.id,
11697
+ error: {
11698
+ code: -32700,
11699
+ message: "Parse error"
11700
+ }
11701
+ });
11702
+ }
11703
+ }
11704
+ }
11705
+ } finally {
11706
+ reader.releaseLock();
11707
+ }
11708
+ }
11709
+ async #processMessage(message) {
11710
+ if ("method" in message && "id" in message) {
11711
+ const response = await this.#tryCallRequestHandler(message.method, message.params);
11712
+ if ("error" in response) {
11713
+ console.error("Error handling request", message, response.error);
11714
+ }
11715
+ await this.#sendMessage({
11716
+ jsonrpc: "2.0",
11717
+ id: message.id,
11718
+ ...response
11719
+ });
11720
+ } else if ("method" in message) {
11721
+ const response = await this.#tryCallNotificationHandler(message.method, message.params);
11722
+ if ("error" in response) {
11723
+ console.error("Error handling notification", message, response.error);
11724
+ }
11725
+ } else if ("id" in message) {
11726
+ this.#handleResponse(message);
11727
+ } else {
11728
+ console.error("Invalid message", { message });
11729
+ }
11730
+ }
11731
+ async #tryCallRequestHandler(method, params) {
11732
+ try {
11733
+ const result = await this.#requestHandler(method, params);
11734
+ return { result: result ?? null };
11735
+ } catch (error) {
11736
+ if (error instanceof RequestError) {
11737
+ return error.toResult();
11738
+ }
11739
+ if (error instanceof z6.ZodError) {
11740
+ return RequestError.invalidParams(error.format()).toResult();
11741
+ }
11742
+ let details;
11743
+ if (error instanceof Error) {
11744
+ details = error.message;
11745
+ } else if (typeof error === "object" && error != null && "message" in error && typeof error.message === "string") {
11746
+ details = error.message;
11747
+ }
11748
+ try {
11749
+ return RequestError.internalError(details ? JSON.parse(details) : {}).toResult();
11750
+ } catch {
11751
+ return RequestError.internalError({ details }).toResult();
11752
+ }
11753
+ }
11754
+ }
11755
+ async #tryCallNotificationHandler(method, params) {
11756
+ try {
11757
+ await this.#notificationHandler(method, params);
11758
+ return { result: null };
11759
+ } catch (error) {
11760
+ if (error instanceof RequestError) {
11761
+ return error.toResult();
11762
+ }
11763
+ if (error instanceof z6.ZodError) {
11764
+ return RequestError.invalidParams(error.format()).toResult();
11765
+ }
11766
+ let details;
11767
+ if (error instanceof Error) {
11768
+ details = error.message;
11769
+ } else if (typeof error === "object" && error != null && "message" in error && typeof error.message === "string") {
11770
+ details = error.message;
11771
+ }
11772
+ try {
11773
+ return RequestError.internalError(details ? JSON.parse(details) : {}).toResult();
11774
+ } catch {
11775
+ return RequestError.internalError({ details }).toResult();
11776
+ }
11777
+ }
11778
+ }
11779
+ #handleResponse(response) {
11780
+ const pendingResponse = this.#pendingResponses.get(response.id);
11781
+ if (pendingResponse) {
11782
+ if ("result" in response) {
11783
+ pendingResponse.resolve(response.result);
11784
+ } else if ("error" in response) {
11785
+ pendingResponse.reject(response.error);
11786
+ }
11787
+ this.#pendingResponses.delete(response.id);
11788
+ } else {
11789
+ console.error("Got response to unknown request", response.id);
11790
+ }
11791
+ }
11792
+ async sendRequest(method, params) {
11793
+ const id = this.#nextRequestId++;
11794
+ const responsePromise = new Promise((resolve3, reject) => {
11795
+ this.#pendingResponses.set(id, { resolve: resolve3, reject });
11796
+ });
11797
+ await this.#sendMessage({ jsonrpc: "2.0", id, method, params });
11798
+ return responsePromise;
11799
+ }
11800
+ async sendNotification(method, params) {
11801
+ await this.#sendMessage({ jsonrpc: "2.0", method, params });
11802
+ }
11803
+ async #sendMessage(message) {
11804
+ this.#writeQueue = this.#writeQueue.then(async () => {
11805
+ const writer = this.#stream.writable.getWriter();
11806
+ try {
11807
+ await writer.write(message);
11808
+ } finally {
11809
+ writer.releaseLock();
11810
+ }
11811
+ }).catch((error) => {
11812
+ console.error("ACP write error:", error);
11813
+ });
11814
+ return this.#writeQueue;
11815
+ }
11816
+ };
11817
+ var RequestError = class _RequestError extends Error {
11818
+ code;
11819
+ data;
11820
+ constructor(code, message, data) {
11821
+ super(message);
11822
+ this.code = code;
11823
+ this.name = "RequestError";
11824
+ this.data = data;
11825
+ }
11826
+ /**
11827
+ * Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.
11828
+ */
11829
+ static parseError(data) {
11830
+ return new _RequestError(-32700, "Parse error", data);
11831
+ }
11832
+ /**
11833
+ * The JSON sent is not a valid Request object.
11834
+ */
11835
+ static invalidRequest(data) {
11836
+ return new _RequestError(-32600, "Invalid request", data);
11837
+ }
11838
+ /**
11839
+ * The method does not exist / is not available.
11840
+ */
11841
+ static methodNotFound(method) {
11842
+ return new _RequestError(-32601, "Method not found", { method });
11843
+ }
11844
+ /**
11845
+ * Invalid method parameter(s).
11846
+ */
11847
+ static invalidParams(data) {
11848
+ return new _RequestError(-32602, "Invalid params", data);
11849
+ }
11850
+ /**
11851
+ * Internal JSON-RPC error.
11852
+ */
11853
+ static internalError(data) {
11854
+ return new _RequestError(-32603, "Internal error", data);
11855
+ }
11856
+ /**
11857
+ * Authentication required.
11858
+ */
11859
+ static authRequired(data) {
11860
+ return new _RequestError(-32e3, "Authentication required", data);
11861
+ }
11862
+ /**
11863
+ * Resource, such as a file, was not found
11864
+ */
11865
+ static resourceNotFound(uri) {
11866
+ return new _RequestError(-32002, "Resource not found", uri && { uri });
11867
+ }
11868
+ toResult() {
11869
+ return {
11870
+ error: {
11871
+ code: this.code,
11872
+ message: this.message,
11873
+ data: this.data
11874
+ }
11875
+ };
11876
+ }
11877
+ toErrorResponse() {
11878
+ return {
11879
+ code: this.code,
11880
+ message: this.message,
11881
+ data: this.data
11882
+ };
11883
+ }
11884
+ };
11885
+
11886
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__acp-ai-provider/src/language-model.js
11887
+ import { spawn as spawn2 } from "node:child_process";
11888
+ import process9 from "node:process";
11889
+ import { Readable as Readable2, Writable } from "node:stream";
11890
+ import z7 from "zod";
11891
+
11892
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__acp-ai-provider/src/format-tool-error.js
11893
+ function formatToolError(toolResult) {
11894
+ if (!toolResult || toolResult.length === 0) return "Unknown tool error";
11895
+ const parts = [];
11896
+ for (const blk of toolResult) {
11897
+ if (blk.type === "content") {
11898
+ if (blk.content.type === "text") {
11899
+ parts.push(blk.content.text);
11900
+ }
11901
+ }
11902
+ }
11903
+ return parts.join("\n");
11904
+ }
11905
+
11906
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__acp-ai-provider/src/tool-proxy/tool-proxy-host.js
11907
+ import { createServer as createServer2 } from "node:net";
11908
+
11909
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__acp-ai-provider/src/tool-proxy/json-rpc.js
11910
+ function createResponse(id, result) {
11911
+ return {
11912
+ jsonrpc: "2.0",
11913
+ id,
11914
+ result
11915
+ };
11916
+ }
11917
+ function createErrorResponse(id, code, message, data) {
11918
+ const error = {
11919
+ code,
11920
+ message
11921
+ };
11922
+ if (data !== void 0) {
11923
+ error.data = data;
11924
+ }
11925
+ return {
11926
+ jsonrpc: "2.0",
11927
+ id,
11928
+ error
11929
+ };
11930
+ }
11931
+ function parseMessage(line) {
11932
+ try {
11933
+ const parsed = JSON.parse(line);
11934
+ if (parsed.jsonrpc !== "2.0") return null;
11935
+ return parsed;
11936
+ } catch {
11937
+ return null;
11938
+ }
11939
+ }
11940
+ function serializeMessage2(message) {
11941
+ return JSON.stringify(message);
11942
+ }
11943
+
11944
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__acp-ai-provider/src/tool-proxy/types.js
11945
+ var JsonRpcErrorCode = {
11946
+ PARSE_ERROR: -32700,
11947
+ INVALID_REQUEST: -32600,
11948
+ METHOD_NOT_FOUND: -32601,
11949
+ INVALID_PARAMS: -32602,
11950
+ INTERNAL_ERROR: -32603
11951
+ };
11952
+ var ProxyMethod = {
11953
+ // Host -> Proxy
11954
+ REGISTER_TOOLS: "registerTools",
11955
+ // Proxy -> Host
11956
+ CALL_HANDLER: "callHandler"
11957
+ };
11958
+
11959
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__acp-ai-provider/src/tool-proxy/tool-proxy-runtime.js
11960
+ var RUNTIME_CODE = `
11961
+ /* MCP Protocol Version 2024-11-05 */
11962
+ const isDeno=typeof Deno!=="undefined",MCP_VER="2024-11-05";
11963
+ let tools=[],host=null,pending=new Map,buf="",hbuf="",rid=0;
11964
+ const env=k=>isDeno?Deno.env.get(k):process.env[k];
11965
+ const write=async m=>{
11966
+ const s=JSON.stringify(m)+"\\n";
11967
+ if(isDeno)await Deno.stdout.write(new TextEncoder().encode(s));
11968
+ else process.stdout.write(s);
11969
+ };
11970
+ const send=(id,r,e)=>write({jsonrpc:"2.0",id,...(e?{error:e}:{result:r})});
11971
+ const hostReq=(m,p)=>new Promise((res,rej)=>{
11972
+ const id="r-"+ ++rid;
11973
+ const s=JSON.stringify({jsonrpc:"2.0",id,method:m,params:p})+"\\n";
11974
+ if(isDeno)host.write(new TextEncoder().encode(s));
11975
+ else host.write(s);
11976
+ const t=setTimeout(()=>{pending.delete(id);rej(new Error("timeout"))},30000);
11977
+ pending.set(id,{resolve:v=>{clearTimeout(t);res(v)},reject:e=>{clearTimeout(t);rej(e)}});
11978
+ });
11979
+ const init=async()=>{
11980
+ const p=parseInt(env("ACP_TOOL_PROXY_PORT")||"0",10);
11981
+ if(p){
11982
+ if(isDeno){
11983
+ host=await Deno.connect({hostname:"127.0.0.1",port:p});
11984
+ (async()=>{
11985
+ const d=new TextDecoder(),b=new Uint8Array(65536);
11986
+ while(true){const n=await host.read(b);if(!n)break;
11987
+ hbuf+=d.decode(b.subarray(0,n));let ls=hbuf.split("\\n");hbuf=ls.pop();
11988
+ for(let l of ls)if(l.trim())onHostMsg(l)}})();
11989
+ }else{
11990
+ host=require("net").createConnection({host:"127.0.0.1",port:p});
11991
+ await new Promise(r=>host.on("connect",r));
11992
+ host.on("data",d=>{hbuf+=d;let ls=hbuf.split("\\n");hbuf=ls.pop();
11993
+ for(let l of ls)if(l.trim())onHostMsg(l)});
11994
+ }
11995
+ try{tools=await hostReq("getTools")}catch(e){
11996
+ const m="Failed to get tools: "+e.message+"\\n";
11997
+ if(isDeno)Deno.stderr.write(new TextEncoder().encode(m));
11998
+ else process.stderr.write(m);
11999
+ }
12000
+ }
12001
+ };
12002
+ const onHostMsg=l=>{try{let r=JSON.parse(l),h=pending.get(r.id);
12003
+ if(h){pending.delete(r.id);r.error?h.reject(new Error(r.error.message)):h.resolve(r.result)}}catch{}};
12004
+ const handle=async l=>{let m;try{m=JSON.parse(l)}catch{return}if(m.jsonrpc!=="2.0")return;
12005
+ if(m.method==="initialize")send(m.id,{protocolVersion:MCP_VER,capabilities:{tools:{}},serverInfo:{name:"proxy",version:"1.0"}});
12006
+ else if(m.method==="notifications/initialized");
12007
+ else if(m.method==="tools/list")send(m.id,{tools:tools.map(t=>({name:t.name,description:t.description,inputSchema:t.inputSchema}))});
12008
+ else if(m.method==="tools/call"){let p=m.params,t=tools.find(x=>x.name===p.name);
12009
+ if(!t)send(m.id,null,{code:-32601,message:"Not found"});
12010
+ else try{let r=await hostReq("callHandler",{name:p.name,args:p.arguments||{}});send(m.id,r)}
12011
+ catch(e){send(m.id,{content:[{type:"text",text:"Error: "+e.message}],isError:true})}}
12012
+ else send(m.id,null,{code:-32601,message:"Unknown"});
12013
+ };
12014
+ init().then(async()=>{
12015
+ if(isDeno){
12016
+ const d=new TextDecoder(),b=new Uint8Array(65536);
12017
+ while(true){const n=await Deno.stdin.read(b);if(!n)break;
12018
+ buf+=d.decode(b.subarray(0,n));let ls=buf.split("\\n");buf=ls.pop();for(let l of ls)if(l.trim())handle(l)}
12019
+ }else{
12020
+ process.stdin.setEncoding("utf8");
12021
+ process.stdin.on("data",c=>{buf+=c;let ls=buf.split("\\n");buf=ls.pop();for(let l of ls)if(l.trim())handle(l)});
12022
+ }
12023
+ });
12024
+ `.trim().replace(/\n/g, "");
12025
+
12026
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__acp-ai-provider/src/tool-proxy/tool-proxy-host.js
12027
+ var ToolProxyHost = class {
12028
+ server = null;
12029
+ connections = [];
12030
+ tools = /* @__PURE__ */ new Map();
12031
+ serverName;
12032
+ port = 0;
12033
+ constructor(name = "acp-tool-proxy") {
12034
+ this.serverName = name;
12035
+ }
12036
+ /**
12037
+ * Register an AI SDK tool to be exposed through the proxy
12038
+ */
12039
+ registerTool(name, tool3) {
12040
+ this.tools.set(name, tool3);
12041
+ }
12042
+ /**
12043
+ * Register multiple tools at once
12044
+ */
12045
+ registerTools(tools) {
12046
+ for (const [name, tool3] of Object.entries(tools)) {
12047
+ this.registerTool(name, tool3);
12048
+ }
12049
+ }
12050
+ /**
12051
+ * Get tool definitions for the runtime
12052
+ */
12053
+ getToolDefinitions() {
12054
+ const definitions = [];
12055
+ for (const [name, tool3] of this.tools.entries()) {
12056
+ definitions.push({
12057
+ name,
12058
+ description: tool3.description || `Tool: ${name}`,
12059
+ // inputSchema from Tool can be Zod or JSON schema, cast to JSON schema format
12060
+ inputSchema: tool3.inputSchema || {
12061
+ type: "object",
12062
+ properties: {}
12063
+ }
12064
+ });
12065
+ }
12066
+ return definitions;
12067
+ }
12068
+ /**
12069
+ * Start TCP server and return MCP server config for ACP
12070
+ */
12071
+ async start() {
12072
+ if (!this.server) {
12073
+ await this.startServer();
12074
+ }
12075
+ return this.getServerConfig();
12076
+ }
12077
+ /**
12078
+ * Get MCP server configuration
12079
+ */
12080
+ getServerConfig() {
12081
+ return {
12082
+ name: this.serverName,
12083
+ command: "node",
12084
+ args: [
12085
+ "-e",
12086
+ RUNTIME_CODE
12087
+ ],
12088
+ env: [
12089
+ {
12090
+ name: "ACP_TOOL_PROXY_PORT",
12091
+ value: String(this.port)
12092
+ }
12093
+ ]
12094
+ };
12095
+ }
12096
+ /**
12097
+ * Start TCP server to receive tool execution requests
12098
+ */
12099
+ startServer() {
12100
+ return new Promise((resolve3, reject) => {
12101
+ this.server = createServer2((socket) => {
12102
+ this.handleConnection(socket);
12103
+ });
12104
+ this.server.on("error", (err) => {
12105
+ reject(err);
12106
+ });
12107
+ this.server.listen(0, "127.0.0.1", () => {
12108
+ const address = this.server.address();
12109
+ if (typeof address === "object" && address) {
12110
+ this.port = address.port;
12111
+ resolve3();
12112
+ } else {
12113
+ reject(new Error("Failed to get server address"));
12114
+ }
12115
+ });
12116
+ });
12117
+ }
12118
+ /**
12119
+ * Handle incoming connection from runtime
12120
+ */
12121
+ handleConnection(socket) {
12122
+ this.connections.push(socket);
12123
+ let buffer = "";
12124
+ socket.on("data", (data) => {
12125
+ buffer += data.toString();
12126
+ const lines = buffer.split("\n");
12127
+ buffer = lines.pop() || "";
12128
+ for (const line of lines) {
12129
+ if (!line.trim()) continue;
12130
+ const message = parseMessage(line);
12131
+ if (!message) continue;
12132
+ if ("method" in message) {
12133
+ this.handleRequest(socket, message).catch((err) => console.error("[ToolProxy] Error handling request:", err));
12134
+ }
12135
+ }
12136
+ });
12137
+ socket.on("close", () => {
12138
+ this.connections = this.connections.filter((c) => c !== socket);
12139
+ });
12140
+ socket.on("error", (err) => {
12141
+ console.error("[ToolProxy] Socket error:", err);
12142
+ });
12143
+ }
12144
+ /**
12145
+ * Handle JSON-RPC request from runtime
12146
+ */
12147
+ async handleRequest(socket, request) {
12148
+ try {
12149
+ if (request.method === ProxyMethod.CALL_HANDLER) {
12150
+ const params = request.params;
12151
+ const tool3 = this.tools.get(params.name);
12152
+ if (!tool3) {
12153
+ this.sendResponse(socket, createErrorResponse(request.id, JsonRpcErrorCode.METHOD_NOT_FOUND, `Tool not found: ${params.name}`));
12154
+ return;
12155
+ }
12156
+ if (!tool3.execute) {
12157
+ this.sendResponse(socket, createErrorResponse(request.id, JsonRpcErrorCode.INTERNAL_ERROR, `Tool has no execute function: ${params.name}`));
12158
+ return;
12159
+ }
12160
+ const result = await tool3.execute?.(params.args, {
12161
+ toolCallId: params.name,
12162
+ messages: []
12163
+ });
12164
+ const toolResult = {
12165
+ content: [
12166
+ {
12167
+ type: "text",
12168
+ text: typeof result === "string" ? result : JSON.stringify(result)
12169
+ }
12170
+ ]
12171
+ };
12172
+ this.sendResponse(socket, createResponse(request.id, toolResult));
12173
+ } else if (request.method === "getTools") {
12174
+ const definitions = this.getToolDefinitions();
12175
+ this.sendResponse(socket, createResponse(request.id, definitions));
12176
+ } else {
12177
+ this.sendResponse(socket, createErrorResponse(request.id, JsonRpcErrorCode.METHOD_NOT_FOUND, `Unknown method: ${request.method}`));
12178
+ }
12179
+ } catch (error) {
12180
+ this.sendResponse(socket, createErrorResponse(request.id, JsonRpcErrorCode.INTERNAL_ERROR, error instanceof Error ? error.message : String(error)));
12181
+ }
12182
+ }
12183
+ /**
12184
+ * Send response to runtime
12185
+ */
12186
+ sendResponse(socket, response) {
12187
+ socket.write(serializeMessage2(response) + "\n");
12188
+ }
12189
+ /**
12190
+ * Stop the TCP server
12191
+ */
12192
+ stop() {
12193
+ for (const socket of this.connections) {
12194
+ socket.destroy();
12195
+ }
12196
+ this.connections = [];
12197
+ if (this.server) {
12198
+ this.server.close();
12199
+ this.server = null;
12200
+ }
12201
+ this.port = 0;
12202
+ }
12203
+ };
12204
+
12205
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__acp-ai-provider/src/acp-tool.js
12206
+ import { jsonSchema as jsonSchema3, tool as tool2 } from "ai";
12207
+ var ACP_PROVIDER_AGENT_DYNAMIC_TOOL_NAME = "acp.acp_provider_agent_dynamic_tool";
12208
+ var executeRegistry = /* @__PURE__ */ new Map();
12209
+ function getACPDynamicTool() {
12210
+ return {
12211
+ [ACP_PROVIDER_AGENT_DYNAMIC_TOOL_NAME]: tool2({
12212
+ type: "provider-defined",
12213
+ id: ACP_PROVIDER_AGENT_DYNAMIC_TOOL_NAME,
12214
+ name: ACP_PROVIDER_AGENT_DYNAMIC_TOOL_NAME,
12215
+ args: {},
12216
+ inputSchema: jsonSchema3({})
12217
+ })
12218
+ };
12219
+ }
12220
+ function getExecuteByName(name) {
12221
+ return executeRegistry.get(name);
12222
+ }
12223
+ function hasRegisteredExecute(name) {
12224
+ return executeRegistry.has(name);
12225
+ }
12226
+
12227
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__acp-ai-provider/src/utils.js
12228
+ function extractBase64Data(data) {
12229
+ return data.includes(",") ? data.split(",")[1] : data;
12230
+ }
12231
+
12232
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__acp-ai-provider/src/convert-utils.js
12233
+ import { asSchema } from "ai";
12234
+ function convertAiSdkMessagesToAcp(options, isFreshSession) {
12235
+ const messages = !isFreshSession ? options.prompt.filter((m) => m.role === "user").slice(-1) : options.prompt;
12236
+ const contentBlocks = [];
12237
+ for (const msg of messages) {
12238
+ let prefix = "";
12239
+ if (msg.role === "system") prefix = "System: ";
12240
+ else if (msg.role === "assistant") prefix = "Assistant: ";
12241
+ else if (msg.role === "tool") prefix = "Result: ";
12242
+ if (Array.isArray(msg.content)) {
12243
+ let isFirst = true;
12244
+ for (const part of msg.content) {
12245
+ if (part.type === "text") {
12246
+ const text = isFirst ? `${prefix}${part.text} ` : part.text;
12247
+ contentBlocks.push({
12248
+ type: "text",
12249
+ text
12250
+ });
12251
+ isFirst = false;
12252
+ } else if (part.type === "tool-call") {
12253
+ const toolCallText = `[Tool Call: ${part.toolName}(${JSON.stringify(part.input)})]`;
12254
+ const text = isFirst ? `${prefix}${toolCallText} ` : toolCallText;
12255
+ contentBlocks.push({
12256
+ type: "text",
12257
+ text
12258
+ });
12259
+ isFirst = false;
12260
+ } else if (part.type === "tool-result") {
12261
+ const resultData = part.result ?? part.output;
12262
+ const resultText = JSON.stringify(resultData) ?? "null";
12263
+ const text = isFirst ? `${prefix}${resultText} ` : resultText;
12264
+ contentBlocks.push({
12265
+ type: "text",
12266
+ text
12267
+ });
12268
+ isFirst = false;
12269
+ } else if (part.type === "file" && typeof part.data === "string") {
12270
+ const type = part.mediaType.startsWith("image/") ? "image" : part.mediaType.startsWith("audio/") ? "audio" : null;
12271
+ if (type) {
12272
+ contentBlocks.push({
12273
+ type,
12274
+ mimeType: part.mediaType,
12275
+ data: extractBase64Data(part.data)
12276
+ });
12277
+ }
12278
+ }
12279
+ }
12280
+ } else if (typeof msg.content === "string") {
12281
+ contentBlocks.push({
12282
+ type: "text",
12283
+ text: `${prefix}${msg.content} `
12284
+ });
12285
+ }
12286
+ }
12287
+ return contentBlocks;
12288
+ }
12289
+ function extractACPTools(tools, prepared = true) {
12290
+ const acpTools2 = [];
12291
+ if (!tools) {
12292
+ return acpTools2;
12293
+ }
12294
+ const toolsArray = Array.isArray(tools) ? tools : Object.entries(tools).map(([name, tool3]) => ({
12295
+ type: "function",
12296
+ name,
12297
+ ...tool3
12298
+ }));
12299
+ for (const t of toolsArray) {
12300
+ if (t.type === "function") {
12301
+ const toolWithSchema = t;
12302
+ const toolInputSchema = toolWithSchema.inputSchema;
12303
+ if (hasRegisteredExecute(t.name) && toolInputSchema) {
12304
+ const execute = getExecuteByName(t.name);
12305
+ if (execute) {
12306
+ acpTools2.push({
12307
+ ...t,
12308
+ name: t.name,
12309
+ inputSchema: prepared ? toolInputSchema : asSchema(toolInputSchema).jsonSchema,
12310
+ execute
12311
+ });
12312
+ }
12313
+ }
12314
+ }
12315
+ }
12316
+ return acpTools2;
12317
+ }
12318
+
12319
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__acp-ai-provider/src/language-model.js
12320
+ var ACP_PROVIDER_AGENT_DYNAMIC_TOOL_NAME2 = "acp.acp_provider_agent_dynamic_tool";
12321
+ var providerAgentDynamicToolSchema = z7.object({
12322
+ toolCallId: z7.string().describe("The unique ID of the tool call."),
12323
+ toolName: z7.string().describe("The name of the tool being called."),
12324
+ args: z7.record(z7.unknown()).describe("The input arguments for the tool call.")
12325
+ });
12326
+ var ACPAISDKClient = class {
12327
+ onSessionUpdateCallback;
12328
+ onPermissionRequestCallback;
12329
+ setSessionUpdateHandler(handler) {
12330
+ this.onSessionUpdateCallback = handler;
12331
+ }
12332
+ setPermissionRequestHandler(handler) {
12333
+ this.onPermissionRequestCallback = handler;
12334
+ }
12335
+ sessionUpdate(params) {
12336
+ if (this.onSessionUpdateCallback) {
12337
+ this.onSessionUpdateCallback(params);
12338
+ }
12339
+ return Promise.resolve();
12340
+ }
12341
+ async requestPermission(params) {
12342
+ if (this.onPermissionRequestCallback) {
12343
+ return await this.onPermissionRequestCallback(params);
12344
+ }
12345
+ return {
12346
+ outcome: {
12347
+ outcome: "selected",
12348
+ optionId: params.options[0]?.optionId || "allow"
12349
+ }
12350
+ };
12351
+ }
12352
+ writeTextFile(_params) {
12353
+ throw new Error("File operations not implemented in language model client");
12354
+ }
12355
+ readTextFile(_params) {
12356
+ throw new Error("File operations not implemented in language model client");
12357
+ }
12358
+ };
12359
+ var ACPLanguageModel = class {
12360
+ specificationVersion = "v2";
12361
+ provider = "acp";
12362
+ modelId;
12363
+ modeId;
12364
+ supportedUrls = {};
12365
+ config;
12366
+ agentProcess = null;
12367
+ connection = null;
12368
+ sessionId = null;
12369
+ sessionResponse = null;
12370
+ client = null;
12371
+ currentModelId = null;
12372
+ currentModeId = null;
12373
+ isFreshSession = true;
12374
+ // State for managing stream conversion
12375
+ textBlockIndex = 0;
12376
+ thinkBlockIndex = 0;
12377
+ currentTextId = null;
12378
+ currentThinkingId = null;
12379
+ toolCallsMap = /* @__PURE__ */ new Map();
12380
+ // Tool proxy for host-side tool execution
12381
+ toolProxyHost = null;
12382
+ constructor(modelId, modeId, config) {
12383
+ this.modelId = modelId;
12384
+ this.modeId = modeId;
12385
+ this.config = config;
12386
+ }
12387
+ /**
12388
+ * Resets the internal state used for stream conversion.
12389
+ */
12390
+ resetStreamState() {
12391
+ this.textBlockIndex = 0;
12392
+ this.thinkBlockIndex = 0;
12393
+ this.currentTextId = null;
12394
+ this.currentThinkingId = null;
12395
+ this.toolCallsMap.clear();
12396
+ }
12397
+ /**
12398
+ * Parses a 'tool_call' notification update into a structured object.
12399
+ * Note: We only use rawInput for tool input (content is for UI display).
12400
+ */
12401
+ parseToolCall(update) {
12402
+ if (update.sessionUpdate !== "tool_call") {
12403
+ throw new Error("Invalid update type for parseToolCall");
12404
+ }
12405
+ const toolCallId = update.toolCallId;
12406
+ const toolName = update.title || update.toolCallId;
12407
+ const toolInput = update.rawInput ?? {};
12408
+ return {
12409
+ toolCallId,
12410
+ toolName,
12411
+ toolInput
12412
+ };
12413
+ }
12414
+ /**
12415
+ * Parses a 'tool_call_update' notification update into a structured object.
12416
+ * Note: We only use rawOutput for tool result (content is for UI display).
12417
+ */
12418
+ parseToolResult(update) {
12419
+ if (update.sessionUpdate !== "tool_call_update") {
12420
+ throw new Error("Invalid update type for parseToolResult");
12421
+ }
12422
+ const toolCallId = update.toolCallId;
12423
+ const toolName = update.title || update.toolCallId;
12424
+ const toolResult = update.rawOutput ?? update.content ?? null;
12425
+ const isError2 = update.status === "failed";
12426
+ return {
12427
+ toolCallId,
12428
+ toolName,
12429
+ toolResult,
12430
+ isError: isError2,
12431
+ status: update.status
12432
+ };
12433
+ }
12434
+ /**
12435
+ * Converts AI SDK prompt messages into ACP ContentBlock objects.
12436
+ * When session exists, only extracts the last user message (history is in session).
12437
+ * Prefixes text with role since ACP ContentBlock has no role field.
12438
+ */
12439
+ /**
12440
+ * Ensures the ACP agent process is running and a session is established.
12441
+ * @param acpTools - Tools from streamText options to proxy
12442
+ */
12443
+ /**
12444
+ * Connects to the ACP agent process and initializes the protocol connection.
12445
+ * Does NOT start a session.
12446
+ */
12447
+ async connectClient() {
12448
+ if (this.connection) {
12449
+ return;
12450
+ }
12451
+ if (!this.agentProcess) {
12452
+ const sessionCwd = this.config.session?.cwd || (typeof process9.cwd === "function" ? process9.cwd() : "/");
12453
+ this.agentProcess = spawn2(this.config.command, this.config.args ?? [], {
12454
+ stdio: [
12455
+ "pipe",
12456
+ "pipe",
12457
+ "inherit"
12458
+ ],
12459
+ env: {
12460
+ ...process9.env,
12461
+ ...this.config.env
12462
+ },
12463
+ cwd: sessionCwd
12464
+ });
12465
+ if (!this.agentProcess.stdout || !this.agentProcess.stdin) {
12466
+ throw new Error("Failed to spawn agent process with stdio");
12467
+ }
12468
+ const input = Writable.toWeb(this.agentProcess.stdin);
12469
+ const output = Readable2.toWeb(this.agentProcess.stdout);
12470
+ this.client = new ACPAISDKClient();
12471
+ this.connection = new ClientSideConnection(() => this.client, ndJsonStream(input, output));
12472
+ }
12473
+ if (!this.connection) {
12474
+ throw new Error("Connection not initialized");
12475
+ }
12476
+ const initConfig = {
12477
+ ...this.config.initialize,
12478
+ protocolVersion: this.config.initialize?.protocolVersion ?? PROTOCOL_VERSION,
12479
+ clientCapabilities: this.config.initialize?.clientCapabilities ?? {
12480
+ fs: {
12481
+ readTextFile: false,
12482
+ writeTextFile: false
12483
+ },
12484
+ terminal: false
12485
+ }
12486
+ };
12487
+ const initResult = await this.connection.initialize(initConfig);
12488
+ const validAuthMethods = initResult.authMethods?.find((a) => a.id === this.config.authMethodId)?.id;
12489
+ if ((initResult.authMethods?.length ?? 0) > 0) {
12490
+ if (!this.config.authMethodId || !validAuthMethods) {
12491
+ console.log("[acp-ai-provider] Warning: No authMethodId specified in config, skipping authentication step. If this is not desired, please set one of the authMethodId in the ACPProviderSettings.", JSON.stringify(initResult.authMethods, null, 2));
12492
+ }
12493
+ if (this.config.authMethodId && validAuthMethods) {
12494
+ await this.connection.authenticate({
12495
+ methodId: this.config.authMethodId ?? initResult.authMethods?.[0].id
12496
+ });
12497
+ }
12498
+ }
12499
+ }
12500
+ /**
12501
+ * Starts a new session or updates the existing one.
12502
+ * Assumes connectClient() has been called.
12503
+ */
12504
+ async startSession(acpTools2) {
12505
+ if (!this.connection) {
12506
+ throw new Error("Not connected");
12507
+ }
12508
+ const mcpServers = [
12509
+ ...this.config.session?.mcpServers ?? []
12510
+ ];
12511
+ let toolsAdded = false;
12512
+ if (acpTools2 && acpTools2.length > 0 && !this.toolProxyHost) {
12513
+ console.log("[acp-ai-provider] Setting up tool proxy for client-side tools...", acpTools2.map((t) => t.name));
12514
+ this.toolProxyHost = new ToolProxyHost("acp-ai-sdk-tools");
12515
+ for (const t of acpTools2) {
12516
+ this.toolProxyHost.registerTool(t.name, t);
12517
+ }
12518
+ toolsAdded = true;
12519
+ }
12520
+ if (this.toolProxyHost) {
12521
+ const proxyConfig = await this.toolProxyHost.start();
12522
+ mcpServers.push(proxyConfig);
12523
+ }
12524
+ if (this.sessionId && toolsAdded) {
12525
+ this.sessionResponse = await this.connection.newSession({
12526
+ ...this.config.session,
12527
+ cwd: this.config.session?.cwd ?? process9.cwd(),
12528
+ mcpServers
12529
+ });
12530
+ this.sessionId = this.sessionResponse.sessionId;
12531
+ this.isFreshSession = true;
12532
+ await this.applySessionDelay();
12533
+ return;
12534
+ }
12535
+ if (this.sessionId) {
12536
+ return;
12537
+ }
12538
+ if (this.config.existingSessionId) {
12539
+ await this.connection.loadSession({
12540
+ sessionId: this.config.existingSessionId,
12541
+ cwd: this.config.session?.cwd ?? process9.cwd(),
12542
+ mcpServers
12543
+ });
12544
+ this.sessionId = this.config.existingSessionId;
12545
+ this.sessionResponse = {
12546
+ sessionId: this.config.existingSessionId
12547
+ };
12548
+ this.isFreshSession = false;
12549
+ } else {
12550
+ this.sessionResponse = await this.connection.newSession({
12551
+ ...this.config.session,
12552
+ cwd: this.config.session?.cwd ?? process9.cwd(),
12553
+ mcpServers
12554
+ });
12555
+ this.sessionId = this.sessionResponse.sessionId;
12556
+ this.isFreshSession = true;
12557
+ }
12558
+ const { models, modes } = this.sessionResponse ?? {};
12559
+ if (models?.currentModelId) {
12560
+ this.currentModelId = models.currentModelId;
12561
+ }
12562
+ if (modes?.currentModeId) {
12563
+ this.currentModeId = modes.currentModeId;
12564
+ }
12565
+ if (this.modelId && this.modelId !== this.currentModelId) {
12566
+ await this.setModel(this.modelId);
12567
+ this.currentModelId = this.modelId;
12568
+ }
12569
+ if (this.modeId && this.modeId !== this.currentModeId) {
12570
+ await this.setMode(this.modeId);
12571
+ this.currentModeId = this.modeId;
12572
+ }
12573
+ await this.applySessionDelay();
12574
+ }
12575
+ async applySessionDelay() {
12576
+ if (this.config.sessionDelayMs) {
12577
+ console.log(`[acp-ai-provider] Waiting ${this.config.sessionDelayMs}ms after session setup...`);
12578
+ await new Promise((resolve3) => setTimeout(resolve3, this.config.sessionDelayMs));
12579
+ }
12580
+ }
12581
+ /**
12582
+ * Ensures the ACP agent process is running and a session is established.
12583
+ * @param acpTools - Tools from streamText options to proxy
12584
+ */
12585
+ async ensureConnected(acpTools2) {
12586
+ await this.connectClient();
12587
+ await this.startSession(acpTools2);
12588
+ }
12589
+ /**
12590
+ * Clears connection state. Skips if persistSession is enabled.
12591
+ */
12592
+ cleanup() {
12593
+ if (this.config.persistSession) return;
12594
+ this.forceCleanup();
12595
+ }
12596
+ /**
12597
+ * Returns the current session ID.
12598
+ */
12599
+ getSessionId() {
12600
+ return this.sessionId;
12601
+ }
12602
+ /**
12603
+ * Initializes the session and returns session info (models, modes, meta).
12604
+ * Call this before prompting to discover available options.
12605
+ */
12606
+ /**
12607
+ * Initializes the session and returns session info (models, modes, meta).
12608
+ * Call this before prompting to discover available options.
12609
+ *
12610
+ * @param acpTools - Optional list of tools to register during session initialization.
12611
+ */
12612
+ async initSession(tools) {
12613
+ const acpTools2 = extractACPTools(tools, false);
12614
+ await this.ensureConnected(acpTools2.length > 0 ? acpTools2 : void 0);
12615
+ return this.sessionResponse;
12616
+ }
12617
+ /**
12618
+ * Sets the session mode (e.g., "ask", "plan").
12619
+ */
12620
+ async setMode(modeId) {
12621
+ if (!this.connection || !this.sessionId) {
12622
+ throw new Error("Not connected. Call preconnect() first.");
12623
+ }
12624
+ const availableModes = this.sessionResponse?.modes?.availableModes;
12625
+ if (availableModes) {
12626
+ const foundMode = availableModes.find((m) => m.id === modeId);
12627
+ if (!foundMode) {
12628
+ const availableList = availableModes.map((m) => m.id).join(", ");
12629
+ const currentInfo = this.sessionResponse?.modes?.currentModeId ? ` (Current: "${this.sessionResponse.modes.currentModeId}")` : "";
12630
+ throw new Error(`Mode "${modeId}" is not available${currentInfo}. Available modes: ${availableList}`);
12631
+ }
12632
+ }
12633
+ await this.connection.setSessionMode({
12634
+ sessionId: this.sessionId,
12635
+ modeId
12636
+ });
12637
+ this.currentModeId = modeId;
12638
+ }
12639
+ /**
12640
+ * Sets the session model.
12641
+ */
12642
+ async setModel(modelId) {
12643
+ if (!this.connection || !this.sessionId) {
12644
+ throw new Error("Not connected. Call preconnect() first.");
12645
+ }
12646
+ const { models } = this.sessionResponse ?? {};
12647
+ if (models?.availableModels) {
12648
+ if (!models.availableModels.some((m) => m.modelId === modelId)) {
12649
+ const availableList = models.availableModels.map((m) => m.modelId).join(", ");
12650
+ const currentInfo = this.currentModelId ? ` (Current: "${this.currentModelId}")` : "";
12651
+ throw new Error(`Model "${modelId}" is not available${currentInfo}. Available models: ${availableList}`);
12652
+ }
12653
+ }
12654
+ await this.connection.setSessionModel({
12655
+ sessionId: this.sessionId,
12656
+ modelId
12657
+ });
12658
+ this.currentModelId = modelId;
12659
+ }
12660
+ /**
12661
+ * Forces cleanup regardless of persistSession setting.
12662
+ */
12663
+ forceCleanup() {
12664
+ if (this.toolProxyHost) {
12665
+ this.toolProxyHost.stop();
12666
+ this.toolProxyHost = null;
12667
+ }
12668
+ if (this.agentProcess) {
12669
+ this.agentProcess.kill();
12670
+ this.agentProcess.stdin?.end();
12671
+ this.agentProcess.stdout?.destroy();
12672
+ this.agentProcess = null;
12673
+ }
12674
+ this.connection = null;
12675
+ this.sessionId = null;
12676
+ this.sessionResponse = null;
12677
+ this.client = null;
12678
+ }
12679
+ /**
12680
+ * Emits raw content (plan, diffs, terminals) as raw stream parts.
12681
+ * Plan data is emitted directly, while diffs and terminals are bound to a toolCallId.
12682
+ */
12683
+ emitRawContent(controller, data) {
12684
+ if ("entries" in data) {
12685
+ controller.enqueue({
12686
+ type: "raw",
12687
+ rawValue: JSON.stringify({
12688
+ type: "plan",
12689
+ entries: data.entries
12690
+ })
12691
+ });
12692
+ return;
12693
+ }
12694
+ for (const item of data.content) {
12695
+ if (item.type === "diff" || item.type === "terminal") {
12696
+ controller.enqueue({
12697
+ type: "raw",
12698
+ rawValue: JSON.stringify({
12699
+ ...item,
12700
+ toolCallId: data.toolCallId
12701
+ })
12702
+ });
12703
+ }
12704
+ }
12705
+ }
12706
+ /**
12707
+ * Standardized handler for converting SessionNotifications into
12708
+ * LanguageModelV2StreamPart objects, pushing them onto a stream controller.
12709
+ */
12710
+ handleStreamNotification(controller, notification) {
12711
+ const update = notification.update;
12712
+ switch (update.sessionUpdate) {
12713
+ case "plan":
12714
+ this.emitRawContent(controller, {
12715
+ type: "plan",
12716
+ entries: update.entries
12717
+ });
12718
+ break;
12719
+ case "agent_thought_chunk":
12720
+ if (!this.currentThinkingId) {
12721
+ this.currentThinkingId = `reasoning - ${this.thinkBlockIndex++} `;
12722
+ controller.enqueue({
12723
+ type: "reasoning-start",
12724
+ id: this.currentThinkingId
12725
+ });
12726
+ }
12727
+ controller.enqueue({
12728
+ type: "reasoning-delta",
12729
+ id: this.currentThinkingId,
12730
+ delta: update.content.type === "text" ? update.content.text : ""
12731
+ });
12732
+ break;
12733
+ case "agent_message_chunk":
12734
+ if (this.currentThinkingId) {
12735
+ controller.enqueue({
12736
+ type: "reasoning-end",
12737
+ id: this.currentThinkingId
12738
+ });
12739
+ this.currentThinkingId = null;
12740
+ }
12741
+ if (update.content.type === "text") {
12742
+ const textChunk = update.content.text;
12743
+ if (!this.currentTextId) {
12744
+ this.currentTextId = `text - ${this.textBlockIndex++} `;
12745
+ controller.enqueue({
12746
+ type: "text-start",
12747
+ id: this.currentTextId
12748
+ });
12749
+ }
12750
+ controller.enqueue({
12751
+ type: "text-delta",
12752
+ id: this.currentTextId,
12753
+ delta: textChunk
12754
+ });
12755
+ }
12756
+ break;
12757
+ case "tool_call": {
12758
+ if (this.currentTextId) {
12759
+ controller.enqueue({
12760
+ type: "text-end",
12761
+ id: this.currentTextId
12762
+ });
12763
+ this.currentTextId = null;
12764
+ }
12765
+ if (this.currentThinkingId) {
12766
+ controller.enqueue({
12767
+ type: "reasoning-end",
12768
+ id: this.currentThinkingId
12769
+ });
12770
+ this.currentThinkingId = null;
12771
+ }
12772
+ const { toolCallId, toolName, toolInput } = this.parseToolCall(update);
12773
+ const existingToolCall = this.toolCallsMap.get(toolCallId);
12774
+ const hasInput = toolInput && typeof toolInput === "object" && Object.keys(toolInput).length > 0;
12775
+ if (!existingToolCall) {
12776
+ this.toolCallsMap.set(toolCallId, {
12777
+ index: this.toolCallsMap.size,
12778
+ name: toolName,
12779
+ inputStarted: true,
12780
+ inputAvailable: !!hasInput
12781
+ });
12782
+ controller.enqueue({
12783
+ type: "tool-input-start",
12784
+ id: toolCallId,
12785
+ toolName
12786
+ });
12787
+ if (hasInput) {
12788
+ controller.enqueue({
12789
+ type: "tool-call",
12790
+ toolCallId,
12791
+ toolName: ACP_PROVIDER_AGENT_DYNAMIC_TOOL_NAME2,
12792
+ input: JSON.stringify({
12793
+ toolCallId,
12794
+ toolName,
12795
+ args: toolInput
12796
+ })
12797
+ });
12798
+ }
12799
+ } else if (!existingToolCall.inputAvailable && hasInput) {
12800
+ existingToolCall.inputAvailable = true;
12801
+ if (update.title && existingToolCall.name !== update.title && update.title !== toolCallId) {
12802
+ existingToolCall.name = update.title;
12803
+ }
12804
+ controller.enqueue({
12805
+ type: "tool-call",
12806
+ toolCallId,
12807
+ toolName: ACP_PROVIDER_AGENT_DYNAMIC_TOOL_NAME2,
12808
+ input: JSON.stringify({
12809
+ toolCallId,
12810
+ toolName: existingToolCall.name,
12811
+ args: toolInput
12812
+ })
12813
+ });
12814
+ }
12815
+ break;
12816
+ }
12817
+ case "tool_call_update": {
12818
+ const { toolCallId, toolName, toolResult, isError: isError2, status } = this.parseToolResult(update);
12819
+ let toolInfo = this.toolCallsMap.get(toolCallId);
12820
+ if (status === "in_progress") {
12821
+ if (!toolInfo) {
12822
+ toolInfo = {
12823
+ index: this.toolCallsMap.size,
12824
+ name: toolName,
12825
+ inputStarted: true,
12826
+ inputAvailable: true
12827
+ };
12828
+ this.toolCallsMap.set(toolCallId, toolInfo);
12829
+ controller.enqueue({
12830
+ type: "tool-input-start",
12831
+ id: toolCallId,
12832
+ toolName
12833
+ });
12834
+ }
12835
+ if (!toolInfo.inputAvailable) {
12836
+ toolInfo.inputAvailable = true;
12837
+ if (update.title && toolInfo.name !== update.title && update.title !== toolCallId) {
12838
+ toolInfo.name = update.title;
12839
+ }
12840
+ controller.enqueue({
12841
+ type: "tool-call",
12842
+ toolCallId,
12843
+ toolName: ACP_PROVIDER_AGENT_DYNAMIC_TOOL_NAME2,
12844
+ input: JSON.stringify({
12845
+ toolCallId,
12846
+ toolName: toolInfo.name,
12847
+ args: {}
12848
+ })
12849
+ });
12850
+ }
12851
+ const content2 = update.content ?? [];
12852
+ if (content2.length > 0) {
12853
+ this.emitRawContent(controller, {
12854
+ content: content2,
12855
+ toolCallId
12856
+ });
12857
+ }
12858
+ break;
12859
+ }
12860
+ if (![
12861
+ "completed",
12862
+ "failed"
12863
+ ].includes(status)) {
12864
+ break;
12865
+ }
12866
+ if (!toolInfo) {
12867
+ toolInfo = {
12868
+ index: this.toolCallsMap.size,
12869
+ name: toolName,
12870
+ inputAvailable: true
12871
+ };
12872
+ this.toolCallsMap.set(toolCallId, toolInfo);
12873
+ controller.enqueue({
12874
+ type: "tool-call",
12875
+ toolCallId,
12876
+ toolName: ACP_PROVIDER_AGENT_DYNAMIC_TOOL_NAME2,
12877
+ input: JSON.stringify({
12878
+ toolCallId,
12879
+ toolName
12880
+ })
12881
+ });
12882
+ } else if (!toolInfo.inputAvailable) {
12883
+ toolInfo.inputAvailable = true;
12884
+ if (update.title && toolInfo.name !== update.title && update.title !== toolCallId) {
12885
+ toolInfo.name = update.title;
12886
+ }
12887
+ controller.enqueue({
12888
+ type: "tool-call",
12889
+ toolCallId,
12890
+ toolName: ACP_PROVIDER_AGENT_DYNAMIC_TOOL_NAME2,
12891
+ input: JSON.stringify({
12892
+ toolCallId,
12893
+ toolName: toolInfo.name,
12894
+ args: {}
12895
+ })
12896
+ });
12897
+ }
12898
+ controller.enqueue({
12899
+ type: "tool-result",
12900
+ toolCallId,
12901
+ toolName: ACP_PROVIDER_AGENT_DYNAMIC_TOOL_NAME2,
12902
+ result: toolResult,
12903
+ providerExecuted: true,
12904
+ // https://github.com/vercel/ai/blob/282f062922cb59167dd3a11e3af67cfa0b75f317/packages/ai/src/generate-text/run-tools-transformation.ts#L316
12905
+ ...isError2 && {
12906
+ isError: true,
12907
+ result: new Error(formatToolError(toolResult))
12908
+ }
12909
+ });
12910
+ const content = update.content ?? [];
12911
+ if (content.length > 0) {
12912
+ this.emitRawContent(controller, {
12913
+ content,
12914
+ toolCallId
12915
+ });
12916
+ }
12917
+ break;
12918
+ }
12919
+ }
12920
+ }
12921
+ /**
12922
+ * Implements the non-streaming generation method.
12923
+ */
12924
+ async doGenerate(options) {
12925
+ try {
12926
+ await this.ensureConnected();
12927
+ const promptContent = convertAiSdkMessagesToAcp(options, this.isFreshSession);
12928
+ this.isFreshSession = false;
12929
+ let accumulatedText = "";
12930
+ const toolCalls = [];
12931
+ const toolResults = /* @__PURE__ */ new Map();
12932
+ const mockController = {
12933
+ enqueue: (part) => {
12934
+ switch (part.type) {
12935
+ case "text-delta":
12936
+ accumulatedText += part.delta;
12937
+ break;
12938
+ case "tool-call": {
12939
+ const inputData = JSON.parse(part.input);
12940
+ toolCalls.push({
12941
+ id: part.toolCallId,
12942
+ name: inputData.toolName,
12943
+ input: inputData.args
12944
+ });
12945
+ break;
12946
+ }
12947
+ case "tool-result": {
12948
+ const matchingToolCall = toolCalls.find((tc) => tc.id === part.toolCallId);
12949
+ toolResults.set(part.toolCallId, {
12950
+ name: matchingToolCall?.name || part.toolCallId,
12951
+ result: part.result,
12952
+ isError: part.isError
12953
+ });
12954
+ break;
12955
+ }
12956
+ // Other stream parts (reasoning, start/end blocks, etc.)
12957
+ // are ignored in non-streaming mode
12958
+ default:
12959
+ break;
12960
+ }
12961
+ }
12962
+ };
12963
+ const streamHandler = this.handleStreamNotification.bind(this);
12964
+ this.resetStreamState();
12965
+ if (this.client) {
12966
+ this.client.setSessionUpdateHandler((notification) => {
12967
+ streamHandler(mockController, notification);
12968
+ });
12969
+ }
12970
+ const response = await this.connection.prompt({
12971
+ sessionId: this.sessionId,
12972
+ prompt: promptContent
12973
+ });
12974
+ const content = [];
12975
+ if (accumulatedText.trim()) {
12976
+ content.push({
12977
+ type: "text",
12978
+ text: accumulatedText
12979
+ });
12980
+ }
12981
+ for (const toolCall of toolCalls) {
12982
+ content.push({
12983
+ type: "tool-call",
12984
+ toolCallId: toolCall.id,
12985
+ toolName: toolCall.name,
12986
+ args: JSON.stringify(toolCall.input),
12987
+ input: toolCall.input,
12988
+ output: toolResults.get(toolCall.id)?.result
12989
+ });
12990
+ }
12991
+ const result = {
12992
+ content,
12993
+ finishReason: response.stopReason === "end_turn" ? "stop" : "other",
12994
+ usage: {
12995
+ inputTokens: 0,
12996
+ outputTokens: 0,
12997
+ totalTokens: 0
12998
+ },
12999
+ warnings: []
13000
+ };
13001
+ this.cleanup();
13002
+ return result;
13003
+ } catch (error) {
13004
+ this.cleanup();
13005
+ throw error;
13006
+ }
13007
+ }
13008
+ /**
13009
+ * Implements the streaming generation method.
13010
+ */
13011
+ async doStream(options) {
13012
+ const acpTools2 = extractACPTools(options.tools);
13013
+ await this.ensureConnected(acpTools2.length > 0 ? acpTools2 : void 0);
13014
+ const promptContent = convertAiSdkMessagesToAcp(options, this.isFreshSession);
13015
+ this.isFreshSession = false;
13016
+ const connection = this.connection;
13017
+ const sessionId = this.sessionId;
13018
+ const client = this.client;
13019
+ const cleanup = () => this.cleanup();
13020
+ const streamHandler = this.handleStreamNotification.bind(this);
13021
+ const stream = new ReadableStream({
13022
+ start: async (controller) => {
13023
+ controller.enqueue({
13024
+ type: "stream-start",
13025
+ warnings: []
13026
+ });
13027
+ this.resetStreamState();
13028
+ try {
13029
+ if (client) {
13030
+ client.setSessionUpdateHandler((notification) => {
13031
+ streamHandler(controller, notification);
13032
+ });
13033
+ }
13034
+ const response = await connection.prompt({
13035
+ sessionId,
13036
+ prompt: promptContent
13037
+ });
13038
+ controller.enqueue({
13039
+ type: "finish",
13040
+ finishReason: response.stopReason === "end_turn" ? "stop" : "other",
13041
+ usage: {
13042
+ inputTokens: 0,
13043
+ outputTokens: 0,
13044
+ totalTokens: 0
13045
+ }
13046
+ });
13047
+ controller.close();
13048
+ cleanup();
13049
+ } catch (error) {
13050
+ cleanup();
13051
+ controller.enqueue({
13052
+ type: "error",
13053
+ error
13054
+ });
13055
+ }
13056
+ },
13057
+ cancel: () => {
13058
+ cleanup();
13059
+ }
13060
+ });
13061
+ return {
13062
+ stream,
13063
+ warnings: []
13064
+ };
13065
+ }
13066
+ get tools() {
13067
+ return getACPDynamicTool();
13068
+ }
13069
+ };
13070
+
13071
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__acp-ai-provider/src/provider.js
13072
+ var ACPProvider = class {
13073
+ config;
13074
+ model = null;
13075
+ constructor(config) {
13076
+ this.config = config;
13077
+ }
13078
+ /**
13079
+ * Create a language model instance for a specific ACP agent
13080
+ *
13081
+ * @returns A LanguageModelV2 instance
13082
+ */
13083
+ languageModel(modelId, modeId) {
13084
+ if (!this.model) {
13085
+ this.model = new ACPLanguageModel(modelId, modeId, this.config);
13086
+ }
13087
+ if (modelId) {
13088
+ this.model.modelId = modelId;
13089
+ }
13090
+ if (modeId) {
13091
+ this.model.modeId = modeId;
13092
+ }
13093
+ return this.model;
13094
+ }
13095
+ /**
13096
+ * Shorthand for creating a language model
13097
+ */
13098
+ call() {
13099
+ return this.languageModel();
13100
+ }
13101
+ /**
13102
+ * Provider tools - includes the agent dynamic tool
13103
+ */
13104
+ get tools() {
13105
+ return this.model?.tools;
13106
+ }
13107
+ /**
13108
+ * Returns the current session ID if one is active.
13109
+ * Useful when `persistSession` is enabled and you need to reference the session later.
13110
+ */
13111
+ getSessionId() {
13112
+ return this.model?.getSessionId() ?? null;
13113
+ }
13114
+ /**
13115
+ * Initializes the session and returns session info (models, modes, meta).
13116
+ * Call this before prompting to discover available options.
13117
+ */
13118
+ initSession(tools) {
13119
+ if (!this.model) {
13120
+ this.languageModel();
13121
+ }
13122
+ return this.model.initSession(tools);
13123
+ }
13124
+ /**
13125
+ * Initializes the connection to the agent process without starting a session.
13126
+ * Useful if you need to reduce the time to the first token.
13127
+ */
13128
+ connect() {
13129
+ if (!this.model) {
13130
+ this.languageModel();
13131
+ }
13132
+ return this.model.connectClient();
13133
+ }
13134
+ /**
13135
+ * Sets the session mode (e.g., "ask", "plan").
13136
+ */
13137
+ setMode(modeId) {
13138
+ if (!this.model) {
13139
+ throw new Error("No model initialized. Call languageModel() first.");
13140
+ }
13141
+ return this.model.setMode(modeId);
13142
+ }
13143
+ /**
13144
+ * Sets the session model.
13145
+ */
13146
+ setModel(modelId) {
13147
+ if (!this.model) {
13148
+ throw new Error("No model initialized. Call languageModel() first.");
13149
+ }
13150
+ return this.model.setModel(modelId);
13151
+ }
13152
+ /**
13153
+ * Forces cleanup of the connection and session.
13154
+ * Call this when you're done with the provider instance, especially when using `persistSession`.
13155
+ */
13156
+ cleanup() {
13157
+ this.model?.forceCleanup();
13158
+ }
13159
+ };
13160
+ function createACPProvider(config) {
13161
+ return new ACPProvider(config);
13162
+ }
13163
+
13164
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/ai/ai-acp-executor.js
13165
+ var AIACPExecutor = class extends BaseAIExecutor {
13166
+ acpSettings;
13167
+ clientTools;
13168
+ provider = null;
13169
+ model = null;
13170
+ constructor(config) {
13171
+ super(config);
13172
+ this.acpSettings = config.acpSettings;
13173
+ this.clientTools = config.clientTools ?? [];
13174
+ }
13175
+ initProvider() {
13176
+ if (!this.model) {
13177
+ this.provider = createACPProvider(this.acpSettings);
13178
+ this.model = this.provider.languageModel();
13179
+ }
13180
+ return this.model;
13181
+ }
13182
+ getModel() {
13183
+ if (!this.model) throw new Error("Model not initialized");
13184
+ return this.model;
13185
+ }
13186
+ getExecutorType() {
13187
+ return "acp";
13188
+ }
13189
+ getToolListDescription() {
13190
+ if (this.clientTools.length === 0) {
13191
+ return "Tools will be provided by AI SDK";
13192
+ }
13193
+ return this.clientTools.map(([name, detail]) => `- ${name}: ${detail.description || "No description"}`).join("\n");
13194
+ }
13195
+ buildTools() {
13196
+ const aiTools = {};
13197
+ for (const [name, detail] of this.clientTools) {
13198
+ if (!detail.execute) continue;
13199
+ aiTools[name] = this.convertToAISDKTool(name, detail, async (input) => {
13200
+ const result = await detail.execute(input);
13201
+ return this.formatResult(result);
13202
+ });
13203
+ }
13204
+ return aiTools;
13205
+ }
13206
+ formatResult(result) {
13207
+ const texts = result.content?.filter((c) => c.type === "text").map((c) => c.text);
13208
+ return texts?.length ? texts.join("\n") : JSON.stringify(result.content);
13209
+ }
13210
+ execute(args) {
13211
+ this.initProvider();
13212
+ return super.execute(args);
13213
+ }
13214
+ cleanup() {
13215
+ if (this.provider && typeof this.provider.cleanup === "function") {
13216
+ this.provider.cleanup();
13217
+ }
13218
+ this.model = null;
13219
+ this.provider = null;
13220
+ }
13221
+ };
13222
+
13223
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/ai/ai-acp-registrar.js
13224
+ function registerAIACPTool(server, params) {
13225
+ const { name, description, allToolNames, depGroups, acpSettings, clientTools = [], maxSteps = 50, tracingEnabled = false } = params;
13226
+ const createArgsDef = createArgsDefFactory(name, allToolNames, depGroups, void 0, void 0);
13227
+ const executor = new AIACPExecutor({
13228
+ name,
13229
+ description,
13230
+ acpSettings,
13231
+ clientTools,
13232
+ maxSteps,
13233
+ tracingEnabled
13234
+ });
13235
+ const toolDescription = CompiledPrompts.samplingToolDescription({
13236
+ toolName: name,
13237
+ description,
13238
+ toolList: allToolNames.length > 0 ? allToolNames.map((n) => `- ${n}`).join("\n") : "Agent has its own tools"
13239
+ });
13240
+ const argsDef = createArgsDef.forSampling();
13241
+ const schema = allToolNames.length > 0 ? argsDef : {
13242
+ type: "object",
13243
+ properties: {}
13244
+ };
13245
+ server.tool(name, toolDescription, jsonSchema(createModelCompatibleJSONSchema(schema)), (args) => {
13246
+ const userRequest = typeof args.userRequest === "string" ? args.userRequest : JSON.stringify(args);
13247
+ return executor.execute({
13248
+ userRequest,
13249
+ context: args.context
13250
+ });
13251
+ });
13252
+ return executor;
13253
+ }
13254
+
13255
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/mode-ai-acp-plugin.js
13256
+ var createAIACPModePlugin = () => ({
13257
+ name: "mode-ai-acp",
13258
+ version: "1.0.0",
13259
+ apply: "ai_acp",
13260
+ registerAgentTool: (context2) => {
13261
+ const opts = context2.options;
13262
+ if (!opts.acpSettings) {
13263
+ throw new Error("ai_acp mode requires acpSettings in options");
13264
+ }
13265
+ registerAIACPTool(context2.server, {
13266
+ description: context2.description,
13267
+ name: context2.name,
13268
+ allToolNames: context2.allToolNames,
13269
+ depGroups: context2.depGroups,
13270
+ acpSettings: opts.acpSettings,
13271
+ clientTools: opts.clientTools,
13272
+ maxSteps: opts.maxSteps,
13273
+ tracingEnabled: opts.tracingEnabled
13274
+ });
13275
+ }
13276
+ });
13277
+ var mode_ai_acp_plugin_default = createAIACPModePlugin();
13278
+
10151
13279
  // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/index.js
10152
13280
  function getBuiltInPlugins() {
10153
13281
  return [
@@ -10157,6 +13285,8 @@ function getBuiltInPlugins() {
10157
13285
  mode_workflow_plugin_default,
10158
13286
  mode_agentic_sampling_plugin_default,
10159
13287
  mode_workflow_sampling_plugin_default,
13288
+ mode_ai_sampling_plugin_default,
13289
+ mode_ai_acp_plugin_default,
10160
13290
  logging_plugin_default
10161
13291
  ];
10162
13292
  }
@@ -10444,13 +13574,13 @@ var PluginManager = class {
10444
13574
  /**
10445
13575
  * Apply transformTool hooks to a tool during composition
10446
13576
  */
10447
- async applyTransformToolHooks(tool, context2) {
13577
+ async applyTransformToolHooks(tool3, context2) {
10448
13578
  const transformPlugins = this.plugins.filter((p2) => p2.transformTool && shouldApplyPlugin(p2, context2.mode));
10449
13579
  if (transformPlugins.length === 0) {
10450
- return tool;
13580
+ return tool3;
10451
13581
  }
10452
13582
  const sortedPlugins = sortPluginsByOrder(transformPlugins);
10453
- let currentTool = tool;
13583
+ let currentTool = tool3;
10454
13584
  for (const plugin of sortedPlugins) {
10455
13585
  if (plugin.transformTool) {
10456
13586
  try {
@@ -10698,12 +13828,12 @@ var ToolManager = class {
10698
13828
  * Get tool schema if it's hidden (for internal access)
10699
13829
  */
10700
13830
  getHiddenToolSchema(name) {
10701
- const tool = this.toolRegistry.get(name);
13831
+ const tool3 = this.toolRegistry.get(name);
10702
13832
  const config = this.toolConfigs.get(name);
10703
- if (tool && config?.visibility?.hidden && tool.schema) {
13833
+ if (tool3 && config?.visibility?.hidden && tool3.schema) {
10704
13834
  return {
10705
- description: tool.description,
10706
- schema: tool.schema
13835
+ description: tool3.description,
13836
+ schema: tool3.schema
10707
13837
  };
10708
13838
  }
10709
13839
  return void 0;
@@ -10732,18 +13862,18 @@ var ToolManager = class {
10732
13862
  */
10733
13863
  getRegisteredToolsAsComposed() {
10734
13864
  const composedTools = {};
10735
- for (const [name, tool] of this.toolRegistry.entries()) {
13865
+ for (const [name, tool3] of this.toolRegistry.entries()) {
10736
13866
  if (this.toolConfigs.get(name)?.visibility?.public === true) {
10737
13867
  continue;
10738
13868
  }
10739
13869
  composedTools[name] = {
10740
13870
  name,
10741
- description: tool.description,
10742
- inputSchema: jsonSchema(tool.schema || {
13871
+ description: tool3.description,
13872
+ inputSchema: jsonSchema(tool3.schema || {
10743
13873
  type: "object",
10744
13874
  properties: {}
10745
13875
  }),
10746
- execute: tool.callback
13876
+ execute: tool3.callback
10747
13877
  };
10748
13878
  }
10749
13879
  return composedTools;
@@ -10813,18 +13943,18 @@ async function processToolsWithPlugins(server, _externalTools, mode) {
10813
13943
  function buildDependencyGroups(toolNameToDetailList, hiddenToolNames, publicToolNames, server) {
10814
13944
  const depGroups = {};
10815
13945
  const toolManager = server.toolManager;
10816
- toolNameToDetailList.forEach(([toolName, tool]) => {
13946
+ toolNameToDetailList.forEach(([toolName, tool3]) => {
10817
13947
  const resolvedName = toolManager.resolveToolName(toolName);
10818
13948
  if (hiddenToolNames.includes(resolvedName ?? "") || publicToolNames.includes(resolvedName ?? "")) {
10819
13949
  return;
10820
13950
  }
10821
- if (!tool) {
13951
+ if (!tool3) {
10822
13952
  const allToolNames = [
10823
13953
  ...toolNameToDetailList.map(([n]) => n)
10824
13954
  ];
10825
13955
  throw new Error(`Action ${toolName} not found, available action list: ${allToolNames.join(", ")}`);
10826
13956
  }
10827
- const baseSchema = tool.inputSchema.jsonSchema ?? tool.inputSchema ?? {
13957
+ const baseSchema = tool3.inputSchema.jsonSchema ?? tool3.inputSchema ?? {
10828
13958
  type: "object",
10829
13959
  properties: {},
10830
13960
  required: []
@@ -10835,7 +13965,7 @@ function buildDependencyGroups(toolNameToDetailList, hiddenToolNames, publicTool
10835
13965
  const sanitizedKey = sanitizePropertyKey(toolName);
10836
13966
  depGroups[sanitizedKey] = {
10837
13967
  type: "object",
10838
- description: tool.description,
13968
+ description: tool3.description,
10839
13969
  properties: updatedProperties,
10840
13970
  required: [
10841
13971
  ...baseRequired
@@ -11111,9 +14241,9 @@ var ComposableMCPServer = class extends Server {
11111
14241
  const requestedToolNames = /* @__PURE__ */ new Set();
11112
14242
  const availableToolNames = /* @__PURE__ */ new Set();
11113
14243
  const allPlaceholderUsages = [];
11114
- tagToResults.tool.forEach((tool) => {
11115
- if (tool.attribs.name) {
11116
- const originalName = tool.attribs.name;
14244
+ tagToResults.tool.forEach((tool3) => {
14245
+ if (tool3.attribs.name) {
14246
+ const originalName = tool3.attribs.name;
11117
14247
  const toolName = sanitizePropertyKey(originalName);
11118
14248
  if (toolName.endsWith(`_${ALL_TOOLS_PLACEHOLDER2}`) || toolName === ALL_TOOLS_PLACEHOLDER2) {
11119
14249
  allPlaceholderUsages.push(originalName);
@@ -11139,24 +14269,24 @@ var ComposableMCPServer = class extends Server {
11139
14269
  }
11140
14270
  return true;
11141
14271
  }
11142
- return tagToResults.tool.find((tool) => {
11143
- const selectAll = tool.attribs.name === `${mcpName}.${ALL_TOOLS_PLACEHOLDER2}` || tool.attribs.name === `${mcpName}`;
14272
+ return tagToResults.tool.find((tool3) => {
14273
+ const selectAll = tool3.attribs.name === `${mcpName}.${ALL_TOOLS_PLACEHOLDER2}` || tool3.attribs.name === `${mcpName}`;
11144
14274
  if (selectAll) {
11145
14275
  return true;
11146
14276
  }
11147
- return tool.attribs.name === toolNameWithScope || tool.attribs.name === toolId;
14277
+ return tool3.attribs.name === toolNameWithScope || tool3.attribs.name === toolId;
11148
14278
  });
11149
14279
  });
11150
- Object.entries(tools).forEach(([toolId, tool]) => {
11151
- this.toolManager.registerTool(toolId, tool.description || "", tool.inputSchema, tool.execute);
14280
+ Object.entries(tools).forEach(([toolId, tool3]) => {
14281
+ this.toolManager.registerTool(toolId, tool3.description || "", tool3.inputSchema, tool3.execute);
11152
14282
  });
11153
14283
  const registeredTools = this.toolManager.getRegisteredToolsAsComposed();
11154
14284
  const allTools = {
11155
14285
  ...tools
11156
14286
  };
11157
- Object.entries(registeredTools).forEach(([toolName, tool]) => {
14287
+ Object.entries(registeredTools).forEach(([toolName, tool3]) => {
11158
14288
  if (!allTools[toolName]) {
11159
- allTools[toolName] = tool;
14289
+ allTools[toolName] = tool3;
11160
14290
  }
11161
14291
  availableToolNames.add(toolName);
11162
14292
  });
@@ -11200,11 +14330,11 @@ var ComposableMCPServer = class extends Server {
11200
14330
  const hiddenToolNames = this.getHiddenToolNames();
11201
14331
  const contextToolNames = toolNameToDetailList.map(([name2]) => name2).filter((n) => !hiddenToolNames.includes(n));
11202
14332
  publicToolNames.forEach((toolId) => {
11203
- const tool = allTools[toolId];
11204
- if (!tool) {
14333
+ const tool3 = allTools[toolId];
14334
+ if (!tool3) {
11205
14335
  throw new Error(`Public tool ${toolId} not found in registry, available: ${Object.keys(allTools).join(", ")}`);
11206
14336
  }
11207
- this.tool(toolId, tool.description || "", jsonSchema(tool.inputSchema), tool.execute, {
14337
+ this.tool(toolId, tool3.description || "", jsonSchema(tool3.inputSchema), tool3.execute, {
11208
14338
  internal: false
11209
14339
  });
11210
14340
  });
@@ -11257,12 +14387,12 @@ var ComposableMCPServer = class extends Server {
11257
14387
  };
11258
14388
 
11259
14389
  // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/env.js
11260
- import process9 from "node:process";
11261
- var isSCF = () => Boolean(process9.env.SCF_RUNTIME || process9.env.PROD_SCF);
14390
+ import process10 from "node:process";
14391
+ var isSCF = () => Boolean(process10.env.SCF_RUNTIME || process10.env.PROD_SCF);
11262
14392
  if (isSCF()) {
11263
14393
  console.log({
11264
14394
  isSCF: isSCF(),
11265
- SCF_RUNTIME: process9.env.SCF_RUNTIME
14395
+ SCF_RUNTIME: process10.env.SCF_RUNTIME
11266
14396
  });
11267
14397
  }
11268
14398
 
@@ -11552,9 +14682,9 @@ function createLargeResultPlugin(options = {}) {
11552
14682
  configuredServers.set(server, true);
11553
14683
  }
11554
14684
  },
11555
- transformTool: (tool, context2) => {
11556
- const originalExecute = tool.execute;
11557
- tool.execute = async (args) => {
14685
+ transformTool: (tool3, context2) => {
14686
+ const originalExecute = tool3.execute;
14687
+ tool3.execute = async (args) => {
11558
14688
  try {
11559
14689
  const result = await originalExecute(args);
11560
14690
  const resultText = JSON.stringify(result);
@@ -11596,7 +14726,7 @@ ${preview}
11596
14726
  throw error;
11597
14727
  }
11598
14728
  };
11599
- return tool;
14729
+ return tool3;
11600
14730
  },
11601
14731
  dispose: () => {
11602
14732
  configuredServers.clear();