@mcpc-tech/cli 0.1.24 → 0.1.25

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 +82 -2453
  2. package/bin/mcpc.mjs +81 -2452
  3. package/package.json +2 -1
package/bin/mcpc.cjs CHANGED
@@ -502,7 +502,7 @@ var require_cross_spawn = __commonJS({
502
502
  var cp = require("child_process");
503
503
  var parse = require_parse();
504
504
  var enoent = require_enoent();
505
- function spawn3(command, args, options) {
505
+ function spawn2(command, args, options) {
506
506
  const parsed = parse(command, args, options);
507
507
  const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
508
508
  enoent.hookChildProcess(spawned, parsed);
@@ -514,8 +514,8 @@ var require_cross_spawn = __commonJS({
514
514
  result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
515
515
  return result;
516
516
  }
517
- module2.exports = spawn3;
518
- module2.exports.spawn = spawn3;
517
+ module2.exports = spawn2;
518
+ module2.exports.spawn = spawn2;
519
519
  module2.exports.sync = spawnSync;
520
520
  module2.exports._parse = parse;
521
521
  module2.exports._enoent = enoent;
@@ -5161,17 +5161,17 @@ var Client = class extends Protocol {
5161
5161
  this._cachedToolOutputValidators.clear();
5162
5162
  this._cachedKnownTaskTools.clear();
5163
5163
  this._cachedRequiredTaskTools.clear();
5164
- for (const tool3 of tools) {
5165
- if (tool3.outputSchema) {
5166
- const toolValidator = this._jsonSchemaValidator.getValidator(tool3.outputSchema);
5167
- this._cachedToolOutputValidators.set(tool3.name, toolValidator);
5164
+ for (const tool2 of tools) {
5165
+ if (tool2.outputSchema) {
5166
+ const toolValidator = this._jsonSchemaValidator.getValidator(tool2.outputSchema);
5167
+ this._cachedToolOutputValidators.set(tool2.name, toolValidator);
5168
5168
  }
5169
- const taskSupport = tool3.execution?.taskSupport;
5169
+ const taskSupport = tool2.execution?.taskSupport;
5170
5170
  if (taskSupport === "required" || taskSupport === "optional") {
5171
- this._cachedKnownTaskTools.add(tool3.name);
5171
+ this._cachedKnownTaskTools.add(tool2.name);
5172
5172
  }
5173
5173
  if (taskSupport === "required") {
5174
- this._cachedRequiredTaskTools.add(tool3.name);
5174
+ this._cachedRequiredTaskTools.add(tool2.name);
5175
5175
  }
5176
5176
  }
5177
5177
  }
@@ -7468,14 +7468,14 @@ async function composeMcpDepTools(mcpConfig, filterIn) {
7468
7468
  acquiredKeys.push(defKey);
7469
7469
  allClients[serverId] = client;
7470
7470
  const { tools } = await client.listTools();
7471
- tools.forEach((tool3) => {
7472
- const toolNameWithScope = `${name}.${tool3.name}`;
7473
- const internalToolName = tool3.name;
7471
+ tools.forEach((tool2) => {
7472
+ const toolNameWithScope = `${name}.${tool2.name}`;
7473
+ const internalToolName = tool2.name;
7474
7474
  const rawToolId = `${serverId}_${internalToolName}`;
7475
7475
  const toolId = sanitizePropertyKey(rawToolId);
7476
7476
  if (filterIn && !filterIn({
7477
7477
  action: internalToolName,
7478
- tool: tool3,
7478
+ tool: tool2,
7479
7479
  mcpName: name,
7480
7480
  toolNameWithScope,
7481
7481
  internalToolName,
@@ -7490,7 +7490,7 @@ async function composeMcpDepTools(mcpConfig, filterIn) {
7490
7490
  timeout: def.toolCallTimeout
7491
7491
  });
7492
7492
  allTools[toolId] = {
7493
- ...tool3,
7493
+ ...tool2,
7494
7494
  execute,
7495
7495
  _originalName: toolNameWithScope
7496
7496
  };
@@ -7553,13 +7553,13 @@ var createConfigPlugin = () => ({
7553
7553
  name: "built-in-config",
7554
7554
  version: "1.0.0",
7555
7555
  enforce: "pre",
7556
- transformTool: (tool3, context2) => {
7556
+ transformTool: (tool2, context2) => {
7557
7557
  const server = context2.server;
7558
7558
  const config = server.findToolConfig?.(context2.toolName);
7559
7559
  if (config?.description) {
7560
- tool3.description = config.description;
7560
+ tool2.description = config.description;
7561
7561
  }
7562
- return tool3;
7562
+ return tool2;
7563
7563
  }
7564
7564
  });
7565
7565
  var config_plugin_default = createConfigPlugin();
@@ -7569,10 +7569,10 @@ var createToolNameMappingPlugin = () => ({
7569
7569
  name: "built-in-tool-name-mapping",
7570
7570
  version: "1.0.0",
7571
7571
  enforce: "pre",
7572
- transformTool: (tool3, context2) => {
7572
+ transformTool: (tool2, context2) => {
7573
7573
  const server = context2.server;
7574
7574
  const toolName = context2.toolName;
7575
- const originalName = tool3._originalName || toolName;
7575
+ const originalName = tool2._originalName || toolName;
7576
7576
  const dotNotation = originalName.replace(/_/g, ".");
7577
7577
  const underscoreNotation = originalName.replace(/\./g, "_");
7578
7578
  if (dotNotation !== originalName && server.toolNameMapping) {
@@ -7584,7 +7584,7 @@ var createToolNameMappingPlugin = () => ({
7584
7584
  if (originalName !== toolName && server.toolNameMapping) {
7585
7585
  server.toolNameMapping.set(originalName, toolName);
7586
7586
  }
7587
- return tool3;
7587
+ return tool2;
7588
7588
  }
7589
7589
  });
7590
7590
  var tool_name_mapping_plugin_default = createToolNameMappingPlugin();
@@ -8077,13 +8077,13 @@ var PromptUtils = {
8077
8077
  * Generate tool list for descriptions
8078
8078
  */
8079
8079
  generateToolList: (tools) => {
8080
- return tools.filter((tool3) => !tool3.hide).map((tool3) => `<tool name="${tool3.name}"${tool3.description ? ` description="${tool3.description}"` : ""}/>`).join("\n");
8080
+ return tools.filter((tool2) => !tool2.hide).map((tool2) => `<tool name="${tool2.name}"${tool2.description ? ` description="${tool2.description}"` : ""}/>`).join("\n");
8081
8081
  },
8082
8082
  /**
8083
8083
  * Generate hidden tool list for descriptions
8084
8084
  */
8085
8085
  generateHiddenToolList: (tools) => {
8086
- return tools.filter((tool3) => tool3.hide).map((tool3) => `<tool name="${tool3.name}" hide/>`).join("\n");
8086
+ return tools.filter((tool2) => tool2.hide).map((tool2) => `<tool name="${tool2.name}" hide/>`).join("\n");
8087
8087
  },
8088
8088
  /**
8089
8089
  * Format workflow steps for display
@@ -9868,12 +9868,12 @@ var SamplingExecutor = class extends BaseSamplingExecutor {
9868
9868
  }
9869
9869
  buildDepGroups() {
9870
9870
  const depGroups = {};
9871
- this.toolNameToDetailList.forEach(([toolName, tool3]) => {
9872
- if (tool3?.inputSchema) {
9871
+ this.toolNameToDetailList.forEach(([toolName, tool2]) => {
9872
+ if (tool2?.inputSchema) {
9873
9873
  depGroups[toolName] = {
9874
9874
  type: "object",
9875
- description: tool3.description || `Tool: ${toolName}`,
9876
- ...tool3.inputSchema
9875
+ description: tool2.description || `Tool: ${toolName}`,
9876
+ ...tool2.inputSchema
9877
9877
  };
9878
9878
  } else {
9879
9879
  const toolSchema = this.server.getHiddenToolSchema(toolName);
@@ -9930,10 +9930,10 @@ var SamplingExecutor = class extends BaseSamplingExecutor {
9930
9930
  }
9931
9931
  buildSystemPrompt(userRequest, agenticSchema, context2) {
9932
9932
  const toolList = this.allToolNames.map((name) => {
9933
- const tool3 = this.toolNameToDetailList.find(([toolName]) => toolName === name);
9933
+ const tool2 = this.toolNameToDetailList.find(([toolName]) => toolName === name);
9934
9934
  const toolSchema = this.server.getHiddenToolSchema(name);
9935
- if (tool3 && tool3[1]) {
9936
- return `- ${name}: ${tool3[1].description || `Tool: ${name}`}`;
9935
+ if (tool2 && tool2[1]) {
9936
+ return `- ${name}: ${tool2[1].description || `Tool: ${name}`}`;
9937
9937
  } else if (toolSchema) {
9938
9938
  return `- ${name}: ${toolSchema.description}`;
9939
9939
  }
@@ -9960,7 +9960,7 @@ ${JSON.stringify(context2, null, 2)}`;
9960
9960
  ## Current Task
9961
9961
  You will now use agentic sampling to complete the following task: "${userRequest}"${contextInfo}
9962
9962
 
9963
- When you need to use a tool, specify the tool name in 'action' and provide tool-specific parameters as additional properties.`;
9963
+ When you need to use a tool, specify the tool name in 'useTool' and provide tool-specific parameters as additional properties.`;
9964
9964
  return this.formatPromptForMode({
9965
9965
  prompt: basePrompt + taskPrompt,
9966
9966
  schema: agenticSchema
@@ -10156,8 +10156,9 @@ function convertAISDKToMCPMessages(prompt) {
10156
10156
  if (toolCalls.length > 0) {
10157
10157
  const calls = toolCalls.map((c) => {
10158
10158
  const call = c;
10159
+ const toolArgs = call.args ?? call.input ?? {};
10159
10160
  return `<use_tool tool="${call.toolName}">
10160
- ${JSON.stringify(call.input || {})}
10161
+ ${JSON.stringify(toolArgs)}
10161
10162
  </use_tool>`;
10162
10163
  });
10163
10164
  parts.push(calls.join("\n"));
@@ -10165,7 +10166,8 @@ ${JSON.stringify(call.input || {})}
10165
10166
  if (toolResults.length > 0) {
10166
10167
  const results = toolResults.map((c) => {
10167
10168
  const result = c;
10168
- const output = JSON.stringify(result.output || result.result || "undefined");
10169
+ const resultValue = result.result ?? result.output ?? "undefined";
10170
+ const output = JSON.stringify(resultValue);
10169
10171
  return `Tool "${result.toolName}" result:
10170
10172
  ${output}`;
10171
10173
  });
@@ -10372,11 +10374,11 @@ var MCPSamplingLanguageModel = class {
10372
10374
  */
10373
10375
  convertAISDKToolsToMCP(tools) {
10374
10376
  if (!tools || tools.length === 0) return [];
10375
- return tools.filter((tool3) => tool3.type === "function").map((tool3) => {
10376
- const toolAny = tool3;
10377
+ return tools.filter((tool2) => tool2.type === "function").map((tool2) => {
10378
+ const toolAny = tool2;
10377
10379
  return {
10378
- name: tool3.name,
10379
- description: toolAny.description || `Tool: ${tool3.name}`,
10380
+ name: tool2.name,
10381
+ description: toolAny.description || `Tool: ${tool2.name}`,
10380
10382
  inputSchema: {
10381
10383
  type: "object",
10382
10384
  ...toolAny.inputSchema || toolAny.parameters
@@ -10446,18 +10448,18 @@ Follow the JSON schema definition for each tool's parameters.
10446
10448
  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.
10447
10449
 
10448
10450
  Tools:`;
10449
- const toolDescriptions = tools.map((tool3) => {
10450
- if (tool3.type === "function") {
10451
- const toolAny = tool3;
10451
+ const toolDescriptions = tools.map((tool2) => {
10452
+ if (tool2.type === "function") {
10453
+ const toolAny = tool2;
10452
10454
  const description = toolAny.description || "No description provided";
10453
10455
  const schema = toolAny.inputSchema || toolAny.parameters;
10454
10456
  const params = schema ? `
10455
10457
  JSON Schema: ${JSON.stringify(schema, null, 2)}` : "";
10456
10458
  return `
10457
- - ${tool3.name}: ${description}${params}`;
10458
- } else if (tool3.type === "provider-defined") {
10459
+ - ${tool2.name}: ${description}${params}`;
10460
+ } else if (tool2.type === "provider-defined") {
10459
10461
  return `
10460
- - ${tool3.name}: ${tool3.id || "No description provided"}`;
10462
+ - ${tool2.name}: ${tool2.id || "No description provided"}`;
10461
10463
  }
10462
10464
  return "";
10463
10465
  }).filter(Boolean).join("");
@@ -10779,2381 +10781,8 @@ var createAISamplingModePlugin = () => ({
10779
10781
  });
10780
10782
  var mode_ai_sampling_plugin_default = createAISamplingModePlugin();
10781
10783
 
10782
- // __mcpc__cli_latest/node_modules/@agentclientprotocol/sdk/dist/acp.js
10783
- var import_zod3 = require("zod");
10784
-
10785
- // __mcpc__cli_latest/node_modules/@agentclientprotocol/sdk/dist/schema.js
10786
- var import_zod2 = require("zod");
10787
- var AGENT_METHODS = {
10788
- authenticate: "authenticate",
10789
- initialize: "initialize",
10790
- session_cancel: "session/cancel",
10791
- session_load: "session/load",
10792
- session_new: "session/new",
10793
- session_prompt: "session/prompt",
10794
- session_set_mode: "session/set_mode",
10795
- session_set_model: "session/set_model"
10796
- };
10797
- var CLIENT_METHODS = {
10798
- fs_read_text_file: "fs/read_text_file",
10799
- fs_write_text_file: "fs/write_text_file",
10800
- session_request_permission: "session/request_permission",
10801
- session_update: "session/update",
10802
- terminal_create: "terminal/create",
10803
- terminal_kill: "terminal/kill",
10804
- terminal_output: "terminal/output",
10805
- terminal_release: "terminal/release",
10806
- terminal_wait_for_exit: "terminal/wait_for_exit"
10807
- };
10808
- var PROTOCOL_VERSION = 1;
10809
- var writeTextFileRequestSchema = import_zod2.z.object({
10810
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10811
- content: import_zod2.z.string(),
10812
- path: import_zod2.z.string(),
10813
- sessionId: import_zod2.z.string()
10814
- });
10815
- var readTextFileRequestSchema = import_zod2.z.object({
10816
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10817
- limit: import_zod2.z.number().optional().nullable(),
10818
- line: import_zod2.z.number().optional().nullable(),
10819
- path: import_zod2.z.string(),
10820
- sessionId: import_zod2.z.string()
10821
- });
10822
- var terminalOutputRequestSchema = import_zod2.z.object({
10823
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10824
- sessionId: import_zod2.z.string(),
10825
- terminalId: import_zod2.z.string()
10826
- });
10827
- var releaseTerminalRequestSchema = import_zod2.z.object({
10828
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10829
- sessionId: import_zod2.z.string(),
10830
- terminalId: import_zod2.z.string()
10831
- });
10832
- var waitForTerminalExitRequestSchema = import_zod2.z.object({
10833
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10834
- sessionId: import_zod2.z.string(),
10835
- terminalId: import_zod2.z.string()
10836
- });
10837
- var killTerminalCommandRequestSchema = import_zod2.z.object({
10838
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10839
- sessionId: import_zod2.z.string(),
10840
- terminalId: import_zod2.z.string()
10841
- });
10842
- var extMethodRequestSchema = import_zod2.z.record(import_zod2.z.unknown());
10843
- var roleSchema = import_zod2.z.union([import_zod2.z.literal("assistant"), import_zod2.z.literal("user")]);
10844
- var textResourceContentsSchema = import_zod2.z.object({
10845
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10846
- mimeType: import_zod2.z.string().optional().nullable(),
10847
- text: import_zod2.z.string(),
10848
- uri: import_zod2.z.string()
10849
- });
10850
- var blobResourceContentsSchema = import_zod2.z.object({
10851
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10852
- blob: import_zod2.z.string(),
10853
- mimeType: import_zod2.z.string().optional().nullable(),
10854
- uri: import_zod2.z.string()
10855
- });
10856
- var toolKindSchema = import_zod2.z.union([
10857
- import_zod2.z.literal("read"),
10858
- import_zod2.z.literal("edit"),
10859
- import_zod2.z.literal("delete"),
10860
- import_zod2.z.literal("move"),
10861
- import_zod2.z.literal("search"),
10862
- import_zod2.z.literal("execute"),
10863
- import_zod2.z.literal("think"),
10864
- import_zod2.z.literal("fetch"),
10865
- import_zod2.z.literal("switch_mode"),
10866
- import_zod2.z.literal("other")
10867
- ]);
10868
- var toolCallStatusSchema = import_zod2.z.union([
10869
- import_zod2.z.literal("pending"),
10870
- import_zod2.z.literal("in_progress"),
10871
- import_zod2.z.literal("completed"),
10872
- import_zod2.z.literal("failed")
10873
- ]);
10874
- var writeTextFileResponseSchema = import_zod2.z.object({
10875
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional()
10876
- });
10877
- var readTextFileResponseSchema = import_zod2.z.object({
10878
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10879
- content: import_zod2.z.string()
10880
- });
10881
- var requestPermissionResponseSchema = import_zod2.z.object({
10882
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10883
- outcome: import_zod2.z.union([
10884
- import_zod2.z.object({
10885
- outcome: import_zod2.z.literal("cancelled")
10886
- }),
10887
- import_zod2.z.object({
10888
- optionId: import_zod2.z.string(),
10889
- outcome: import_zod2.z.literal("selected")
10890
- })
10891
- ])
10892
- });
10893
- var createTerminalResponseSchema = import_zod2.z.object({
10894
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10895
- terminalId: import_zod2.z.string()
10896
- });
10897
- var releaseTerminalResponseSchema = import_zod2.z.object({
10898
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional()
10899
- });
10900
- var waitForTerminalExitResponseSchema = import_zod2.z.object({
10901
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10902
- exitCode: import_zod2.z.number().optional().nullable(),
10903
- signal: import_zod2.z.string().optional().nullable()
10904
- });
10905
- var killTerminalResponseSchema = import_zod2.z.object({
10906
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional()
10907
- });
10908
- var extMethodResponseSchema = import_zod2.z.record(import_zod2.z.unknown());
10909
- var cancelNotificationSchema = import_zod2.z.object({
10910
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10911
- sessionId: import_zod2.z.string()
10912
- });
10913
- var extNotificationSchema = import_zod2.z.record(import_zod2.z.unknown());
10914
- var authenticateRequestSchema = import_zod2.z.object({
10915
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10916
- methodId: import_zod2.z.string()
10917
- });
10918
- var setSessionModeRequestSchema = import_zod2.z.object({
10919
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10920
- modeId: import_zod2.z.string(),
10921
- sessionId: import_zod2.z.string()
10922
- });
10923
- var setSessionModelRequestSchema = import_zod2.z.object({
10924
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10925
- modelId: import_zod2.z.string(),
10926
- sessionId: import_zod2.z.string()
10927
- });
10928
- var extMethodRequest1Schema = import_zod2.z.record(import_zod2.z.unknown());
10929
- var httpHeaderSchema = import_zod2.z.object({
10930
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10931
- name: import_zod2.z.string(),
10932
- value: import_zod2.z.string()
10933
- });
10934
- var annotationsSchema = import_zod2.z.object({
10935
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10936
- audience: import_zod2.z.array(roleSchema).optional().nullable(),
10937
- lastModified: import_zod2.z.string().optional().nullable(),
10938
- priority: import_zod2.z.number().optional().nullable()
10939
- });
10940
- var embeddedResourceResourceSchema = import_zod2.z.union([
10941
- textResourceContentsSchema,
10942
- blobResourceContentsSchema
10943
- ]);
10944
- var authenticateResponseSchema = import_zod2.z.object({
10945
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional()
10946
- });
10947
- var setSessionModeResponseSchema = import_zod2.z.object({
10948
- meta: import_zod2.z.unknown().optional()
10949
- });
10950
- var promptResponseSchema = import_zod2.z.object({
10951
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10952
- stopReason: import_zod2.z.union([
10953
- import_zod2.z.literal("end_turn"),
10954
- import_zod2.z.literal("max_tokens"),
10955
- import_zod2.z.literal("max_turn_requests"),
10956
- import_zod2.z.literal("refusal"),
10957
- import_zod2.z.literal("cancelled")
10958
- ])
10959
- });
10960
- var setSessionModelResponseSchema = import_zod2.z.object({
10961
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional()
10962
- });
10963
- var extMethodResponse1Schema = import_zod2.z.record(import_zod2.z.unknown());
10964
- var sessionModeIdSchema = import_zod2.z.string();
10965
- var extNotification1Schema = import_zod2.z.record(import_zod2.z.unknown());
10966
- var unstructuredCommandInputSchema = import_zod2.z.object({
10967
- hint: import_zod2.z.string()
10968
- });
10969
- var permissionOptionSchema = import_zod2.z.object({
10970
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10971
- kind: import_zod2.z.union([
10972
- import_zod2.z.literal("allow_once"),
10973
- import_zod2.z.literal("allow_always"),
10974
- import_zod2.z.literal("reject_once"),
10975
- import_zod2.z.literal("reject_always")
10976
- ]),
10977
- name: import_zod2.z.string(),
10978
- optionId: import_zod2.z.string()
10979
- });
10980
- var toolCallContentSchema = import_zod2.z.union([
10981
- import_zod2.z.object({
10982
- content: import_zod2.z.union([
10983
- import_zod2.z.object({
10984
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10985
- annotations: annotationsSchema.optional().nullable(),
10986
- text: import_zod2.z.string(),
10987
- type: import_zod2.z.literal("text")
10988
- }),
10989
- import_zod2.z.object({
10990
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10991
- annotations: annotationsSchema.optional().nullable(),
10992
- data: import_zod2.z.string(),
10993
- mimeType: import_zod2.z.string(),
10994
- type: import_zod2.z.literal("image"),
10995
- uri: import_zod2.z.string().optional().nullable()
10996
- }),
10997
- import_zod2.z.object({
10998
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
10999
- annotations: annotationsSchema.optional().nullable(),
11000
- data: import_zod2.z.string(),
11001
- mimeType: import_zod2.z.string(),
11002
- type: import_zod2.z.literal("audio")
11003
- }),
11004
- import_zod2.z.object({
11005
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11006
- annotations: annotationsSchema.optional().nullable(),
11007
- description: import_zod2.z.string().optional().nullable(),
11008
- mimeType: import_zod2.z.string().optional().nullable(),
11009
- name: import_zod2.z.string(),
11010
- size: import_zod2.z.number().optional().nullable(),
11011
- title: import_zod2.z.string().optional().nullable(),
11012
- type: import_zod2.z.literal("resource_link"),
11013
- uri: import_zod2.z.string()
11014
- }),
11015
- import_zod2.z.object({
11016
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11017
- annotations: annotationsSchema.optional().nullable(),
11018
- resource: embeddedResourceResourceSchema,
11019
- type: import_zod2.z.literal("resource")
11020
- })
11021
- ]),
11022
- type: import_zod2.z.literal("content")
11023
- }),
11024
- import_zod2.z.object({
11025
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11026
- newText: import_zod2.z.string(),
11027
- oldText: import_zod2.z.string().optional().nullable(),
11028
- path: import_zod2.z.string(),
11029
- type: import_zod2.z.literal("diff")
11030
- }),
11031
- import_zod2.z.object({
11032
- terminalId: import_zod2.z.string(),
11033
- type: import_zod2.z.literal("terminal")
11034
- })
11035
- ]);
11036
- var toolCallLocationSchema = import_zod2.z.object({
11037
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11038
- line: import_zod2.z.number().optional().nullable(),
11039
- path: import_zod2.z.string()
11040
- });
11041
- var envVariableSchema = import_zod2.z.object({
11042
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11043
- name: import_zod2.z.string(),
11044
- value: import_zod2.z.string()
11045
- });
11046
- var terminalExitStatusSchema = import_zod2.z.object({
11047
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11048
- exitCode: import_zod2.z.number().optional().nullable(),
11049
- signal: import_zod2.z.string().optional().nullable()
11050
- });
11051
- var fileSystemCapabilitySchema = import_zod2.z.object({
11052
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11053
- readTextFile: import_zod2.z.boolean().optional(),
11054
- writeTextFile: import_zod2.z.boolean().optional()
11055
- });
11056
- var stdioSchema = import_zod2.z.object({
11057
- args: import_zod2.z.array(import_zod2.z.string()),
11058
- command: import_zod2.z.string(),
11059
- env: import_zod2.z.array(envVariableSchema),
11060
- name: import_zod2.z.string()
11061
- });
11062
- var mcpServerSchema = import_zod2.z.union([
11063
- import_zod2.z.object({
11064
- headers: import_zod2.z.array(httpHeaderSchema),
11065
- name: import_zod2.z.string(),
11066
- type: import_zod2.z.literal("http"),
11067
- url: import_zod2.z.string()
11068
- }),
11069
- import_zod2.z.object({
11070
- headers: import_zod2.z.array(httpHeaderSchema),
11071
- name: import_zod2.z.string(),
11072
- type: import_zod2.z.literal("sse"),
11073
- url: import_zod2.z.string()
11074
- }),
11075
- stdioSchema
11076
- ]);
11077
- var contentBlockSchema = import_zod2.z.union([
11078
- import_zod2.z.object({
11079
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11080
- annotations: annotationsSchema.optional().nullable(),
11081
- text: import_zod2.z.string(),
11082
- type: import_zod2.z.literal("text")
11083
- }),
11084
- import_zod2.z.object({
11085
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11086
- annotations: annotationsSchema.optional().nullable(),
11087
- data: import_zod2.z.string(),
11088
- mimeType: import_zod2.z.string(),
11089
- type: import_zod2.z.literal("image"),
11090
- uri: import_zod2.z.string().optional().nullable()
11091
- }),
11092
- import_zod2.z.object({
11093
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11094
- annotations: annotationsSchema.optional().nullable(),
11095
- data: import_zod2.z.string(),
11096
- mimeType: import_zod2.z.string(),
11097
- type: import_zod2.z.literal("audio")
11098
- }),
11099
- import_zod2.z.object({
11100
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11101
- annotations: annotationsSchema.optional().nullable(),
11102
- description: import_zod2.z.string().optional().nullable(),
11103
- mimeType: import_zod2.z.string().optional().nullable(),
11104
- name: import_zod2.z.string(),
11105
- size: import_zod2.z.number().optional().nullable(),
11106
- title: import_zod2.z.string().optional().nullable(),
11107
- type: import_zod2.z.literal("resource_link"),
11108
- uri: import_zod2.z.string()
11109
- }),
11110
- import_zod2.z.object({
11111
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11112
- annotations: annotationsSchema.optional().nullable(),
11113
- resource: embeddedResourceResourceSchema,
11114
- type: import_zod2.z.literal("resource")
11115
- })
11116
- ]);
11117
- var authMethodSchema = import_zod2.z.object({
11118
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11119
- description: import_zod2.z.string().optional().nullable(),
11120
- id: import_zod2.z.string(),
11121
- name: import_zod2.z.string()
11122
- });
11123
- var mcpCapabilitiesSchema = import_zod2.z.object({
11124
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11125
- http: import_zod2.z.boolean().optional(),
11126
- sse: import_zod2.z.boolean().optional()
11127
- });
11128
- var promptCapabilitiesSchema = import_zod2.z.object({
11129
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11130
- audio: import_zod2.z.boolean().optional(),
11131
- embeddedContext: import_zod2.z.boolean().optional(),
11132
- image: import_zod2.z.boolean().optional()
11133
- });
11134
- var modelInfoSchema = import_zod2.z.object({
11135
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11136
- description: import_zod2.z.string().optional().nullable(),
11137
- modelId: import_zod2.z.string(),
11138
- name: import_zod2.z.string()
11139
- });
11140
- var sessionModeSchema = import_zod2.z.object({
11141
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11142
- description: import_zod2.z.string().optional().nullable(),
11143
- id: sessionModeIdSchema,
11144
- name: import_zod2.z.string()
11145
- });
11146
- var sessionModelStateSchema = import_zod2.z.object({
11147
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11148
- availableModels: import_zod2.z.array(modelInfoSchema),
11149
- currentModelId: import_zod2.z.string()
11150
- });
11151
- var sessionModeStateSchema = import_zod2.z.object({
11152
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11153
- availableModes: import_zod2.z.array(sessionModeSchema),
11154
- currentModeId: import_zod2.z.string()
11155
- });
11156
- var planEntrySchema = import_zod2.z.object({
11157
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11158
- content: import_zod2.z.string(),
11159
- priority: import_zod2.z.union([import_zod2.z.literal("high"), import_zod2.z.literal("medium"), import_zod2.z.literal("low")]),
11160
- status: import_zod2.z.union([
11161
- import_zod2.z.literal("pending"),
11162
- import_zod2.z.literal("in_progress"),
11163
- import_zod2.z.literal("completed")
11164
- ])
11165
- });
11166
- var availableCommandInputSchema = unstructuredCommandInputSchema;
11167
- var clientNotificationSchema = import_zod2.z.union([
11168
- cancelNotificationSchema,
11169
- extNotificationSchema
11170
- ]);
11171
- var createTerminalRequestSchema = import_zod2.z.object({
11172
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11173
- args: import_zod2.z.array(import_zod2.z.string()).optional(),
11174
- command: import_zod2.z.string(),
11175
- cwd: import_zod2.z.string().optional().nullable(),
11176
- env: import_zod2.z.array(envVariableSchema).optional(),
11177
- outputByteLimit: import_zod2.z.number().optional().nullable(),
11178
- sessionId: import_zod2.z.string()
11179
- });
11180
- var terminalOutputResponseSchema = import_zod2.z.object({
11181
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11182
- exitStatus: terminalExitStatusSchema.optional().nullable(),
11183
- output: import_zod2.z.string(),
11184
- truncated: import_zod2.z.boolean()
11185
- });
11186
- var newSessionRequestSchema = import_zod2.z.object({
11187
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11188
- cwd: import_zod2.z.string(),
11189
- mcpServers: import_zod2.z.array(mcpServerSchema)
11190
- });
11191
- var loadSessionRequestSchema = import_zod2.z.object({
11192
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11193
- cwd: import_zod2.z.string(),
11194
- mcpServers: import_zod2.z.array(mcpServerSchema),
11195
- sessionId: import_zod2.z.string()
11196
- });
11197
- var promptRequestSchema = import_zod2.z.object({
11198
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11199
- prompt: import_zod2.z.array(contentBlockSchema),
11200
- sessionId: import_zod2.z.string()
11201
- });
11202
- var newSessionResponseSchema = import_zod2.z.object({
11203
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11204
- models: sessionModelStateSchema.optional().nullable(),
11205
- modes: sessionModeStateSchema.optional().nullable(),
11206
- sessionId: import_zod2.z.string()
11207
- });
11208
- var loadSessionResponseSchema = import_zod2.z.object({
11209
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11210
- models: sessionModelStateSchema.optional().nullable(),
11211
- modes: sessionModeStateSchema.optional().nullable()
11212
- });
11213
- var toolCallUpdateSchema = import_zod2.z.object({
11214
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11215
- content: import_zod2.z.array(toolCallContentSchema).optional().nullable(),
11216
- kind: toolKindSchema.optional().nullable(),
11217
- locations: import_zod2.z.array(toolCallLocationSchema).optional().nullable(),
11218
- rawInput: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11219
- rawOutput: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11220
- status: toolCallStatusSchema.optional().nullable(),
11221
- title: import_zod2.z.string().optional().nullable(),
11222
- toolCallId: import_zod2.z.string()
11223
- });
11224
- var clientCapabilitiesSchema = import_zod2.z.object({
11225
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11226
- fs: fileSystemCapabilitySchema.optional(),
11227
- terminal: import_zod2.z.boolean().optional()
11228
- });
11229
- var agentCapabilitiesSchema = import_zod2.z.object({
11230
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11231
- loadSession: import_zod2.z.boolean().optional(),
11232
- mcpCapabilities: mcpCapabilitiesSchema.optional(),
11233
- promptCapabilities: promptCapabilitiesSchema.optional()
11234
- });
11235
- var availableCommandSchema = import_zod2.z.object({
11236
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11237
- description: import_zod2.z.string(),
11238
- input: availableCommandInputSchema.optional().nullable(),
11239
- name: import_zod2.z.string()
11240
- });
11241
- var clientResponseSchema = import_zod2.z.union([
11242
- writeTextFileResponseSchema,
11243
- readTextFileResponseSchema,
11244
- requestPermissionResponseSchema,
11245
- createTerminalResponseSchema,
11246
- terminalOutputResponseSchema,
11247
- releaseTerminalResponseSchema,
11248
- waitForTerminalExitResponseSchema,
11249
- killTerminalResponseSchema,
11250
- extMethodResponseSchema
11251
- ]);
11252
- var requestPermissionRequestSchema = import_zod2.z.object({
11253
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11254
- options: import_zod2.z.array(permissionOptionSchema),
11255
- sessionId: import_zod2.z.string(),
11256
- toolCall: toolCallUpdateSchema
11257
- });
11258
- var initializeRequestSchema = import_zod2.z.object({
11259
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11260
- clientCapabilities: clientCapabilitiesSchema.optional(),
11261
- protocolVersion: import_zod2.z.number()
11262
- });
11263
- var initializeResponseSchema = import_zod2.z.object({
11264
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11265
- agentCapabilities: agentCapabilitiesSchema.optional(),
11266
- authMethods: import_zod2.z.array(authMethodSchema).optional(),
11267
- protocolVersion: import_zod2.z.number()
11268
- });
11269
- var sessionNotificationSchema = import_zod2.z.object({
11270
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11271
- sessionId: import_zod2.z.string(),
11272
- update: import_zod2.z.union([
11273
- import_zod2.z.object({
11274
- content: contentBlockSchema,
11275
- sessionUpdate: import_zod2.z.literal("user_message_chunk")
11276
- }),
11277
- import_zod2.z.object({
11278
- content: contentBlockSchema,
11279
- sessionUpdate: import_zod2.z.literal("agent_message_chunk")
11280
- }),
11281
- import_zod2.z.object({
11282
- content: contentBlockSchema,
11283
- sessionUpdate: import_zod2.z.literal("agent_thought_chunk")
11284
- }),
11285
- import_zod2.z.object({
11286
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11287
- content: import_zod2.z.array(toolCallContentSchema).optional(),
11288
- kind: import_zod2.z.union([
11289
- import_zod2.z.literal("read"),
11290
- import_zod2.z.literal("edit"),
11291
- import_zod2.z.literal("delete"),
11292
- import_zod2.z.literal("move"),
11293
- import_zod2.z.literal("search"),
11294
- import_zod2.z.literal("execute"),
11295
- import_zod2.z.literal("think"),
11296
- import_zod2.z.literal("fetch"),
11297
- import_zod2.z.literal("switch_mode"),
11298
- import_zod2.z.literal("other")
11299
- ]).optional(),
11300
- locations: import_zod2.z.array(toolCallLocationSchema).optional(),
11301
- rawInput: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11302
- rawOutput: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11303
- sessionUpdate: import_zod2.z.literal("tool_call"),
11304
- status: import_zod2.z.union([
11305
- import_zod2.z.literal("pending"),
11306
- import_zod2.z.literal("in_progress"),
11307
- import_zod2.z.literal("completed"),
11308
- import_zod2.z.literal("failed")
11309
- ]).optional(),
11310
- title: import_zod2.z.string(),
11311
- toolCallId: import_zod2.z.string()
11312
- }),
11313
- import_zod2.z.object({
11314
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11315
- content: import_zod2.z.array(toolCallContentSchema).optional().nullable(),
11316
- kind: toolKindSchema.optional().nullable(),
11317
- locations: import_zod2.z.array(toolCallLocationSchema).optional().nullable(),
11318
- rawInput: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11319
- rawOutput: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11320
- sessionUpdate: import_zod2.z.literal("tool_call_update"),
11321
- status: toolCallStatusSchema.optional().nullable(),
11322
- title: import_zod2.z.string().optional().nullable(),
11323
- toolCallId: import_zod2.z.string()
11324
- }),
11325
- import_zod2.z.object({
11326
- _meta: import_zod2.z.record(import_zod2.z.unknown()).optional(),
11327
- entries: import_zod2.z.array(planEntrySchema),
11328
- sessionUpdate: import_zod2.z.literal("plan")
11329
- }),
11330
- import_zod2.z.object({
11331
- availableCommands: import_zod2.z.array(availableCommandSchema),
11332
- sessionUpdate: import_zod2.z.literal("available_commands_update")
11333
- }),
11334
- import_zod2.z.object({
11335
- currentModeId: sessionModeIdSchema,
11336
- sessionUpdate: import_zod2.z.literal("current_mode_update")
11337
- })
11338
- ])
11339
- });
11340
- var clientRequestSchema = import_zod2.z.union([
11341
- writeTextFileRequestSchema,
11342
- readTextFileRequestSchema,
11343
- requestPermissionRequestSchema,
11344
- createTerminalRequestSchema,
11345
- terminalOutputRequestSchema,
11346
- releaseTerminalRequestSchema,
11347
- waitForTerminalExitRequestSchema,
11348
- killTerminalCommandRequestSchema,
11349
- extMethodRequestSchema
11350
- ]);
11351
- var agentRequestSchema = import_zod2.z.union([
11352
- initializeRequestSchema,
11353
- authenticateRequestSchema,
11354
- newSessionRequestSchema,
11355
- loadSessionRequestSchema,
11356
- setSessionModeRequestSchema,
11357
- promptRequestSchema,
11358
- setSessionModelRequestSchema,
11359
- extMethodRequest1Schema
11360
- ]);
11361
- var agentResponseSchema = import_zod2.z.union([
11362
- initializeResponseSchema,
11363
- authenticateResponseSchema,
11364
- newSessionResponseSchema,
11365
- loadSessionResponseSchema,
11366
- setSessionModeResponseSchema,
11367
- promptResponseSchema,
11368
- setSessionModelResponseSchema,
11369
- extMethodResponse1Schema
11370
- ]);
11371
- var agentNotificationSchema = import_zod2.z.union([
11372
- sessionNotificationSchema,
11373
- extNotification1Schema
11374
- ]);
11375
- var agentClientProtocolSchema = import_zod2.z.union([
11376
- clientRequestSchema,
11377
- clientResponseSchema,
11378
- clientNotificationSchema,
11379
- agentRequestSchema,
11380
- agentResponseSchema,
11381
- agentNotificationSchema
11382
- ]);
11383
-
11384
- // __mcpc__cli_latest/node_modules/@agentclientprotocol/sdk/dist/stream.js
11385
- function ndJsonStream(output, input) {
11386
- const textEncoder = new TextEncoder();
11387
- const textDecoder = new TextDecoder();
11388
- const readable = new ReadableStream({
11389
- async start(controller) {
11390
- let content = "";
11391
- const reader = input.getReader();
11392
- try {
11393
- while (true) {
11394
- const { value, done } = await reader.read();
11395
- if (done) {
11396
- break;
11397
- }
11398
- if (!value) {
11399
- continue;
11400
- }
11401
- content += textDecoder.decode(value, { stream: true });
11402
- const lines = content.split("\n");
11403
- content = lines.pop() || "";
11404
- for (const line of lines) {
11405
- const trimmedLine = line.trim();
11406
- if (trimmedLine) {
11407
- try {
11408
- const message = JSON.parse(trimmedLine);
11409
- controller.enqueue(message);
11410
- } catch (err) {
11411
- console.error("Failed to parse JSON message:", trimmedLine, err);
11412
- }
11413
- }
11414
- }
11415
- }
11416
- } finally {
11417
- reader.releaseLock();
11418
- controller.close();
11419
- }
11420
- }
11421
- });
11422
- const writable = new WritableStream({
11423
- async write(message) {
11424
- const content = JSON.stringify(message) + "\n";
11425
- const writer = output.getWriter();
11426
- try {
11427
- await writer.write(textEncoder.encode(content));
11428
- } finally {
11429
- writer.releaseLock();
11430
- }
11431
- }
11432
- });
11433
- return { readable, writable };
11434
- }
11435
-
11436
- // __mcpc__cli_latest/node_modules/@agentclientprotocol/sdk/dist/acp.js
11437
- var ClientSideConnection = class {
11438
- #connection;
11439
- /**
11440
- * Creates a new client-side connection to an agent.
11441
- *
11442
- * This establishes the communication channel between a client and agent
11443
- * following the ACP specification.
11444
- *
11445
- * @param toClient - A function that creates a Client handler to process incoming agent requests
11446
- * @param stream - The bidirectional message stream for communication. Typically created using
11447
- * {@link ndJsonStream} for stdio-based connections.
11448
- *
11449
- * See protocol docs: [Communication Model](https://agentclientprotocol.com/protocol/overview#communication-model)
11450
- */
11451
- constructor(toClient, stream) {
11452
- const client = toClient(this);
11453
- const requestHandler = async (method, params) => {
11454
- switch (method) {
11455
- case CLIENT_METHODS.fs_write_text_file: {
11456
- const validatedParams = writeTextFileRequestSchema.parse(params);
11457
- return client.writeTextFile?.(validatedParams);
11458
- }
11459
- case CLIENT_METHODS.fs_read_text_file: {
11460
- const validatedParams = readTextFileRequestSchema.parse(params);
11461
- return client.readTextFile?.(validatedParams);
11462
- }
11463
- case CLIENT_METHODS.session_request_permission: {
11464
- const validatedParams = requestPermissionRequestSchema.parse(params);
11465
- return client.requestPermission(validatedParams);
11466
- }
11467
- case CLIENT_METHODS.terminal_create: {
11468
- const validatedParams = createTerminalRequestSchema.parse(params);
11469
- return client.createTerminal?.(validatedParams);
11470
- }
11471
- case CLIENT_METHODS.terminal_output: {
11472
- const validatedParams = terminalOutputRequestSchema.parse(params);
11473
- return client.terminalOutput?.(validatedParams);
11474
- }
11475
- case CLIENT_METHODS.terminal_release: {
11476
- const validatedParams = releaseTerminalRequestSchema.parse(params);
11477
- const result = await client.releaseTerminal?.(validatedParams);
11478
- return result ?? {};
11479
- }
11480
- case CLIENT_METHODS.terminal_wait_for_exit: {
11481
- const validatedParams = waitForTerminalExitRequestSchema.parse(params);
11482
- return client.waitForTerminalExit?.(validatedParams);
11483
- }
11484
- case CLIENT_METHODS.terminal_kill: {
11485
- const validatedParams = killTerminalCommandRequestSchema.parse(params);
11486
- const result = await client.killTerminal?.(validatedParams);
11487
- return result ?? {};
11488
- }
11489
- default:
11490
- if (method.startsWith("_")) {
11491
- const customMethod = method.substring(1);
11492
- if (!client.extMethod) {
11493
- throw RequestError.methodNotFound(method);
11494
- }
11495
- return client.extMethod(customMethod, params);
11496
- }
11497
- throw RequestError.methodNotFound(method);
11498
- }
11499
- };
11500
- const notificationHandler = async (method, params) => {
11501
- switch (method) {
11502
- case CLIENT_METHODS.session_update: {
11503
- const validatedParams = sessionNotificationSchema.parse(params);
11504
- return client.sessionUpdate(validatedParams);
11505
- }
11506
- default:
11507
- if (method.startsWith("_")) {
11508
- const customMethod = method.substring(1);
11509
- if (!client.extNotification) {
11510
- return;
11511
- }
11512
- return client.extNotification(customMethod, params);
11513
- }
11514
- throw RequestError.methodNotFound(method);
11515
- }
11516
- };
11517
- this.#connection = new Connection(requestHandler, notificationHandler, stream);
11518
- }
11519
- /**
11520
- * Establishes the connection with a client and negotiates protocol capabilities.
11521
- *
11522
- * This method is called once at the beginning of the connection to:
11523
- * - Negotiate the protocol version to use
11524
- * - Exchange capability information between client and agent
11525
- * - Determine available authentication methods
11526
- *
11527
- * The agent should respond with its supported protocol version and capabilities.
11528
- *
11529
- * See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/initialization)
11530
- */
11531
- async initialize(params) {
11532
- return await this.#connection.sendRequest(AGENT_METHODS.initialize, params);
11533
- }
11534
- /**
11535
- * Creates a new conversation session with the agent.
11536
- *
11537
- * Sessions represent independent conversation contexts with their own history and state.
11538
- *
11539
- * The agent should:
11540
- * - Create a new session context
11541
- * - Connect to any specified MCP servers
11542
- * - Return a unique session ID for future requests
11543
- *
11544
- * May return an `auth_required` error if the agent requires authentication.
11545
- *
11546
- * See protocol docs: [Session Setup](https://agentclientprotocol.com/protocol/session-setup)
11547
- */
11548
- async newSession(params) {
11549
- return await this.#connection.sendRequest(AGENT_METHODS.session_new, params);
11550
- }
11551
- /**
11552
- * Loads an existing session to resume a previous conversation.
11553
- *
11554
- * This method is only available if the agent advertises the `loadSession` capability.
11555
- *
11556
- * The agent should:
11557
- * - Restore the session context and conversation history
11558
- * - Connect to the specified MCP servers
11559
- * - Stream the entire conversation history back to the client via notifications
11560
- *
11561
- * See protocol docs: [Loading Sessions](https://agentclientprotocol.com/protocol/session-setup#loading-sessions)
11562
- */
11563
- async loadSession(params) {
11564
- return await this.#connection.sendRequest(AGENT_METHODS.session_load, params) ?? {};
11565
- }
11566
- /**
11567
- * Sets the operational mode for a session.
11568
- *
11569
- * Allows switching between different agent modes (e.g., "ask", "architect", "code")
11570
- * that affect system prompts, tool availability, and permission behaviors.
11571
- *
11572
- * The mode must be one of the modes advertised in `availableModes` during session
11573
- * creation or loading. Agents may also change modes autonomously and notify the
11574
- * client via `current_mode_update` notifications.
11575
- *
11576
- * This method can be called at any time during a session, whether the Agent is
11577
- * idle or actively generating a turn.
11578
- *
11579
- * See protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)
11580
- */
11581
- async setSessionMode(params) {
11582
- return await this.#connection.sendRequest(AGENT_METHODS.session_set_mode, params) ?? {};
11583
- }
11584
- /**
11585
- * **UNSTABLE**
11586
- *
11587
- * This capability is not part of the spec yet, and may be removed or changed at any point.
11588
- *
11589
- * Select a model for a given session.
11590
- */
11591
- async setSessionModel(params) {
11592
- return await this.#connection.sendRequest(AGENT_METHODS.session_set_model, params) ?? {};
11593
- }
11594
- /**
11595
- * Authenticates the client using the specified authentication method.
11596
- *
11597
- * Called when the agent requires authentication before allowing session creation.
11598
- * The client provides the authentication method ID that was advertised during initialization.
11599
- *
11600
- * After successful authentication, the client can proceed to create sessions with
11601
- * `newSession` without receiving an `auth_required` error.
11602
- *
11603
- * See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/initialization)
11604
- */
11605
- async authenticate(params) {
11606
- return await this.#connection.sendRequest(AGENT_METHODS.authenticate, params) ?? {};
11607
- }
11608
- /**
11609
- * Processes a user prompt within a session.
11610
- *
11611
- * This method handles the whole lifecycle of a prompt:
11612
- * - Receives user messages with optional context (files, images, etc.)
11613
- * - Processes the prompt using language models
11614
- * - Reports language model content and tool calls to the Clients
11615
- * - Requests permission to run tools
11616
- * - Executes any requested tool calls
11617
- * - Returns when the turn is complete with a stop reason
11618
- *
11619
- * See protocol docs: [Prompt Turn](https://agentclientprotocol.com/protocol/prompt-turn)
11620
- */
11621
- async prompt(params) {
11622
- return await this.#connection.sendRequest(AGENT_METHODS.session_prompt, params);
11623
- }
11624
- /**
11625
- * Cancels ongoing operations for a session.
11626
- *
11627
- * This is a notification sent by the client to cancel an ongoing prompt turn.
11628
- *
11629
- * Upon receiving this notification, the Agent SHOULD:
11630
- * - Stop all language model requests as soon as possible
11631
- * - Abort all tool call invocations in progress
11632
- * - Send any pending `session/update` notifications
11633
- * - Respond to the original `session/prompt` request with `StopReason::Cancelled`
11634
- *
11635
- * See protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/prompt-turn#cancellation)
11636
- */
11637
- async cancel(params) {
11638
- return await this.#connection.sendNotification(AGENT_METHODS.session_cancel, params);
11639
- }
11640
- /**
11641
- * Extension method
11642
- *
11643
- * Allows the Client to send an arbitrary request that is not part of the ACP spec.
11644
- */
11645
- async extMethod(method, params) {
11646
- return await this.#connection.sendRequest(`_${method}`, params);
11647
- }
11648
- /**
11649
- * Extension notification
11650
- *
11651
- * Allows the Client to send an arbitrary notification that is not part of the ACP spec.
11652
- */
11653
- async extNotification(method, params) {
11654
- return await this.#connection.sendNotification(`_${method}`, params);
11655
- }
11656
- };
11657
- var Connection = class {
11658
- #pendingResponses = /* @__PURE__ */ new Map();
11659
- #nextRequestId = 0;
11660
- #requestHandler;
11661
- #notificationHandler;
11662
- #stream;
11663
- #writeQueue = Promise.resolve();
11664
- constructor(requestHandler, notificationHandler, stream) {
11665
- this.#requestHandler = requestHandler;
11666
- this.#notificationHandler = notificationHandler;
11667
- this.#stream = stream;
11668
- this.#receive();
11669
- }
11670
- async #receive() {
11671
- const reader = this.#stream.readable.getReader();
11672
- try {
11673
- while (true) {
11674
- const { value: message, done } = await reader.read();
11675
- if (done) {
11676
- break;
11677
- }
11678
- if (!message) {
11679
- continue;
11680
- }
11681
- try {
11682
- this.#processMessage(message);
11683
- } catch (err) {
11684
- console.error("Unexpected error during message processing:", message, err);
11685
- if ("id" in message && message.id !== void 0) {
11686
- this.#sendMessage({
11687
- jsonrpc: "2.0",
11688
- id: message.id,
11689
- error: {
11690
- code: -32700,
11691
- message: "Parse error"
11692
- }
11693
- });
11694
- }
11695
- }
11696
- }
11697
- } finally {
11698
- reader.releaseLock();
11699
- }
11700
- }
11701
- async #processMessage(message) {
11702
- if ("method" in message && "id" in message) {
11703
- const response = await this.#tryCallRequestHandler(message.method, message.params);
11704
- if ("error" in response) {
11705
- console.error("Error handling request", message, response.error);
11706
- }
11707
- await this.#sendMessage({
11708
- jsonrpc: "2.0",
11709
- id: message.id,
11710
- ...response
11711
- });
11712
- } else if ("method" in message) {
11713
- const response = await this.#tryCallNotificationHandler(message.method, message.params);
11714
- if ("error" in response) {
11715
- console.error("Error handling notification", message, response.error);
11716
- }
11717
- } else if ("id" in message) {
11718
- this.#handleResponse(message);
11719
- } else {
11720
- console.error("Invalid message", { message });
11721
- }
11722
- }
11723
- async #tryCallRequestHandler(method, params) {
11724
- try {
11725
- const result = await this.#requestHandler(method, params);
11726
- return { result: result ?? null };
11727
- } catch (error) {
11728
- if (error instanceof RequestError) {
11729
- return error.toResult();
11730
- }
11731
- if (error instanceof import_zod3.z.ZodError) {
11732
- return RequestError.invalidParams(error.format()).toResult();
11733
- }
11734
- let details;
11735
- if (error instanceof Error) {
11736
- details = error.message;
11737
- } else if (typeof error === "object" && error != null && "message" in error && typeof error.message === "string") {
11738
- details = error.message;
11739
- }
11740
- try {
11741
- return RequestError.internalError(details ? JSON.parse(details) : {}).toResult();
11742
- } catch {
11743
- return RequestError.internalError({ details }).toResult();
11744
- }
11745
- }
11746
- }
11747
- async #tryCallNotificationHandler(method, params) {
11748
- try {
11749
- await this.#notificationHandler(method, params);
11750
- return { result: null };
11751
- } catch (error) {
11752
- if (error instanceof RequestError) {
11753
- return error.toResult();
11754
- }
11755
- if (error instanceof import_zod3.z.ZodError) {
11756
- return RequestError.invalidParams(error.format()).toResult();
11757
- }
11758
- let details;
11759
- if (error instanceof Error) {
11760
- details = error.message;
11761
- } else if (typeof error === "object" && error != null && "message" in error && typeof error.message === "string") {
11762
- details = error.message;
11763
- }
11764
- try {
11765
- return RequestError.internalError(details ? JSON.parse(details) : {}).toResult();
11766
- } catch {
11767
- return RequestError.internalError({ details }).toResult();
11768
- }
11769
- }
11770
- }
11771
- #handleResponse(response) {
11772
- const pendingResponse = this.#pendingResponses.get(response.id);
11773
- if (pendingResponse) {
11774
- if ("result" in response) {
11775
- pendingResponse.resolve(response.result);
11776
- } else if ("error" in response) {
11777
- pendingResponse.reject(response.error);
11778
- }
11779
- this.#pendingResponses.delete(response.id);
11780
- } else {
11781
- console.error("Got response to unknown request", response.id);
11782
- }
11783
- }
11784
- async sendRequest(method, params) {
11785
- const id = this.#nextRequestId++;
11786
- const responsePromise = new Promise((resolve3, reject) => {
11787
- this.#pendingResponses.set(id, { resolve: resolve3, reject });
11788
- });
11789
- await this.#sendMessage({ jsonrpc: "2.0", id, method, params });
11790
- return responsePromise;
11791
- }
11792
- async sendNotification(method, params) {
11793
- await this.#sendMessage({ jsonrpc: "2.0", method, params });
11794
- }
11795
- async #sendMessage(message) {
11796
- this.#writeQueue = this.#writeQueue.then(async () => {
11797
- const writer = this.#stream.writable.getWriter();
11798
- try {
11799
- await writer.write(message);
11800
- } finally {
11801
- writer.releaseLock();
11802
- }
11803
- }).catch((error) => {
11804
- console.error("ACP write error:", error);
11805
- });
11806
- return this.#writeQueue;
11807
- }
11808
- };
11809
- var RequestError = class _RequestError extends Error {
11810
- code;
11811
- data;
11812
- constructor(code, message, data) {
11813
- super(message);
11814
- this.code = code;
11815
- this.name = "RequestError";
11816
- this.data = data;
11817
- }
11818
- /**
11819
- * Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.
11820
- */
11821
- static parseError(data) {
11822
- return new _RequestError(-32700, "Parse error", data);
11823
- }
11824
- /**
11825
- * The JSON sent is not a valid Request object.
11826
- */
11827
- static invalidRequest(data) {
11828
- return new _RequestError(-32600, "Invalid request", data);
11829
- }
11830
- /**
11831
- * The method does not exist / is not available.
11832
- */
11833
- static methodNotFound(method) {
11834
- return new _RequestError(-32601, "Method not found", { method });
11835
- }
11836
- /**
11837
- * Invalid method parameter(s).
11838
- */
11839
- static invalidParams(data) {
11840
- return new _RequestError(-32602, "Invalid params", data);
11841
- }
11842
- /**
11843
- * Internal JSON-RPC error.
11844
- */
11845
- static internalError(data) {
11846
- return new _RequestError(-32603, "Internal error", data);
11847
- }
11848
- /**
11849
- * Authentication required.
11850
- */
11851
- static authRequired(data) {
11852
- return new _RequestError(-32e3, "Authentication required", data);
11853
- }
11854
- /**
11855
- * Resource, such as a file, was not found
11856
- */
11857
- static resourceNotFound(uri) {
11858
- return new _RequestError(-32002, "Resource not found", uri && { uri });
11859
- }
11860
- toResult() {
11861
- return {
11862
- error: {
11863
- code: this.code,
11864
- message: this.message,
11865
- data: this.data
11866
- }
11867
- };
11868
- }
11869
- toErrorResponse() {
11870
- return {
11871
- code: this.code,
11872
- message: this.message,
11873
- data: this.data
11874
- };
11875
- }
11876
- };
11877
-
11878
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__acp-ai-provider/src/language-model.js
11879
- var import_node_child_process = require("node:child_process");
11880
- var import_node_process9 = __toESM(require("node:process"), 1);
11881
- var import_node_stream2 = require("node:stream");
11882
- var import_zod4 = __toESM(require("zod"), 1);
11883
-
11884
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__acp-ai-provider/src/format-tool-error.js
11885
- function formatToolError(toolResult) {
11886
- if (!toolResult || toolResult.length === 0) return "Unknown tool error";
11887
- const parts = [];
11888
- for (const blk of toolResult) {
11889
- if (blk.type === "content") {
11890
- if (blk.content.type === "text") {
11891
- parts.push(blk.content.text);
11892
- }
11893
- }
11894
- }
11895
- return parts.join("\n");
11896
- }
11897
-
11898
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__acp-ai-provider/src/tool-proxy/tool-proxy-host.js
11899
- var import_node_net = require("node:net");
11900
-
11901
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__acp-ai-provider/src/tool-proxy/json-rpc.js
11902
- function createResponse(id, result) {
11903
- return {
11904
- jsonrpc: "2.0",
11905
- id,
11906
- result
11907
- };
11908
- }
11909
- function createErrorResponse(id, code, message, data) {
11910
- const error = {
11911
- code,
11912
- message
11913
- };
11914
- if (data !== void 0) {
11915
- error.data = data;
11916
- }
11917
- return {
11918
- jsonrpc: "2.0",
11919
- id,
11920
- error
11921
- };
11922
- }
11923
- function parseMessage(line) {
11924
- try {
11925
- const parsed = JSON.parse(line);
11926
- if (parsed.jsonrpc !== "2.0") return null;
11927
- return parsed;
11928
- } catch {
11929
- return null;
11930
- }
11931
- }
11932
- function serializeMessage2(message) {
11933
- return JSON.stringify(message);
11934
- }
11935
-
11936
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__acp-ai-provider/src/tool-proxy/types.js
11937
- var JsonRpcErrorCode = {
11938
- PARSE_ERROR: -32700,
11939
- INVALID_REQUEST: -32600,
11940
- METHOD_NOT_FOUND: -32601,
11941
- INVALID_PARAMS: -32602,
11942
- INTERNAL_ERROR: -32603
11943
- };
11944
- var ProxyMethod = {
11945
- // Host -> Proxy
11946
- REGISTER_TOOLS: "registerTools",
11947
- // Proxy -> Host
11948
- CALL_HANDLER: "callHandler"
11949
- };
11950
-
11951
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__acp-ai-provider/src/tool-proxy/tool-proxy-runtime.js
11952
- var RUNTIME_CODE = `
11953
- /* MCP Protocol Version 2024-11-05 */
11954
- const isDeno=typeof Deno!=="undefined",MCP_VER="2024-11-05";
11955
- let tools=[],host=null,pending=new Map,buf="",hbuf="",rid=0;
11956
- const env=k=>isDeno?Deno.env.get(k):process.env[k];
11957
- const write=async m=>{
11958
- const s=JSON.stringify(m)+"\\n";
11959
- if(isDeno)await Deno.stdout.write(new TextEncoder().encode(s));
11960
- else process.stdout.write(s);
11961
- };
11962
- const send=(id,r,e)=>write({jsonrpc:"2.0",id,...(e?{error:e}:{result:r})});
11963
- const hostReq=(m,p)=>new Promise((res,rej)=>{
11964
- const id="r-"+ ++rid;
11965
- const s=JSON.stringify({jsonrpc:"2.0",id,method:m,params:p})+"\\n";
11966
- if(isDeno)host.write(new TextEncoder().encode(s));
11967
- else host.write(s);
11968
- const t=setTimeout(()=>{pending.delete(id);rej(new Error("timeout"))},30000);
11969
- pending.set(id,{resolve:v=>{clearTimeout(t);res(v)},reject:e=>{clearTimeout(t);rej(e)}});
11970
- });
11971
- const init=async()=>{
11972
- const p=parseInt(env("ACP_TOOL_PROXY_PORT")||"0",10);
11973
- if(p){
11974
- if(isDeno){
11975
- host=await Deno.connect({hostname:"127.0.0.1",port:p});
11976
- (async()=>{
11977
- const d=new TextDecoder(),b=new Uint8Array(65536);
11978
- while(true){const n=await host.read(b);if(!n)break;
11979
- hbuf+=d.decode(b.subarray(0,n));let ls=hbuf.split("\\n");hbuf=ls.pop();
11980
- for(let l of ls)if(l.trim())onHostMsg(l)}})();
11981
- }else{
11982
- host=require("net").createConnection({host:"127.0.0.1",port:p});
11983
- await new Promise(r=>host.on("connect",r));
11984
- host.on("data",d=>{hbuf+=d;let ls=hbuf.split("\\n");hbuf=ls.pop();
11985
- for(let l of ls)if(l.trim())onHostMsg(l)});
11986
- }
11987
- try{tools=await hostReq("getTools")}catch(e){
11988
- const m="Failed to get tools: "+e.message+"\\n";
11989
- if(isDeno)Deno.stderr.write(new TextEncoder().encode(m));
11990
- else process.stderr.write(m);
11991
- }
11992
- }
11993
- };
11994
- const onHostMsg=l=>{try{let r=JSON.parse(l),h=pending.get(r.id);
11995
- if(h){pending.delete(r.id);r.error?h.reject(new Error(r.error.message)):h.resolve(r.result)}}catch{}};
11996
- const handle=async l=>{let m;try{m=JSON.parse(l)}catch{return}if(m.jsonrpc!=="2.0")return;
11997
- if(m.method==="initialize")send(m.id,{protocolVersion:MCP_VER,capabilities:{tools:{}},serverInfo:{name:"proxy",version:"1.0"}});
11998
- else if(m.method==="notifications/initialized");
11999
- else if(m.method==="tools/list")send(m.id,{tools:tools.map(t=>({name:t.name,description:t.description,inputSchema:t.inputSchema}))});
12000
- else if(m.method==="tools/call"){let p=m.params,t=tools.find(x=>x.name===p.name);
12001
- if(!t)send(m.id,null,{code:-32601,message:"Not found"});
12002
- else try{let r=await hostReq("callHandler",{name:p.name,args:p.arguments||{}});send(m.id,r)}
12003
- catch(e){send(m.id,{content:[{type:"text",text:"Error: "+e.message}],isError:true})}}
12004
- else send(m.id,null,{code:-32601,message:"Unknown"});
12005
- };
12006
- init().then(async()=>{
12007
- if(isDeno){
12008
- const d=new TextDecoder(),b=new Uint8Array(65536);
12009
- while(true){const n=await Deno.stdin.read(b);if(!n)break;
12010
- 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)}
12011
- }else{
12012
- process.stdin.setEncoding("utf8");
12013
- 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)});
12014
- }
12015
- });
12016
- `.trim().replace(/\n/g, "");
12017
-
12018
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__acp-ai-provider/src/tool-proxy/tool-proxy-host.js
12019
- var ToolProxyHost = class {
12020
- server = null;
12021
- connections = [];
12022
- tools = /* @__PURE__ */ new Map();
12023
- serverName;
12024
- port = 0;
12025
- constructor(name = "acp-tool-proxy") {
12026
- this.serverName = name;
12027
- }
12028
- /**
12029
- * Register an AI SDK tool to be exposed through the proxy
12030
- */
12031
- registerTool(name, tool3) {
12032
- this.tools.set(name, tool3);
12033
- }
12034
- /**
12035
- * Register multiple tools at once
12036
- */
12037
- registerTools(tools) {
12038
- for (const [name, tool3] of Object.entries(tools)) {
12039
- this.registerTool(name, tool3);
12040
- }
12041
- }
12042
- /**
12043
- * Get tool definitions for the runtime
12044
- */
12045
- getToolDefinitions() {
12046
- const definitions = [];
12047
- for (const [name, tool3] of this.tools.entries()) {
12048
- definitions.push({
12049
- name,
12050
- description: tool3.description || `Tool: ${name}`,
12051
- // inputSchema from Tool can be Zod or JSON schema, cast to JSON schema format
12052
- inputSchema: tool3.inputSchema || {
12053
- type: "object",
12054
- properties: {}
12055
- }
12056
- });
12057
- }
12058
- return definitions;
12059
- }
12060
- /**
12061
- * Start TCP server and return MCP server config for ACP
12062
- */
12063
- async start() {
12064
- if (!this.server) {
12065
- await this.startServer();
12066
- }
12067
- return this.getServerConfig();
12068
- }
12069
- /**
12070
- * Get MCP server configuration
12071
- */
12072
- getServerConfig() {
12073
- return {
12074
- name: this.serverName,
12075
- command: "node",
12076
- args: [
12077
- "-e",
12078
- RUNTIME_CODE
12079
- ],
12080
- env: [
12081
- {
12082
- name: "ACP_TOOL_PROXY_PORT",
12083
- value: String(this.port)
12084
- }
12085
- ]
12086
- };
12087
- }
12088
- /**
12089
- * Start TCP server to receive tool execution requests
12090
- */
12091
- startServer() {
12092
- return new Promise((resolve3, reject) => {
12093
- this.server = (0, import_node_net.createServer)((socket) => {
12094
- this.handleConnection(socket);
12095
- });
12096
- this.server.on("error", (err) => {
12097
- reject(err);
12098
- });
12099
- this.server.listen(0, "127.0.0.1", () => {
12100
- const address = this.server.address();
12101
- if (typeof address === "object" && address) {
12102
- this.port = address.port;
12103
- resolve3();
12104
- } else {
12105
- reject(new Error("Failed to get server address"));
12106
- }
12107
- });
12108
- });
12109
- }
12110
- /**
12111
- * Handle incoming connection from runtime
12112
- */
12113
- handleConnection(socket) {
12114
- this.connections.push(socket);
12115
- let buffer = "";
12116
- socket.on("data", (data) => {
12117
- buffer += data.toString();
12118
- const lines = buffer.split("\n");
12119
- buffer = lines.pop() || "";
12120
- for (const line of lines) {
12121
- if (!line.trim()) continue;
12122
- const message = parseMessage(line);
12123
- if (!message) continue;
12124
- if ("method" in message) {
12125
- this.handleRequest(socket, message).catch((err) => console.error("[ToolProxy] Error handling request:", err));
12126
- }
12127
- }
12128
- });
12129
- socket.on("close", () => {
12130
- this.connections = this.connections.filter((c) => c !== socket);
12131
- });
12132
- socket.on("error", (err) => {
12133
- console.error("[ToolProxy] Socket error:", err);
12134
- });
12135
- }
12136
- /**
12137
- * Handle JSON-RPC request from runtime
12138
- */
12139
- async handleRequest(socket, request) {
12140
- try {
12141
- if (request.method === ProxyMethod.CALL_HANDLER) {
12142
- const params = request.params;
12143
- const tool3 = this.tools.get(params.name);
12144
- if (!tool3) {
12145
- this.sendResponse(socket, createErrorResponse(request.id, JsonRpcErrorCode.METHOD_NOT_FOUND, `Tool not found: ${params.name}`));
12146
- return;
12147
- }
12148
- if (!tool3.execute) {
12149
- this.sendResponse(socket, createErrorResponse(request.id, JsonRpcErrorCode.INTERNAL_ERROR, `Tool has no execute function: ${params.name}`));
12150
- return;
12151
- }
12152
- const result = await tool3.execute?.(params.args, {
12153
- toolCallId: params.name,
12154
- messages: []
12155
- });
12156
- const toolResult = {
12157
- content: [
12158
- {
12159
- type: "text",
12160
- text: typeof result === "string" ? result : JSON.stringify(result)
12161
- }
12162
- ]
12163
- };
12164
- this.sendResponse(socket, createResponse(request.id, toolResult));
12165
- } else if (request.method === "getTools") {
12166
- const definitions = this.getToolDefinitions();
12167
- this.sendResponse(socket, createResponse(request.id, definitions));
12168
- } else {
12169
- this.sendResponse(socket, createErrorResponse(request.id, JsonRpcErrorCode.METHOD_NOT_FOUND, `Unknown method: ${request.method}`));
12170
- }
12171
- } catch (error) {
12172
- this.sendResponse(socket, createErrorResponse(request.id, JsonRpcErrorCode.INTERNAL_ERROR, error instanceof Error ? error.message : String(error)));
12173
- }
12174
- }
12175
- /**
12176
- * Send response to runtime
12177
- */
12178
- sendResponse(socket, response) {
12179
- socket.write(serializeMessage2(response) + "\n");
12180
- }
12181
- /**
12182
- * Stop the TCP server
12183
- */
12184
- stop() {
12185
- for (const socket of this.connections) {
12186
- socket.destroy();
12187
- }
12188
- this.connections = [];
12189
- if (this.server) {
12190
- this.server.close();
12191
- this.server = null;
12192
- }
12193
- this.port = 0;
12194
- }
12195
- };
12196
-
12197
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__acp-ai-provider/src/acp-tool.js
12198
- var import_ai2 = require("ai");
12199
- var ACP_PROVIDER_AGENT_DYNAMIC_TOOL_NAME = "acp.acp_provider_agent_dynamic_tool";
12200
- var executeRegistry = /* @__PURE__ */ new Map();
12201
- function getACPDynamicTool() {
12202
- return {
12203
- [ACP_PROVIDER_AGENT_DYNAMIC_TOOL_NAME]: (0, import_ai2.tool)({
12204
- type: "provider-defined",
12205
- id: ACP_PROVIDER_AGENT_DYNAMIC_TOOL_NAME,
12206
- name: ACP_PROVIDER_AGENT_DYNAMIC_TOOL_NAME,
12207
- args: {},
12208
- inputSchema: (0, import_ai2.jsonSchema)({})
12209
- })
12210
- };
12211
- }
12212
- function getExecuteByName(name) {
12213
- return executeRegistry.get(name);
12214
- }
12215
- function hasRegisteredExecute(name) {
12216
- return executeRegistry.has(name);
12217
- }
12218
-
12219
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__acp-ai-provider/src/utils.js
12220
- function extractBase64Data(data) {
12221
- return data.includes(",") ? data.split(",")[1] : data;
12222
- }
12223
-
12224
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__acp-ai-provider/src/convert-utils.js
12225
- var import_ai3 = require("ai");
12226
- function convertAiSdkMessagesToAcp(options, isFreshSession) {
12227
- const messages = !isFreshSession ? options.prompt.filter((m) => m.role === "user").slice(-1) : options.prompt;
12228
- const contentBlocks = [];
12229
- for (const msg of messages) {
12230
- let prefix = "";
12231
- if (msg.role === "system") prefix = "System: ";
12232
- else if (msg.role === "assistant") prefix = "Assistant: ";
12233
- else if (msg.role === "tool") prefix = "Result: ";
12234
- if (Array.isArray(msg.content)) {
12235
- let isFirst = true;
12236
- for (const part of msg.content) {
12237
- if (part.type === "text") {
12238
- const text = isFirst ? `${prefix}${part.text} ` : part.text;
12239
- contentBlocks.push({
12240
- type: "text",
12241
- text
12242
- });
12243
- isFirst = false;
12244
- } else if (part.type === "tool-call") {
12245
- const toolCallText = `[Tool Call: ${part.toolName}(${JSON.stringify(part.input)})]`;
12246
- const text = isFirst ? `${prefix}${toolCallText} ` : toolCallText;
12247
- contentBlocks.push({
12248
- type: "text",
12249
- text
12250
- });
12251
- isFirst = false;
12252
- } else if (part.type === "tool-result") {
12253
- const resultData = part.result ?? part.output;
12254
- const resultText = JSON.stringify(resultData) ?? "null";
12255
- const text = isFirst ? `${prefix}${resultText} ` : resultText;
12256
- contentBlocks.push({
12257
- type: "text",
12258
- text
12259
- });
12260
- isFirst = false;
12261
- } else if (part.type === "file" && typeof part.data === "string") {
12262
- const type = part.mediaType.startsWith("image/") ? "image" : part.mediaType.startsWith("audio/") ? "audio" : null;
12263
- if (type) {
12264
- contentBlocks.push({
12265
- type,
12266
- mimeType: part.mediaType,
12267
- data: extractBase64Data(part.data)
12268
- });
12269
- }
12270
- }
12271
- }
12272
- } else if (typeof msg.content === "string") {
12273
- contentBlocks.push({
12274
- type: "text",
12275
- text: `${prefix}${msg.content} `
12276
- });
12277
- }
12278
- }
12279
- return contentBlocks;
12280
- }
12281
- function extractACPTools(tools, prepared = true) {
12282
- const acpTools2 = [];
12283
- if (!tools) {
12284
- return acpTools2;
12285
- }
12286
- const toolsArray = Array.isArray(tools) ? tools : Object.entries(tools).map(([name, tool3]) => ({
12287
- type: "function",
12288
- name,
12289
- ...tool3
12290
- }));
12291
- for (const t of toolsArray) {
12292
- if (t.type === "function") {
12293
- const toolWithSchema = t;
12294
- const toolInputSchema = toolWithSchema.inputSchema;
12295
- if (hasRegisteredExecute(t.name) && toolInputSchema) {
12296
- const execute = getExecuteByName(t.name);
12297
- if (execute) {
12298
- acpTools2.push({
12299
- ...t,
12300
- name: t.name,
12301
- inputSchema: prepared ? toolInputSchema : (0, import_ai3.asSchema)(toolInputSchema).jsonSchema,
12302
- execute
12303
- });
12304
- }
12305
- }
12306
- }
12307
- }
12308
- return acpTools2;
12309
- }
12310
-
12311
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__acp-ai-provider/src/language-model.js
12312
- var ACP_PROVIDER_AGENT_DYNAMIC_TOOL_NAME2 = "acp.acp_provider_agent_dynamic_tool";
12313
- var providerAgentDynamicToolSchema = import_zod4.default.object({
12314
- toolCallId: import_zod4.default.string().describe("The unique ID of the tool call."),
12315
- toolName: import_zod4.default.string().describe("The name of the tool being called."),
12316
- args: import_zod4.default.record(import_zod4.default.unknown()).describe("The input arguments for the tool call.")
12317
- });
12318
- var ACPAISDKClient = class {
12319
- onSessionUpdateCallback;
12320
- onPermissionRequestCallback;
12321
- setSessionUpdateHandler(handler) {
12322
- this.onSessionUpdateCallback = handler;
12323
- }
12324
- setPermissionRequestHandler(handler) {
12325
- this.onPermissionRequestCallback = handler;
12326
- }
12327
- sessionUpdate(params) {
12328
- if (this.onSessionUpdateCallback) {
12329
- this.onSessionUpdateCallback(params);
12330
- }
12331
- return Promise.resolve();
12332
- }
12333
- async requestPermission(params) {
12334
- if (this.onPermissionRequestCallback) {
12335
- return await this.onPermissionRequestCallback(params);
12336
- }
12337
- return {
12338
- outcome: {
12339
- outcome: "selected",
12340
- optionId: params.options[0]?.optionId || "allow"
12341
- }
12342
- };
12343
- }
12344
- writeTextFile(_params) {
12345
- throw new Error("File operations not implemented in language model client");
12346
- }
12347
- readTextFile(_params) {
12348
- throw new Error("File operations not implemented in language model client");
12349
- }
12350
- };
12351
- var ACPLanguageModel = class {
12352
- specificationVersion = "v2";
12353
- provider = "acp";
12354
- modelId;
12355
- modeId;
12356
- supportedUrls = {};
12357
- config;
12358
- agentProcess = null;
12359
- connection = null;
12360
- sessionId = null;
12361
- sessionResponse = null;
12362
- client = null;
12363
- currentModelId = null;
12364
- currentModeId = null;
12365
- isFreshSession = true;
12366
- // State for managing stream conversion
12367
- textBlockIndex = 0;
12368
- thinkBlockIndex = 0;
12369
- currentTextId = null;
12370
- currentThinkingId = null;
12371
- toolCallsMap = /* @__PURE__ */ new Map();
12372
- // Tool proxy for host-side tool execution
12373
- toolProxyHost = null;
12374
- constructor(modelId, modeId, config) {
12375
- this.modelId = modelId;
12376
- this.modeId = modeId;
12377
- this.config = config;
12378
- }
12379
- /**
12380
- * Resets the internal state used for stream conversion.
12381
- */
12382
- resetStreamState() {
12383
- this.textBlockIndex = 0;
12384
- this.thinkBlockIndex = 0;
12385
- this.currentTextId = null;
12386
- this.currentThinkingId = null;
12387
- this.toolCallsMap.clear();
12388
- }
12389
- /**
12390
- * Parses a 'tool_call' notification update into a structured object.
12391
- * Note: We only use rawInput for tool input (content is for UI display).
12392
- */
12393
- parseToolCall(update) {
12394
- if (update.sessionUpdate !== "tool_call") {
12395
- throw new Error("Invalid update type for parseToolCall");
12396
- }
12397
- const toolCallId = update.toolCallId;
12398
- const toolName = update.title || update.toolCallId;
12399
- const toolInput = update.rawInput ?? {};
12400
- return {
12401
- toolCallId,
12402
- toolName,
12403
- toolInput
12404
- };
12405
- }
12406
- /**
12407
- * Parses a 'tool_call_update' notification update into a structured object.
12408
- * Note: We only use rawOutput for tool result (content is for UI display).
12409
- */
12410
- parseToolResult(update) {
12411
- if (update.sessionUpdate !== "tool_call_update") {
12412
- throw new Error("Invalid update type for parseToolResult");
12413
- }
12414
- const toolCallId = update.toolCallId;
12415
- const toolName = update.title || update.toolCallId;
12416
- const toolResult = update.rawOutput ?? update.content ?? null;
12417
- const isError2 = update.status === "failed";
12418
- return {
12419
- toolCallId,
12420
- toolName,
12421
- toolResult,
12422
- isError: isError2,
12423
- status: update.status
12424
- };
12425
- }
12426
- /**
12427
- * Converts AI SDK prompt messages into ACP ContentBlock objects.
12428
- * When session exists, only extracts the last user message (history is in session).
12429
- * Prefixes text with role since ACP ContentBlock has no role field.
12430
- */
12431
- /**
12432
- * Ensures the ACP agent process is running and a session is established.
12433
- * @param acpTools - Tools from streamText options to proxy
12434
- */
12435
- /**
12436
- * Connects to the ACP agent process and initializes the protocol connection.
12437
- * Does NOT start a session.
12438
- */
12439
- async connectClient() {
12440
- if (this.connection) {
12441
- return;
12442
- }
12443
- if (!this.agentProcess) {
12444
- const sessionCwd = this.config.session?.cwd || (typeof import_node_process9.default.cwd === "function" ? import_node_process9.default.cwd() : "/");
12445
- this.agentProcess = (0, import_node_child_process.spawn)(this.config.command, this.config.args ?? [], {
12446
- stdio: [
12447
- "pipe",
12448
- "pipe",
12449
- "inherit"
12450
- ],
12451
- env: {
12452
- ...import_node_process9.default.env,
12453
- ...this.config.env
12454
- },
12455
- cwd: sessionCwd
12456
- });
12457
- if (!this.agentProcess.stdout || !this.agentProcess.stdin) {
12458
- throw new Error("Failed to spawn agent process with stdio");
12459
- }
12460
- const input = import_node_stream2.Writable.toWeb(this.agentProcess.stdin);
12461
- const output = import_node_stream2.Readable.toWeb(this.agentProcess.stdout);
12462
- this.client = new ACPAISDKClient();
12463
- this.connection = new ClientSideConnection(() => this.client, ndJsonStream(input, output));
12464
- }
12465
- if (!this.connection) {
12466
- throw new Error("Connection not initialized");
12467
- }
12468
- const initConfig = {
12469
- ...this.config.initialize,
12470
- protocolVersion: this.config.initialize?.protocolVersion ?? PROTOCOL_VERSION,
12471
- clientCapabilities: this.config.initialize?.clientCapabilities ?? {
12472
- fs: {
12473
- readTextFile: false,
12474
- writeTextFile: false
12475
- },
12476
- terminal: false
12477
- }
12478
- };
12479
- const initResult = await this.connection.initialize(initConfig);
12480
- const validAuthMethods = initResult.authMethods?.find((a) => a.id === this.config.authMethodId)?.id;
12481
- if ((initResult.authMethods?.length ?? 0) > 0) {
12482
- if (!this.config.authMethodId || !validAuthMethods) {
12483
- 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));
12484
- }
12485
- if (this.config.authMethodId && validAuthMethods) {
12486
- await this.connection.authenticate({
12487
- methodId: this.config.authMethodId ?? initResult.authMethods?.[0].id
12488
- });
12489
- }
12490
- }
12491
- }
12492
- /**
12493
- * Starts a new session or updates the existing one.
12494
- * Assumes connectClient() has been called.
12495
- */
12496
- async startSession(acpTools2) {
12497
- if (!this.connection) {
12498
- throw new Error("Not connected");
12499
- }
12500
- const mcpServers = [
12501
- ...this.config.session?.mcpServers ?? []
12502
- ];
12503
- let toolsAdded = false;
12504
- if (acpTools2 && acpTools2.length > 0 && !this.toolProxyHost) {
12505
- console.log("[acp-ai-provider] Setting up tool proxy for client-side tools...", acpTools2.map((t) => t.name));
12506
- this.toolProxyHost = new ToolProxyHost("acp-ai-sdk-tools");
12507
- for (const t of acpTools2) {
12508
- this.toolProxyHost.registerTool(t.name, t);
12509
- }
12510
- toolsAdded = true;
12511
- }
12512
- if (this.toolProxyHost) {
12513
- const proxyConfig = await this.toolProxyHost.start();
12514
- mcpServers.push(proxyConfig);
12515
- }
12516
- if (this.sessionId && toolsAdded) {
12517
- this.sessionResponse = await this.connection.newSession({
12518
- ...this.config.session,
12519
- cwd: this.config.session?.cwd ?? import_node_process9.default.cwd(),
12520
- mcpServers
12521
- });
12522
- this.sessionId = this.sessionResponse.sessionId;
12523
- this.isFreshSession = true;
12524
- await this.applySessionDelay();
12525
- return;
12526
- }
12527
- if (this.sessionId) {
12528
- return;
12529
- }
12530
- if (this.config.existingSessionId) {
12531
- await this.connection.loadSession({
12532
- sessionId: this.config.existingSessionId,
12533
- cwd: this.config.session?.cwd ?? import_node_process9.default.cwd(),
12534
- mcpServers
12535
- });
12536
- this.sessionId = this.config.existingSessionId;
12537
- this.sessionResponse = {
12538
- sessionId: this.config.existingSessionId
12539
- };
12540
- this.isFreshSession = false;
12541
- } else {
12542
- this.sessionResponse = await this.connection.newSession({
12543
- ...this.config.session,
12544
- cwd: this.config.session?.cwd ?? import_node_process9.default.cwd(),
12545
- mcpServers
12546
- });
12547
- this.sessionId = this.sessionResponse.sessionId;
12548
- this.isFreshSession = true;
12549
- }
12550
- const { models, modes } = this.sessionResponse ?? {};
12551
- if (models?.currentModelId) {
12552
- this.currentModelId = models.currentModelId;
12553
- }
12554
- if (modes?.currentModeId) {
12555
- this.currentModeId = modes.currentModeId;
12556
- }
12557
- if (this.modelId && this.modelId !== this.currentModelId) {
12558
- await this.setModel(this.modelId);
12559
- this.currentModelId = this.modelId;
12560
- }
12561
- if (this.modeId && this.modeId !== this.currentModeId) {
12562
- await this.setMode(this.modeId);
12563
- this.currentModeId = this.modeId;
12564
- }
12565
- await this.applySessionDelay();
12566
- }
12567
- async applySessionDelay() {
12568
- if (this.config.sessionDelayMs) {
12569
- console.log(`[acp-ai-provider] Waiting ${this.config.sessionDelayMs}ms after session setup...`);
12570
- await new Promise((resolve3) => setTimeout(resolve3, this.config.sessionDelayMs));
12571
- }
12572
- }
12573
- /**
12574
- * Ensures the ACP agent process is running and a session is established.
12575
- * @param acpTools - Tools from streamText options to proxy
12576
- */
12577
- async ensureConnected(acpTools2) {
12578
- await this.connectClient();
12579
- await this.startSession(acpTools2);
12580
- }
12581
- /**
12582
- * Clears connection state. Skips if persistSession is enabled.
12583
- */
12584
- cleanup() {
12585
- if (this.config.persistSession) return;
12586
- this.forceCleanup();
12587
- }
12588
- /**
12589
- * Returns the current session ID.
12590
- */
12591
- getSessionId() {
12592
- return this.sessionId;
12593
- }
12594
- /**
12595
- * Initializes the session and returns session info (models, modes, meta).
12596
- * Call this before prompting to discover available options.
12597
- */
12598
- /**
12599
- * Initializes the session and returns session info (models, modes, meta).
12600
- * Call this before prompting to discover available options.
12601
- *
12602
- * @param acpTools - Optional list of tools to register during session initialization.
12603
- */
12604
- async initSession(tools) {
12605
- const acpTools2 = extractACPTools(tools, false);
12606
- await this.ensureConnected(acpTools2.length > 0 ? acpTools2 : void 0);
12607
- return this.sessionResponse;
12608
- }
12609
- /**
12610
- * Sets the session mode (e.g., "ask", "plan").
12611
- */
12612
- async setMode(modeId) {
12613
- if (!this.connection || !this.sessionId) {
12614
- throw new Error("Not connected. Call preconnect() first.");
12615
- }
12616
- const availableModes = this.sessionResponse?.modes?.availableModes;
12617
- if (availableModes) {
12618
- const foundMode = availableModes.find((m) => m.id === modeId);
12619
- if (!foundMode) {
12620
- const availableList = availableModes.map((m) => m.id).join(", ");
12621
- const currentInfo = this.sessionResponse?.modes?.currentModeId ? ` (Current: "${this.sessionResponse.modes.currentModeId}")` : "";
12622
- throw new Error(`Mode "${modeId}" is not available${currentInfo}. Available modes: ${availableList}`);
12623
- }
12624
- }
12625
- await this.connection.setSessionMode({
12626
- sessionId: this.sessionId,
12627
- modeId
12628
- });
12629
- this.currentModeId = modeId;
12630
- }
12631
- /**
12632
- * Sets the session model.
12633
- */
12634
- async setModel(modelId) {
12635
- if (!this.connection || !this.sessionId) {
12636
- throw new Error("Not connected. Call preconnect() first.");
12637
- }
12638
- const { models } = this.sessionResponse ?? {};
12639
- if (models?.availableModels) {
12640
- if (!models.availableModels.some((m) => m.modelId === modelId)) {
12641
- const availableList = models.availableModels.map((m) => m.modelId).join(", ");
12642
- const currentInfo = this.currentModelId ? ` (Current: "${this.currentModelId}")` : "";
12643
- throw new Error(`Model "${modelId}" is not available${currentInfo}. Available models: ${availableList}`);
12644
- }
12645
- }
12646
- await this.connection.setSessionModel({
12647
- sessionId: this.sessionId,
12648
- modelId
12649
- });
12650
- this.currentModelId = modelId;
12651
- }
12652
- /**
12653
- * Forces cleanup regardless of persistSession setting.
12654
- */
12655
- forceCleanup() {
12656
- if (this.toolProxyHost) {
12657
- this.toolProxyHost.stop();
12658
- this.toolProxyHost = null;
12659
- }
12660
- if (this.agentProcess) {
12661
- this.agentProcess.kill();
12662
- this.agentProcess.stdin?.end();
12663
- this.agentProcess.stdout?.destroy();
12664
- this.agentProcess = null;
12665
- }
12666
- this.connection = null;
12667
- this.sessionId = null;
12668
- this.sessionResponse = null;
12669
- this.client = null;
12670
- }
12671
- /**
12672
- * Emits raw content (plan, diffs, terminals) as raw stream parts.
12673
- * Plan data is emitted directly, while diffs and terminals are bound to a toolCallId.
12674
- */
12675
- emitRawContent(controller, data) {
12676
- if ("entries" in data) {
12677
- controller.enqueue({
12678
- type: "raw",
12679
- rawValue: JSON.stringify({
12680
- type: "plan",
12681
- entries: data.entries
12682
- })
12683
- });
12684
- return;
12685
- }
12686
- for (const item of data.content) {
12687
- if (item.type === "diff" || item.type === "terminal") {
12688
- controller.enqueue({
12689
- type: "raw",
12690
- rawValue: JSON.stringify({
12691
- ...item,
12692
- toolCallId: data.toolCallId
12693
- })
12694
- });
12695
- }
12696
- }
12697
- }
12698
- /**
12699
- * Standardized handler for converting SessionNotifications into
12700
- * LanguageModelV2StreamPart objects, pushing them onto a stream controller.
12701
- */
12702
- handleStreamNotification(controller, notification) {
12703
- const update = notification.update;
12704
- switch (update.sessionUpdate) {
12705
- case "plan":
12706
- this.emitRawContent(controller, {
12707
- type: "plan",
12708
- entries: update.entries
12709
- });
12710
- break;
12711
- case "agent_thought_chunk":
12712
- if (!this.currentThinkingId) {
12713
- this.currentThinkingId = `reasoning - ${this.thinkBlockIndex++} `;
12714
- controller.enqueue({
12715
- type: "reasoning-start",
12716
- id: this.currentThinkingId
12717
- });
12718
- }
12719
- controller.enqueue({
12720
- type: "reasoning-delta",
12721
- id: this.currentThinkingId,
12722
- delta: update.content.type === "text" ? update.content.text : ""
12723
- });
12724
- break;
12725
- case "agent_message_chunk":
12726
- if (this.currentThinkingId) {
12727
- controller.enqueue({
12728
- type: "reasoning-end",
12729
- id: this.currentThinkingId
12730
- });
12731
- this.currentThinkingId = null;
12732
- }
12733
- if (update.content.type === "text") {
12734
- const textChunk = update.content.text;
12735
- if (!this.currentTextId) {
12736
- this.currentTextId = `text - ${this.textBlockIndex++} `;
12737
- controller.enqueue({
12738
- type: "text-start",
12739
- id: this.currentTextId
12740
- });
12741
- }
12742
- controller.enqueue({
12743
- type: "text-delta",
12744
- id: this.currentTextId,
12745
- delta: textChunk
12746
- });
12747
- }
12748
- break;
12749
- case "tool_call": {
12750
- if (this.currentTextId) {
12751
- controller.enqueue({
12752
- type: "text-end",
12753
- id: this.currentTextId
12754
- });
12755
- this.currentTextId = null;
12756
- }
12757
- if (this.currentThinkingId) {
12758
- controller.enqueue({
12759
- type: "reasoning-end",
12760
- id: this.currentThinkingId
12761
- });
12762
- this.currentThinkingId = null;
12763
- }
12764
- const { toolCallId, toolName, toolInput } = this.parseToolCall(update);
12765
- const existingToolCall = this.toolCallsMap.get(toolCallId);
12766
- const hasInput = toolInput && typeof toolInput === "object" && Object.keys(toolInput).length > 0;
12767
- if (!existingToolCall) {
12768
- this.toolCallsMap.set(toolCallId, {
12769
- index: this.toolCallsMap.size,
12770
- name: toolName,
12771
- inputStarted: true,
12772
- inputAvailable: !!hasInput
12773
- });
12774
- controller.enqueue({
12775
- type: "tool-input-start",
12776
- id: toolCallId,
12777
- toolName
12778
- });
12779
- if (hasInput) {
12780
- controller.enqueue({
12781
- type: "tool-call",
12782
- toolCallId,
12783
- toolName: ACP_PROVIDER_AGENT_DYNAMIC_TOOL_NAME2,
12784
- input: JSON.stringify({
12785
- toolCallId,
12786
- toolName,
12787
- args: toolInput
12788
- })
12789
- });
12790
- }
12791
- } else if (!existingToolCall.inputAvailable && hasInput) {
12792
- existingToolCall.inputAvailable = true;
12793
- if (update.title && existingToolCall.name !== update.title && update.title !== toolCallId) {
12794
- existingToolCall.name = update.title;
12795
- }
12796
- controller.enqueue({
12797
- type: "tool-call",
12798
- toolCallId,
12799
- toolName: ACP_PROVIDER_AGENT_DYNAMIC_TOOL_NAME2,
12800
- input: JSON.stringify({
12801
- toolCallId,
12802
- toolName: existingToolCall.name,
12803
- args: toolInput
12804
- })
12805
- });
12806
- }
12807
- break;
12808
- }
12809
- case "tool_call_update": {
12810
- const { toolCallId, toolName, toolResult, isError: isError2, status } = this.parseToolResult(update);
12811
- let toolInfo = this.toolCallsMap.get(toolCallId);
12812
- if (status === "in_progress") {
12813
- if (!toolInfo) {
12814
- toolInfo = {
12815
- index: this.toolCallsMap.size,
12816
- name: toolName,
12817
- inputStarted: true,
12818
- inputAvailable: true
12819
- };
12820
- this.toolCallsMap.set(toolCallId, toolInfo);
12821
- controller.enqueue({
12822
- type: "tool-input-start",
12823
- id: toolCallId,
12824
- toolName
12825
- });
12826
- }
12827
- if (!toolInfo.inputAvailable) {
12828
- toolInfo.inputAvailable = true;
12829
- if (update.title && toolInfo.name !== update.title && update.title !== toolCallId) {
12830
- toolInfo.name = update.title;
12831
- }
12832
- controller.enqueue({
12833
- type: "tool-call",
12834
- toolCallId,
12835
- toolName: ACP_PROVIDER_AGENT_DYNAMIC_TOOL_NAME2,
12836
- input: JSON.stringify({
12837
- toolCallId,
12838
- toolName: toolInfo.name,
12839
- args: {}
12840
- })
12841
- });
12842
- }
12843
- const content2 = update.content ?? [];
12844
- if (content2.length > 0) {
12845
- this.emitRawContent(controller, {
12846
- content: content2,
12847
- toolCallId
12848
- });
12849
- }
12850
- break;
12851
- }
12852
- if (![
12853
- "completed",
12854
- "failed"
12855
- ].includes(status)) {
12856
- break;
12857
- }
12858
- if (!toolInfo) {
12859
- toolInfo = {
12860
- index: this.toolCallsMap.size,
12861
- name: toolName,
12862
- inputAvailable: true
12863
- };
12864
- this.toolCallsMap.set(toolCallId, toolInfo);
12865
- controller.enqueue({
12866
- type: "tool-call",
12867
- toolCallId,
12868
- toolName: ACP_PROVIDER_AGENT_DYNAMIC_TOOL_NAME2,
12869
- input: JSON.stringify({
12870
- toolCallId,
12871
- toolName
12872
- })
12873
- });
12874
- } else if (!toolInfo.inputAvailable) {
12875
- toolInfo.inputAvailable = true;
12876
- if (update.title && toolInfo.name !== update.title && update.title !== toolCallId) {
12877
- toolInfo.name = update.title;
12878
- }
12879
- controller.enqueue({
12880
- type: "tool-call",
12881
- toolCallId,
12882
- toolName: ACP_PROVIDER_AGENT_DYNAMIC_TOOL_NAME2,
12883
- input: JSON.stringify({
12884
- toolCallId,
12885
- toolName: toolInfo.name,
12886
- args: {}
12887
- })
12888
- });
12889
- }
12890
- controller.enqueue({
12891
- type: "tool-result",
12892
- toolCallId,
12893
- toolName: ACP_PROVIDER_AGENT_DYNAMIC_TOOL_NAME2,
12894
- result: toolResult,
12895
- providerExecuted: true,
12896
- // https://github.com/vercel/ai/blob/282f062922cb59167dd3a11e3af67cfa0b75f317/packages/ai/src/generate-text/run-tools-transformation.ts#L316
12897
- ...isError2 && {
12898
- isError: true,
12899
- result: new Error(formatToolError(toolResult))
12900
- }
12901
- });
12902
- const content = update.content ?? [];
12903
- if (content.length > 0) {
12904
- this.emitRawContent(controller, {
12905
- content,
12906
- toolCallId
12907
- });
12908
- }
12909
- break;
12910
- }
12911
- }
12912
- }
12913
- /**
12914
- * Implements the non-streaming generation method.
12915
- */
12916
- async doGenerate(options) {
12917
- try {
12918
- await this.ensureConnected();
12919
- const promptContent = convertAiSdkMessagesToAcp(options, this.isFreshSession);
12920
- this.isFreshSession = false;
12921
- let accumulatedText = "";
12922
- const toolCalls = [];
12923
- const toolResults = /* @__PURE__ */ new Map();
12924
- const mockController = {
12925
- enqueue: (part) => {
12926
- switch (part.type) {
12927
- case "text-delta":
12928
- accumulatedText += part.delta;
12929
- break;
12930
- case "tool-call": {
12931
- const inputData = JSON.parse(part.input);
12932
- toolCalls.push({
12933
- id: part.toolCallId,
12934
- name: inputData.toolName,
12935
- input: inputData.args
12936
- });
12937
- break;
12938
- }
12939
- case "tool-result": {
12940
- const matchingToolCall = toolCalls.find((tc) => tc.id === part.toolCallId);
12941
- toolResults.set(part.toolCallId, {
12942
- name: matchingToolCall?.name || part.toolCallId,
12943
- result: part.result,
12944
- isError: part.isError
12945
- });
12946
- break;
12947
- }
12948
- // Other stream parts (reasoning, start/end blocks, etc.)
12949
- // are ignored in non-streaming mode
12950
- default:
12951
- break;
12952
- }
12953
- }
12954
- };
12955
- const streamHandler = this.handleStreamNotification.bind(this);
12956
- this.resetStreamState();
12957
- if (this.client) {
12958
- this.client.setSessionUpdateHandler((notification) => {
12959
- streamHandler(mockController, notification);
12960
- });
12961
- }
12962
- const response = await this.connection.prompt({
12963
- sessionId: this.sessionId,
12964
- prompt: promptContent
12965
- });
12966
- const content = [];
12967
- if (accumulatedText.trim()) {
12968
- content.push({
12969
- type: "text",
12970
- text: accumulatedText
12971
- });
12972
- }
12973
- for (const toolCall of toolCalls) {
12974
- content.push({
12975
- type: "tool-call",
12976
- toolCallId: toolCall.id,
12977
- toolName: toolCall.name,
12978
- args: JSON.stringify(toolCall.input),
12979
- input: toolCall.input,
12980
- output: toolResults.get(toolCall.id)?.result
12981
- });
12982
- }
12983
- const result = {
12984
- content,
12985
- finishReason: response.stopReason === "end_turn" ? "stop" : "other",
12986
- usage: {
12987
- inputTokens: 0,
12988
- outputTokens: 0,
12989
- totalTokens: 0
12990
- },
12991
- warnings: []
12992
- };
12993
- this.cleanup();
12994
- return result;
12995
- } catch (error) {
12996
- this.cleanup();
12997
- throw error;
12998
- }
12999
- }
13000
- /**
13001
- * Implements the streaming generation method.
13002
- */
13003
- async doStream(options) {
13004
- const acpTools2 = extractACPTools(options.tools);
13005
- await this.ensureConnected(acpTools2.length > 0 ? acpTools2 : void 0);
13006
- const promptContent = convertAiSdkMessagesToAcp(options, this.isFreshSession);
13007
- this.isFreshSession = false;
13008
- const connection = this.connection;
13009
- const sessionId = this.sessionId;
13010
- const client = this.client;
13011
- const cleanup = () => this.cleanup();
13012
- const streamHandler = this.handleStreamNotification.bind(this);
13013
- const stream = new ReadableStream({
13014
- start: async (controller) => {
13015
- controller.enqueue({
13016
- type: "stream-start",
13017
- warnings: []
13018
- });
13019
- this.resetStreamState();
13020
- try {
13021
- if (client) {
13022
- client.setSessionUpdateHandler((notification) => {
13023
- streamHandler(controller, notification);
13024
- });
13025
- }
13026
- const response = await connection.prompt({
13027
- sessionId,
13028
- prompt: promptContent
13029
- });
13030
- controller.enqueue({
13031
- type: "finish",
13032
- finishReason: response.stopReason === "end_turn" ? "stop" : "other",
13033
- usage: {
13034
- inputTokens: 0,
13035
- outputTokens: 0,
13036
- totalTokens: 0
13037
- }
13038
- });
13039
- controller.close();
13040
- cleanup();
13041
- } catch (error) {
13042
- cleanup();
13043
- controller.enqueue({
13044
- type: "error",
13045
- error
13046
- });
13047
- }
13048
- },
13049
- cancel: () => {
13050
- cleanup();
13051
- }
13052
- });
13053
- return {
13054
- stream,
13055
- warnings: []
13056
- };
13057
- }
13058
- get tools() {
13059
- return getACPDynamicTool();
13060
- }
13061
- };
13062
-
13063
- // __mcpc__cli_latest/node_modules/@jsr/mcpc__acp-ai-provider/src/provider.js
13064
- var ACPProvider = class {
13065
- config;
13066
- model = null;
13067
- constructor(config) {
13068
- this.config = config;
13069
- }
13070
- /**
13071
- * Create a language model instance for a specific ACP agent
13072
- *
13073
- * @returns A LanguageModelV2 instance
13074
- */
13075
- languageModel(modelId, modeId) {
13076
- if (!this.model) {
13077
- this.model = new ACPLanguageModel(modelId, modeId, this.config);
13078
- }
13079
- if (modelId) {
13080
- this.model.modelId = modelId;
13081
- }
13082
- if (modeId) {
13083
- this.model.modeId = modeId;
13084
- }
13085
- return this.model;
13086
- }
13087
- /**
13088
- * Shorthand for creating a language model
13089
- */
13090
- call() {
13091
- return this.languageModel();
13092
- }
13093
- /**
13094
- * Provider tools - includes the agent dynamic tool
13095
- */
13096
- get tools() {
13097
- return this.model?.tools;
13098
- }
13099
- /**
13100
- * Returns the current session ID if one is active.
13101
- * Useful when `persistSession` is enabled and you need to reference the session later.
13102
- */
13103
- getSessionId() {
13104
- return this.model?.getSessionId() ?? null;
13105
- }
13106
- /**
13107
- * Initializes the session and returns session info (models, modes, meta).
13108
- * Call this before prompting to discover available options.
13109
- */
13110
- initSession(tools) {
13111
- if (!this.model) {
13112
- this.languageModel();
13113
- }
13114
- return this.model.initSession(tools);
13115
- }
13116
- /**
13117
- * Initializes the connection to the agent process without starting a session.
13118
- * Useful if you need to reduce the time to the first token.
13119
- */
13120
- connect() {
13121
- if (!this.model) {
13122
- this.languageModel();
13123
- }
13124
- return this.model.connectClient();
13125
- }
13126
- /**
13127
- * Sets the session mode (e.g., "ask", "plan").
13128
- */
13129
- setMode(modeId) {
13130
- if (!this.model) {
13131
- throw new Error("No model initialized. Call languageModel() first.");
13132
- }
13133
- return this.model.setMode(modeId);
13134
- }
13135
- /**
13136
- * Sets the session model.
13137
- */
13138
- setModel(modelId) {
13139
- if (!this.model) {
13140
- throw new Error("No model initialized. Call languageModel() first.");
13141
- }
13142
- return this.model.setModel(modelId);
13143
- }
13144
- /**
13145
- * Forces cleanup of the connection and session.
13146
- * Call this when you're done with the provider instance, especially when using `persistSession`.
13147
- */
13148
- cleanup() {
13149
- this.model?.forceCleanup();
13150
- }
13151
- };
13152
- function createACPProvider(config) {
13153
- return new ACPProvider(config);
13154
- }
13155
-
13156
10784
  // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/ai/ai-acp-executor.js
10785
+ var import_acp_ai_provider = require("@mcpc-tech/acp-ai-provider");
13157
10786
  var AIACPExecutor = class extends BaseAIExecutor {
13158
10787
  acpSettings;
13159
10788
  clientTools;
@@ -13166,7 +10795,7 @@ var AIACPExecutor = class extends BaseAIExecutor {
13166
10795
  }
13167
10796
  initProvider() {
13168
10797
  if (!this.model) {
13169
- this.provider = createACPProvider(this.acpSettings);
10798
+ this.provider = (0, import_acp_ai_provider.createACPProvider)(this.acpSettings);
13170
10799
  this.model = this.provider.languageModel();
13171
10800
  }
13172
10801
  return this.model;
@@ -13567,13 +11196,13 @@ var PluginManager = class {
13567
11196
  /**
13568
11197
  * Apply transformTool hooks to a tool during composition
13569
11198
  */
13570
- async applyTransformToolHooks(tool3, context2) {
11199
+ async applyTransformToolHooks(tool2, context2) {
13571
11200
  const transformPlugins = this.plugins.filter((p2) => p2.transformTool && shouldApplyPlugin(p2, context2.mode));
13572
11201
  if (transformPlugins.length === 0) {
13573
- return tool3;
11202
+ return tool2;
13574
11203
  }
13575
11204
  const sortedPlugins = sortPluginsByOrder(transformPlugins);
13576
- let currentTool = tool3;
11205
+ let currentTool = tool2;
13577
11206
  for (const plugin of sortedPlugins) {
13578
11207
  if (plugin.transformTool) {
13579
11208
  try {
@@ -13821,12 +11450,12 @@ var ToolManager = class {
13821
11450
  * Get tool schema if it's hidden (for internal access)
13822
11451
  */
13823
11452
  getHiddenToolSchema(name) {
13824
- const tool3 = this.toolRegistry.get(name);
11453
+ const tool2 = this.toolRegistry.get(name);
13825
11454
  const config = this.toolConfigs.get(name);
13826
- if (tool3 && config?.visibility?.hidden && tool3.schema) {
11455
+ if (tool2 && config?.visibility?.hidden && tool2.schema) {
13827
11456
  return {
13828
- description: tool3.description,
13829
- schema: tool3.schema
11457
+ description: tool2.description,
11458
+ schema: tool2.schema
13830
11459
  };
13831
11460
  }
13832
11461
  return void 0;
@@ -13855,18 +11484,18 @@ var ToolManager = class {
13855
11484
  */
13856
11485
  getRegisteredToolsAsComposed() {
13857
11486
  const composedTools = {};
13858
- for (const [name, tool3] of this.toolRegistry.entries()) {
11487
+ for (const [name, tool2] of this.toolRegistry.entries()) {
13859
11488
  if (this.toolConfigs.get(name)?.visibility?.public === true) {
13860
11489
  continue;
13861
11490
  }
13862
11491
  composedTools[name] = {
13863
11492
  name,
13864
- description: tool3.description,
13865
- inputSchema: jsonSchema(tool3.schema || {
11493
+ description: tool2.description,
11494
+ inputSchema: jsonSchema(tool2.schema || {
13866
11495
  type: "object",
13867
11496
  properties: {}
13868
11497
  }),
13869
- execute: tool3.callback
11498
+ execute: tool2.callback
13870
11499
  };
13871
11500
  }
13872
11501
  return composedTools;
@@ -13936,18 +11565,18 @@ async function processToolsWithPlugins(server, _externalTools, mode) {
13936
11565
  function buildDependencyGroups(toolNameToDetailList, hiddenToolNames, publicToolNames, server) {
13937
11566
  const depGroups = {};
13938
11567
  const toolManager = server.toolManager;
13939
- toolNameToDetailList.forEach(([toolName, tool3]) => {
11568
+ toolNameToDetailList.forEach(([toolName, tool2]) => {
13940
11569
  const resolvedName = toolManager.resolveToolName(toolName);
13941
11570
  if (hiddenToolNames.includes(resolvedName ?? "") || publicToolNames.includes(resolvedName ?? "")) {
13942
11571
  return;
13943
11572
  }
13944
- if (!tool3) {
11573
+ if (!tool2) {
13945
11574
  const allToolNames = [
13946
11575
  ...toolNameToDetailList.map(([n]) => n)
13947
11576
  ];
13948
11577
  throw new Error(`Action ${toolName} not found, available action list: ${allToolNames.join(", ")}`);
13949
11578
  }
13950
- const baseSchema = tool3.inputSchema.jsonSchema ?? tool3.inputSchema ?? {
11579
+ const baseSchema = tool2.inputSchema.jsonSchema ?? tool2.inputSchema ?? {
13951
11580
  type: "object",
13952
11581
  properties: {},
13953
11582
  required: []
@@ -13958,7 +11587,7 @@ function buildDependencyGroups(toolNameToDetailList, hiddenToolNames, publicTool
13958
11587
  const sanitizedKey = sanitizePropertyKey(toolName);
13959
11588
  depGroups[sanitizedKey] = {
13960
11589
  type: "object",
13961
- description: tool3.description,
11590
+ description: tool2.description,
13962
11591
  properties: updatedProperties,
13963
11592
  required: [
13964
11593
  ...baseRequired
@@ -14234,9 +11863,9 @@ var ComposableMCPServer = class extends Server {
14234
11863
  const requestedToolNames = /* @__PURE__ */ new Set();
14235
11864
  const availableToolNames = /* @__PURE__ */ new Set();
14236
11865
  const allPlaceholderUsages = [];
14237
- tagToResults.tool.forEach((tool3) => {
14238
- if (tool3.attribs.name) {
14239
- const originalName = tool3.attribs.name;
11866
+ tagToResults.tool.forEach((tool2) => {
11867
+ if (tool2.attribs.name) {
11868
+ const originalName = tool2.attribs.name;
14240
11869
  const toolName = sanitizePropertyKey(originalName);
14241
11870
  if (toolName.endsWith(`_${ALL_TOOLS_PLACEHOLDER2}`) || toolName === ALL_TOOLS_PLACEHOLDER2) {
14242
11871
  allPlaceholderUsages.push(originalName);
@@ -14262,24 +11891,24 @@ var ComposableMCPServer = class extends Server {
14262
11891
  }
14263
11892
  return true;
14264
11893
  }
14265
- return tagToResults.tool.find((tool3) => {
14266
- const selectAll = tool3.attribs.name === `${mcpName}.${ALL_TOOLS_PLACEHOLDER2}` || tool3.attribs.name === `${mcpName}`;
11894
+ return tagToResults.tool.find((tool2) => {
11895
+ const selectAll = tool2.attribs.name === `${mcpName}.${ALL_TOOLS_PLACEHOLDER2}` || tool2.attribs.name === `${mcpName}`;
14267
11896
  if (selectAll) {
14268
11897
  return true;
14269
11898
  }
14270
- return tool3.attribs.name === toolNameWithScope || tool3.attribs.name === toolId;
11899
+ return tool2.attribs.name === toolNameWithScope || tool2.attribs.name === toolId;
14271
11900
  });
14272
11901
  });
14273
- Object.entries(tools).forEach(([toolId, tool3]) => {
14274
- this.toolManager.registerTool(toolId, tool3.description || "", tool3.inputSchema, tool3.execute);
11902
+ Object.entries(tools).forEach(([toolId, tool2]) => {
11903
+ this.toolManager.registerTool(toolId, tool2.description || "", tool2.inputSchema, tool2.execute);
14275
11904
  });
14276
11905
  const registeredTools = this.toolManager.getRegisteredToolsAsComposed();
14277
11906
  const allTools = {
14278
11907
  ...tools
14279
11908
  };
14280
- Object.entries(registeredTools).forEach(([toolName, tool3]) => {
11909
+ Object.entries(registeredTools).forEach(([toolName, tool2]) => {
14281
11910
  if (!allTools[toolName]) {
14282
- allTools[toolName] = tool3;
11911
+ allTools[toolName] = tool2;
14283
11912
  }
14284
11913
  availableToolNames.add(toolName);
14285
11914
  });
@@ -14323,11 +11952,11 @@ var ComposableMCPServer = class extends Server {
14323
11952
  const hiddenToolNames = this.getHiddenToolNames();
14324
11953
  const contextToolNames = toolNameToDetailList.map(([name2]) => name2).filter((n) => !hiddenToolNames.includes(n));
14325
11954
  publicToolNames.forEach((toolId) => {
14326
- const tool3 = allTools[toolId];
14327
- if (!tool3) {
11955
+ const tool2 = allTools[toolId];
11956
+ if (!tool2) {
14328
11957
  throw new Error(`Public tool ${toolId} not found in registry, available: ${Object.keys(allTools).join(", ")}`);
14329
11958
  }
14330
- this.tool(toolId, tool3.description || "", jsonSchema(tool3.inputSchema), tool3.execute, {
11959
+ this.tool(toolId, tool2.description || "", jsonSchema(tool2.inputSchema), tool2.execute, {
14331
11960
  internal: false
14332
11961
  });
14333
11962
  });
@@ -14380,12 +12009,12 @@ var ComposableMCPServer = class extends Server {
14380
12009
  };
14381
12010
 
14382
12011
  // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/env.js
14383
- var import_node_process10 = __toESM(require("node:process"), 1);
14384
- var isSCF = () => Boolean(import_node_process10.default.env.SCF_RUNTIME || import_node_process10.default.env.PROD_SCF);
12012
+ var import_node_process9 = __toESM(require("node:process"), 1);
12013
+ var isSCF = () => Boolean(import_node_process9.default.env.SCF_RUNTIME || import_node_process9.default.env.PROD_SCF);
14385
12014
  if (isSCF()) {
14386
12015
  console.log({
14387
12016
  isSCF: isSCF(),
14388
- SCF_RUNTIME: import_node_process10.default.env.SCF_RUNTIME
12017
+ SCF_RUNTIME: import_node_process9.default.env.SCF_RUNTIME
14389
12018
  });
14390
12019
  }
14391
12020
 
@@ -14675,9 +12304,9 @@ function createLargeResultPlugin(options = {}) {
14675
12304
  configuredServers.set(server, true);
14676
12305
  }
14677
12306
  },
14678
- transformTool: (tool3, context2) => {
14679
- const originalExecute = tool3.execute;
14680
- tool3.execute = async (args) => {
12307
+ transformTool: (tool2, context2) => {
12308
+ const originalExecute = tool2.execute;
12309
+ tool2.execute = async (args) => {
14681
12310
  try {
14682
12311
  const result = await originalExecute(args);
14683
12312
  const resultText = JSON.stringify(result);
@@ -14719,7 +12348,7 @@ ${preview}
14719
12348
  throw error;
14720
12349
  }
14721
12350
  };
14722
- return tool3;
12351
+ return tool2;
14723
12352
  },
14724
12353
  dispose: () => {
14725
12354
  configuredServers.clear();