@mcpc-tech/cli 0.1.19 → 0.1.21

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 +4899 -0
  2. package/bin/mcpc.mjs +251 -247
  3. package/package.json +13 -7
package/bin/mcpc.cjs ADDED
@@ -0,0 +1,4899 @@
1
+ #!/usr/bin/env node
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") {
10
+ for (let key of __getOwnPropNames(from))
11
+ if (!__hasOwnProp.call(to, key) && key !== except)
12
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
13
+ }
14
+ return to;
15
+ };
16
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
17
+ // If the importer is in node compatibility mode or this is not an ESM
18
+ // file that has been converted to a CommonJS file using a Babel-
19
+ // compatible transform (i.e. "__esModule" has not been set), then set
20
+ // "default" to the CommonJS "module.exports" for node compatibility.
21
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
+ mod
23
+ ));
24
+
25
+ // __mcpc__cli_latest/node_modules/@mcpc/cli/src/bin.ts
26
+ var import_stdio2 = require("@modelcontextprotocol/sdk/server/stdio.js");
27
+
28
+ // __mcpc__cli_latest/node_modules/@mcpc/cli/src/app.js
29
+ var import_zod_openapi3 = require("@hono/zod-openapi");
30
+
31
+ // __mcpc__cli_latest/node_modules/@mcpc/cli/src/controllers/messages.controller.js
32
+ var import_zod_openapi = require("@hono/zod-openapi");
33
+ var import_zod = require("zod");
34
+
35
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__utils/src/transport/sse.js
36
+ var import_types = require("@modelcontextprotocol/sdk/types.js");
37
+
38
+ // __mcpc__cli_latest/node_modules/@jsr/std__http/server_sent_event_stream.js
39
+ var NEWLINE_REGEXP = /\r\n|\r|\n/;
40
+ var encoder = new TextEncoder();
41
+ function assertHasNoNewline(value, varName, errPrefix) {
42
+ if (value.match(NEWLINE_REGEXP) !== null) {
43
+ throw new SyntaxError(`${errPrefix}: ${varName} cannot contain a newline`);
44
+ }
45
+ }
46
+ function stringify(message) {
47
+ const lines = [];
48
+ if (message.comment) {
49
+ assertHasNoNewline(message.comment, "`message.comment`", "Cannot serialize message");
50
+ lines.push(`:${message.comment}`);
51
+ }
52
+ if (message.event) {
53
+ assertHasNoNewline(message.event, "`message.event`", "Cannot serialize message");
54
+ lines.push(`event:${message.event}`);
55
+ }
56
+ if (message.data) {
57
+ message.data.split(NEWLINE_REGEXP).forEach((line) => lines.push(`data:${line}`));
58
+ }
59
+ if (message.id) {
60
+ assertHasNoNewline(message.id.toString(), "`message.id`", "Cannot serialize message");
61
+ lines.push(`id:${message.id}`);
62
+ }
63
+ if (message.retry) lines.push(`retry:${message.retry}`);
64
+ return encoder.encode(lines.join("\n") + "\n\n");
65
+ }
66
+ var ServerSentEventStream = class extends TransformStream {
67
+ constructor() {
68
+ super({
69
+ transform: (message, controller) => {
70
+ controller.enqueue(stringify(message));
71
+ }
72
+ });
73
+ }
74
+ };
75
+
76
+ // __mcpc__cli_latest/node_modules/@mcpc/cli/src/controllers/sse.controller.js
77
+ var import_zod_openapi2 = require("@hono/zod-openapi");
78
+
79
+ // __mcpc__cli_latest/node_modules/@mcpc/cli/src/controllers/streamable-http.controller.js
80
+ var import_streamableHttp = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
81
+
82
+ // __mcpc__cli_latest/node_modules/@mcpc/cli/src/config/loader.js
83
+ var import_promises = require("node:fs/promises");
84
+ var import_node_os = require("node:os");
85
+ var import_node_path = require("node:path");
86
+ var import_node_process = __toESM(require("node:process"), 1);
87
+ function extractServerName(command, commandArgs) {
88
+ for (const arg of commandArgs) {
89
+ if (!arg.startsWith("-")) {
90
+ const name2 = arg.replace(/[@.,/\\:;!?#$%^&*()[\]{}]/g, "_").substring(0, 64);
91
+ if (name2) return name2;
92
+ }
93
+ }
94
+ const name = command.replace(/[@.,/\\:;!?#$%^&*()[\]{}]/g, "_").substring(0, 64);
95
+ return name || "agentic-tool";
96
+ }
97
+ function getUserConfigDir() {
98
+ return (0, import_node_path.join)((0, import_node_os.homedir)(), ".mcpc");
99
+ }
100
+ function getUserConfigPath() {
101
+ return (0, import_node_path.join)(getUserConfigDir(), "config.json");
102
+ }
103
+ async function saveUserConfig(config, newAgentName) {
104
+ const configPath = getUserConfigPath();
105
+ const configDir = (0, import_node_path.dirname)(configPath);
106
+ try {
107
+ let existingConfig = null;
108
+ try {
109
+ const content = await (0, import_promises.readFile)(configPath, "utf-8");
110
+ existingConfig = JSON.parse(content);
111
+ } catch {
112
+ }
113
+ if (existingConfig) {
114
+ const hasConflict = existingConfig.agents.some((agent) => agent.name === newAgentName);
115
+ if (hasConflict) {
116
+ console.error(`
117
+ \u26A0 Agent "${newAgentName}" already exists in ${configPath}
118
+ Use --name to choose a different name, or delete the existing agent first.
119
+ `);
120
+ return;
121
+ }
122
+ existingConfig.agents.push(...config.agents);
123
+ await (0, import_promises.writeFile)(configPath, JSON.stringify(existingConfig, null, 2), "utf-8");
124
+ console.error(`
125
+ \u2713 Added agent "${newAgentName}" (total: ${existingConfig.agents.length})
126
+ Config: ${configPath}
127
+ Run: mcpc
128
+ `);
129
+ return;
130
+ }
131
+ await (0, import_promises.mkdir)(configDir, {
132
+ recursive: true
133
+ });
134
+ await (0, import_promises.writeFile)(configPath, JSON.stringify(config, null, 2), "utf-8");
135
+ console.error(`
136
+ \u2713 Configuration saved to: ${configPath}
137
+ Run: mcpc
138
+ `);
139
+ } catch (error) {
140
+ console.error(`Failed to save config to ${configPath}:`, error);
141
+ }
142
+ }
143
+ async function createWrapConfig(args) {
144
+ if (!args.mcpServers || args.mcpServers.length === 0) {
145
+ console.error("Error: --wrap/--add requires at least one MCP server\nExample: mcpc --wrap --mcp-stdio 'npx -y @wonderwhy-er/desktop-commander'\nMultiple: mcpc --add --mcp-stdio 'npx -y server1' --mcp-http 'https://api.example.com'");
146
+ import_node_process.default.exit(1);
147
+ }
148
+ const mcpServers = {};
149
+ const serverNames = [];
150
+ const refs = [];
151
+ for (const spec of args.mcpServers) {
152
+ const serverName = extractServerName(spec.command, spec.args);
153
+ mcpServers[serverName] = {
154
+ command: spec.command,
155
+ args: spec.args,
156
+ transportType: spec.transportType
157
+ };
158
+ serverNames.push(serverName);
159
+ refs.push(`<tool name="${serverName}.__ALL__"/>`);
160
+ console.error(`Added MCP server: ${serverName}
161
+ Transport: ${spec.transportType}
162
+ Command: ${spec.command} ${spec.args.join(" ")}`);
163
+ }
164
+ const agentName = args.name || `${serverNames.join("__")}--orchestrator`;
165
+ const config = {
166
+ name: "mcpc-wrap-config",
167
+ version: "0.1.0",
168
+ capabilities: {
169
+ tools: {},
170
+ sampling: {}
171
+ },
172
+ agents: [
173
+ {
174
+ name: agentName,
175
+ description: `Orchestrate ${serverNames.length === 1 ? serverNames[0] : serverNames.join(", ")} MCP server tools`,
176
+ deps: {
177
+ mcpServers
178
+ },
179
+ options: {
180
+ mode: args.mode || "agentic",
181
+ refs
182
+ }
183
+ }
184
+ ]
185
+ };
186
+ const modeInfo = args.mode ? `
187
+ Mode: ${args.mode}` : "";
188
+ console.error(`
189
+ Created configuration for ${serverNames.length} MCP server(s)${modeInfo}`);
190
+ if (args.saveConfig) {
191
+ await saveUserConfig(config, agentName);
192
+ }
193
+ return config;
194
+ }
195
+ function printHelp() {
196
+ console.log(`
197
+ MCPC CLI - Model Context Protocol Composer
198
+
199
+ USAGE:
200
+ mcpc [OPTIONS]
201
+
202
+ OPTIONS:
203
+ --help, -h Show this help message
204
+ --config <json> Inline JSON configuration string
205
+ --config-url <url> Fetch configuration from URL
206
+ --config-file <path> Load configuration from file path
207
+ --request-headers <header>, -H <header>
208
+ Add custom HTTP header for URL fetching
209
+ Format: "Key: Value" or "Key=Value"
210
+ Can be used multiple times
211
+ --mode <mode> Set execution mode for all agents
212
+ Supported modes:
213
+ - agentic: Fully autonomous agent mode (default)
214
+ - agentic_workflow: Agent workflow mode with dynamic or predefined steps
215
+ - agentic_sampling: Autonomous sampling mode for agentic execution
216
+ - agentic_workflow_sampling: Autonomous sampling mode for workflow execution
217
+ - code_execution: Code execution mode for most efficient token usage
218
+ --add Add MCP servers to ~/.mcpc/config.json and exit
219
+ Then run 'mcpc' to start the server with saved config
220
+ Use --mcp-stdio, --mcp-http, or --mcp-sse to specify servers
221
+ --wrap Wrap and run MCP servers immediately without saving config
222
+ Use --mcp-stdio, --mcp-http, or --mcp-sse to specify servers
223
+ --mcp-stdio <cmd> Add an MCP server with stdio transport
224
+ Example: --mcp-stdio "npx -y @wonderwhy-er/desktop-commander"
225
+ --mcp-http <url> Add an MCP server with streamable-http transport
226
+ Example: --mcp-http "https://api.github.com/mcp"
227
+ --mcp-sse <url> Add an MCP server with SSE transport
228
+ Example: --mcp-sse "https://api.example.com/sse"
229
+ --name <name> Custom agent name for wrap mode (overrides auto-detection)
230
+
231
+ ENVIRONMENT VARIABLES:
232
+ MCPC_CONFIG Inline JSON configuration (same as --config)
233
+ MCPC_CONFIG_URL URL to fetch config from (same as --config-url)
234
+ MCPC_CONFIG_FILE Path to config file (same as --config-file)
235
+
236
+ EXAMPLES:
237
+ # Show help
238
+ mcpc --help
239
+
240
+ # Add MCP servers to config and save to ~/.mcpc/config.json
241
+ mcpc --add --mcp-stdio "npx -y @wonderwhy-er/desktop-commander"
242
+ # Edit ~/.mcpc/config.json if needed (add headers, etc.)
243
+ mcpc # Loads config from ~/.mcpc/config.json automatically
244
+
245
+ # Wrap and run immediately (one-time use, no config saved)
246
+ mcpc --wrap --mcp-stdio "npx -y @wonderwhy-er/desktop-commander"
247
+
248
+ # Multiple servers with different transports
249
+ mcpc --add --mcp-stdio "npx -y @wonderwhy-er/desktop-commander" --mcp-http "https://api.github.com/mcp" --mcp-sse "https://api.example.com/sse"
250
+
251
+ # Custom agent name
252
+ mcpc --add --name my-agent --mcp-stdio "npx shadcn@latest mcp"
253
+ mcpc --wrap --name my-agent --mcp-stdio "npx shadcn@latest mcp"
254
+
255
+ # Load from URL
256
+ mcpc --config-url \\
257
+ "https://raw.githubusercontent.com/mcpc-tech/mcpc/main/packages/cli/examples/configs/codex-fork.json"
258
+
259
+ # Load from URL with custom headers
260
+ mcpc \\
261
+ --config-url "https://api.example.com/config.json" \\
262
+ -H "Authorization: Bearer token123" \\
263
+ -H "X-Custom-Header: value"
264
+
265
+ # Load from file
266
+ mcpc --config-file ./my-config.json
267
+
268
+ # Override execution mode for all agents
269
+ mcpc --config-file ./my-config.json --mode agentic_workflow
270
+
271
+ # Using environment variable
272
+ export MCPC_CONFIG='[{"name":"agent","description":"..."}]'
273
+ mcpc
274
+
275
+ # Use default configuration (./mcpc.config.json)
276
+ mcpc
277
+
278
+ CONFIGURATION:
279
+ Configuration files support environment variable substitution using $VAR_NAME syntax.
280
+
281
+ Priority order:
282
+ 1. --config (inline JSON)
283
+ 2. MCPC_CONFIG environment variable
284
+ 3. --config-url or MCPC_CONFIG_URL
285
+ 4. --config-file or MCPC_CONFIG_FILE
286
+ 5. ./mcpc.config.json (default)
287
+
288
+ For more information, visit: https://github.com/mcpc-tech/mcpc
289
+ `);
290
+ }
291
+ function parseArgs() {
292
+ const args = import_node_process.default.argv.slice(2);
293
+ const result = {};
294
+ for (let i = 0; i < args.length; i++) {
295
+ const arg = args[i];
296
+ if (arg === "--config" && i + 1 < args.length) {
297
+ result.config = args[++i];
298
+ } else if (arg === "--config-url" && i + 1 < args.length) {
299
+ result.configUrl = args[++i];
300
+ } else if (arg === "--config-file" && i + 1 < args.length) {
301
+ result.configFile = args[++i];
302
+ } else if ((arg === "--request-headers" || arg === "-H") && i + 1 < args.length) {
303
+ const headerStr = args[++i];
304
+ const colonIdx = headerStr.indexOf(":");
305
+ const equalIdx = headerStr.indexOf("=");
306
+ const separatorIdx = colonIdx !== -1 ? equalIdx !== -1 ? Math.min(colonIdx, equalIdx) : colonIdx : equalIdx;
307
+ if (separatorIdx !== -1) {
308
+ const key = headerStr.substring(0, separatorIdx).trim();
309
+ const value = headerStr.substring(separatorIdx + 1).trim();
310
+ if (!result.requestHeaders) {
311
+ result.requestHeaders = {};
312
+ }
313
+ result.requestHeaders[key] = value;
314
+ }
315
+ } else if (arg === "--help" || arg === "-h") {
316
+ result.help = true;
317
+ } else if (arg === "--add") {
318
+ result.add = true;
319
+ } else if (arg === "--wrap") {
320
+ result.wrap = true;
321
+ } else if ((arg === "--mcp-stdio" || arg === "--mcp-http" || arg === "--mcp-sse") && i + 1 < args.length) {
322
+ const cmdString = args[++i];
323
+ const cmdParts = cmdString.split(/\s+/);
324
+ const command = cmdParts[0];
325
+ const cmdArgs = cmdParts.slice(1);
326
+ let transportType;
327
+ if (arg === "--mcp-stdio") {
328
+ transportType = "stdio";
329
+ } else if (arg === "--mcp-http") {
330
+ transportType = "streamable-http";
331
+ } else {
332
+ transportType = "sse";
333
+ }
334
+ if (!result.mcpServers) {
335
+ result.mcpServers = [];
336
+ }
337
+ result.mcpServers.push({
338
+ command,
339
+ args: cmdArgs,
340
+ transportType
341
+ });
342
+ } else if (arg === "--mode" && i + 1 < args.length) {
343
+ result.mode = args[++i];
344
+ } else if (arg === "--name" && i + 1 < args.length) {
345
+ result.name = args[++i];
346
+ }
347
+ }
348
+ return result;
349
+ }
350
+ async function loadConfig() {
351
+ const args = parseArgs();
352
+ if (args.help) {
353
+ printHelp();
354
+ import_node_process.default.exit(0);
355
+ }
356
+ if (args.add) {
357
+ await createWrapConfig({
358
+ ...args,
359
+ saveConfig: true
360
+ });
361
+ import_node_process.default.exit(0);
362
+ }
363
+ if (args.wrap) {
364
+ return await createWrapConfig({
365
+ ...args,
366
+ saveConfig: false
367
+ });
368
+ }
369
+ if (args.config) {
370
+ try {
371
+ const parsed = JSON.parse(args.config);
372
+ return applyModeOverride(normalizeConfig(parsed), args.mode);
373
+ } catch (error) {
374
+ console.error("Failed to parse --config argument:", error);
375
+ throw error;
376
+ }
377
+ }
378
+ if (import_node_process.default.env.MCPC_CONFIG) {
379
+ try {
380
+ const parsed = JSON.parse(import_node_process.default.env.MCPC_CONFIG);
381
+ return applyModeOverride(normalizeConfig(parsed), args.mode);
382
+ } catch (error) {
383
+ console.error("Failed to parse MCPC_CONFIG environment variable:", error);
384
+ throw error;
385
+ }
386
+ }
387
+ const configUrl = args.configUrl || import_node_process.default.env.MCPC_CONFIG_URL;
388
+ if (configUrl) {
389
+ try {
390
+ const headers = {
391
+ "User-Agent": "MCPC-CLI/0.1.0",
392
+ ...args.requestHeaders
393
+ };
394
+ const response = await fetch(configUrl, {
395
+ headers
396
+ });
397
+ if (!response.ok) {
398
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
399
+ }
400
+ const content = await response.text();
401
+ const parsed = JSON.parse(content);
402
+ return applyModeOverride(normalizeConfig(parsed), args.mode);
403
+ } catch (error) {
404
+ console.error(`Failed to fetch config from ${configUrl}:`, error);
405
+ throw error;
406
+ }
407
+ }
408
+ const configFile = args.configFile || import_node_process.default.env.MCPC_CONFIG_FILE;
409
+ if (configFile) {
410
+ try {
411
+ const content = await (0, import_promises.readFile)(configFile, "utf-8");
412
+ const parsed = JSON.parse(content);
413
+ return applyModeOverride(normalizeConfig(parsed), args.mode);
414
+ } catch (error) {
415
+ if (error.code === "ENOENT") {
416
+ console.error(`Config file not found: ${configFile}`);
417
+ throw error;
418
+ } else {
419
+ console.error(`Failed to load config from ${configFile}:`, error);
420
+ throw error;
421
+ }
422
+ }
423
+ }
424
+ const userConfigPath = getUserConfigPath();
425
+ try {
426
+ const content = await (0, import_promises.readFile)(userConfigPath, "utf-8");
427
+ const parsed = JSON.parse(content);
428
+ return applyModeOverride(normalizeConfig(parsed), args.mode);
429
+ } catch (error) {
430
+ if (error.code !== "ENOENT") {
431
+ console.error(`Failed to load config from ${userConfigPath}:`, error);
432
+ throw error;
433
+ }
434
+ }
435
+ const defaultConfigPath = (0, import_node_path.resolve)(import_node_process.default.cwd(), "mcpc.config.json");
436
+ try {
437
+ const content = await (0, import_promises.readFile)(defaultConfigPath, "utf-8");
438
+ const parsed = JSON.parse(content);
439
+ return applyModeOverride(normalizeConfig(parsed), args.mode);
440
+ } catch (error) {
441
+ if (error.code === "ENOENT") {
442
+ return null;
443
+ } else {
444
+ console.error(`Failed to load config from ${defaultConfigPath}:`, error);
445
+ throw error;
446
+ }
447
+ }
448
+ }
449
+ function replaceEnvVars(str) {
450
+ return str.replace(/\$([A-Z_][A-Z0-9_]*)/g, (_match, varName) => {
451
+ return import_node_process.default.env[varName] || "";
452
+ });
453
+ }
454
+ function replaceEnvVarsInConfig(obj) {
455
+ if (typeof obj === "string") {
456
+ return replaceEnvVars(obj);
457
+ }
458
+ if (Array.isArray(obj)) {
459
+ return obj.map((item) => replaceEnvVarsInConfig(item));
460
+ }
461
+ if (obj && typeof obj === "object") {
462
+ const result = {};
463
+ for (const [key, value] of Object.entries(obj)) {
464
+ result[key] = replaceEnvVarsInConfig(value);
465
+ }
466
+ return result;
467
+ }
468
+ return obj;
469
+ }
470
+ function applyModeOverride(config, mode) {
471
+ if (!mode) return config;
472
+ config.agents.forEach((agent) => {
473
+ if (!agent.options) agent.options = {};
474
+ agent.options.mode = mode;
475
+ });
476
+ return config;
477
+ }
478
+ function normalizeConfig(config) {
479
+ config = replaceEnvVarsInConfig(config);
480
+ if (Array.isArray(config)) {
481
+ return {
482
+ name: "mcpc-server",
483
+ version: "0.1.0",
484
+ agents: normalizeAgents(config)
485
+ };
486
+ }
487
+ if (config && typeof config === "object") {
488
+ const cfg = config;
489
+ return {
490
+ name: cfg.name || "mcpc-server",
491
+ version: cfg.version || "0.1.0",
492
+ capabilities: cfg.capabilities,
493
+ agents: normalizeAgents(cfg.agents || [])
494
+ };
495
+ }
496
+ throw new Error("Invalid configuration format");
497
+ }
498
+ function normalizeAgents(agents) {
499
+ return agents.map((agent) => {
500
+ if (agent.deps && !agent.deps.mcpServers) {
501
+ agent.deps.mcpServers = {};
502
+ }
503
+ return agent;
504
+ });
505
+ }
506
+
507
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/compose.js
508
+ var import_types2 = require("@modelcontextprotocol/sdk/types.js");
509
+
510
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/schema.js
511
+ var schemaSymbol = Symbol.for("mcpc.schema");
512
+ var vercelSchemaSymbol = Symbol.for("vercel.ai.schema");
513
+ var validatorSymbol = Symbol.for("mcpc.validator");
514
+ function jsonSchema(schema, options = {}) {
515
+ if (isWrappedSchema(schema)) {
516
+ return schema;
517
+ }
518
+ return {
519
+ [schemaSymbol]: true,
520
+ [validatorSymbol]: true,
521
+ _type: void 0,
522
+ jsonSchema: schema,
523
+ validate: options.validate
524
+ };
525
+ }
526
+ function isWrappedSchema(value) {
527
+ return typeof value === "object" && value !== null && (schemaSymbol in value && value[schemaSymbol] === true || vercelSchemaSymbol in value && value[vercelSchemaSymbol] === true);
528
+ }
529
+ function extractJsonSchema(schema) {
530
+ if (isWrappedSchema(schema)) {
531
+ return schema.jsonSchema;
532
+ }
533
+ return schema;
534
+ }
535
+
536
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/compose.js
537
+ var import_server = require("@modelcontextprotocol/sdk/server/index.js");
538
+
539
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__utils/src/json.js
540
+ var import_jsonrepair = require("jsonrepair");
541
+ function stripMarkdownAndText(text) {
542
+ text = text.trim();
543
+ text = text.replace(/^```(?:json)?\s*\n?/i, "");
544
+ text = text.replace(/\n?```\s*$/, "");
545
+ text = text.replace(/^(?:here is|here's|response|result|output|json):\s*/i, "");
546
+ const firstJsonIndex = text.search(/[\{\[]/);
547
+ if (firstJsonIndex >= 0) {
548
+ text = text.slice(firstJsonIndex);
549
+ let depth = 0;
550
+ let inString = false;
551
+ let escapeNext = false;
552
+ const startChar = text[0];
553
+ const endChar = startChar === "{" ? "}" : "]";
554
+ for (let i = 0; i < text.length; i++) {
555
+ const char = text[i];
556
+ if (escapeNext) {
557
+ escapeNext = false;
558
+ continue;
559
+ }
560
+ if (char === "\\") {
561
+ escapeNext = true;
562
+ continue;
563
+ }
564
+ if (char === '"' && !inString) {
565
+ inString = true;
566
+ continue;
567
+ }
568
+ if (char === '"' && inString) {
569
+ inString = false;
570
+ continue;
571
+ }
572
+ if (inString) continue;
573
+ if (char === startChar) {
574
+ depth++;
575
+ } else if (char === endChar) {
576
+ depth--;
577
+ if (depth === 0) {
578
+ return text.slice(0, i + 1);
579
+ }
580
+ }
581
+ }
582
+ }
583
+ return text.trim();
584
+ }
585
+ function parseJSON(text, throwError) {
586
+ try {
587
+ return JSON.parse(text);
588
+ } catch (_error) {
589
+ try {
590
+ const cleanedText = stripMarkdownAndText(text);
591
+ try {
592
+ return JSON.parse(cleanedText);
593
+ } catch {
594
+ const repairedText = (0, import_jsonrepair.jsonrepair)(cleanedText);
595
+ console.warn(`Failed to parse JSON, cleaned and repaired. Original: ${text.slice(0, 100)}...`);
596
+ return JSON.parse(repairedText);
597
+ }
598
+ } catch (_repairError) {
599
+ if (throwError) {
600
+ throw new Error(`Failed to parse JSON after cleanup and repair. Original error: ${_error instanceof Error ? _error.message : String(_error)}`);
601
+ }
602
+ return null;
603
+ }
604
+ }
605
+ }
606
+
607
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__utils/src/ai.js
608
+ var p = (template, options = {}) => {
609
+ const { missingVariableHandling = "warn" } = options;
610
+ const names = /* @__PURE__ */ new Set();
611
+ const regex = /\{((\w|\.)+)\}/g;
612
+ let match;
613
+ while ((match = regex.exec(template)) !== null) {
614
+ names.add(match[1]);
615
+ }
616
+ const required = Array.from(names);
617
+ return (input) => {
618
+ let result = template;
619
+ for (const name of required) {
620
+ const key = name;
621
+ const value = input[key];
622
+ const re = new RegExp(`\\{${String(name)}\\}`, "g");
623
+ if (value !== void 0 && value !== null) {
624
+ result = result.replace(re, String(value));
625
+ } else {
626
+ switch (missingVariableHandling) {
627
+ case "error":
628
+ throw new Error(`Missing variable "${String(name)}" in input for template.`);
629
+ case "empty":
630
+ result = result.replace(re, "");
631
+ break;
632
+ case "warn":
633
+ case "ignore":
634
+ default:
635
+ break;
636
+ }
637
+ }
638
+ }
639
+ return result;
640
+ };
641
+ };
642
+
643
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__utils/src/tool-tags.js
644
+ var import_cheerio = require("cheerio");
645
+ function parseTags(htmlString, tags) {
646
+ const $ = (0, import_cheerio.load)(htmlString, {
647
+ xml: {
648
+ decodeEntities: false
649
+ }
650
+ });
651
+ const tagToResults = {};
652
+ for (const tag of tags) {
653
+ const elements = $(tag);
654
+ tagToResults[tag] = elements.toArray();
655
+ }
656
+ return {
657
+ tagToResults,
658
+ $
659
+ };
660
+ }
661
+
662
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/mcp.js
663
+ var import_client = require("@modelcontextprotocol/sdk/client/index.js");
664
+ var import_stdio = require("@modelcontextprotocol/sdk/client/stdio.js");
665
+ var import_sse3 = require("@modelcontextprotocol/sdk/client/sse.js");
666
+ var import_streamableHttp2 = require("@modelcontextprotocol/sdk/client/streamableHttp.js");
667
+ var import_inMemory = require("@modelcontextprotocol/sdk/inMemory.js");
668
+
669
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/config.js
670
+ var import_node_process2 = __toESM(require("node:process"), 1);
671
+ var GEMINI_PREFERRED_FORMAT = import_node_process2.default.env.GEMINI_PREFERRED_FORMAT === "0" ? false : true;
672
+
673
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/json.js
674
+ var import_jsonrepair2 = require("jsonrepair");
675
+
676
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/provider.js
677
+ function sanitizePropertyKey(name) {
678
+ return name.replace(/[@.,/\\:;!?#$%^&*()[\]{}]/g, "_").substring(0, 64);
679
+ }
680
+ var createModelCompatibleJSONSchema = (schema) => {
681
+ const validatorOnlyKeys = [
682
+ "errorMessage"
683
+ ];
684
+ const geminiRestrictedKeys = GEMINI_PREFERRED_FORMAT ? [
685
+ "additionalProperties"
686
+ ] : [];
687
+ const keysToRemove = /* @__PURE__ */ new Set([
688
+ ...validatorOnlyKeys,
689
+ ...geminiRestrictedKeys
690
+ ]);
691
+ let cleanSchema = schema;
692
+ if (GEMINI_PREFERRED_FORMAT) {
693
+ const { oneOf: _oneOf, allOf: _allOf, anyOf: _anyOf, ...rest2 } = schema;
694
+ cleanSchema = rest2;
695
+ }
696
+ const cleanRecursively = (obj) => {
697
+ if (Array.isArray(obj)) {
698
+ return obj.map(cleanRecursively);
699
+ }
700
+ if (obj && typeof obj === "object") {
701
+ const result = {};
702
+ for (const [key, value] of Object.entries(obj)) {
703
+ if (!keysToRemove.has(key)) {
704
+ result[key] = cleanRecursively(value);
705
+ }
706
+ }
707
+ return result;
708
+ }
709
+ return obj;
710
+ };
711
+ return cleanRecursively(cleanSchema);
712
+ };
713
+
714
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/mcp.js
715
+ var import_node_process3 = require("node:process");
716
+ var import_node_process4 = __toESM(require("node:process"), 1);
717
+ var import_node_crypto = require("node:crypto");
718
+ var mcpClientPool = /* @__PURE__ */ new Map();
719
+ var mcpClientConnecting = /* @__PURE__ */ new Map();
720
+ var shortHash = (s) => (0, import_node_crypto.createHash)("sha256").update(s).digest("hex").slice(0, 8);
721
+ function defSignature(def) {
722
+ const defCopy = {
723
+ ...def
724
+ };
725
+ if (defCopy.transportType === "memory" || defCopy.transport) {
726
+ return `memory:${Date.now()}:${Math.random()}`;
727
+ }
728
+ return JSON.stringify(defCopy);
729
+ }
730
+ function createTransport(def) {
731
+ const defAny = def;
732
+ const explicitType = defAny.transportType || defAny.type;
733
+ if (explicitType === "memory") {
734
+ if (!defAny.server) {
735
+ throw new Error("In-memory transport requires a 'server' field with a Server instance");
736
+ }
737
+ const [clientTransport, serverTransport] = import_inMemory.InMemoryTransport.createLinkedPair();
738
+ defAny.server.connect(serverTransport).catch((err) => {
739
+ console.error("Error connecting in-memory server:", err);
740
+ });
741
+ return clientTransport;
742
+ }
743
+ if (explicitType === "sse") {
744
+ const options = {};
745
+ if (defAny.headers) {
746
+ options.requestInit = {
747
+ headers: defAny.headers
748
+ };
749
+ options.eventSourceInit = {
750
+ headers: defAny.headers
751
+ };
752
+ }
753
+ return new import_sse3.SSEClientTransport(new URL(defAny.url), options);
754
+ }
755
+ if (defAny.url && typeof defAny.url === "string") {
756
+ const options = {};
757
+ if (defAny.headers) {
758
+ options.requestInit = {
759
+ headers: defAny.headers
760
+ };
761
+ }
762
+ return new import_streamableHttp2.StreamableHTTPClientTransport(new URL(defAny.url), options);
763
+ }
764
+ if (explicitType === "stdio" || defAny.command) {
765
+ return new import_stdio.StdioClientTransport({
766
+ command: defAny.command,
767
+ args: defAny.args,
768
+ env: {
769
+ ...import_node_process4.default.env,
770
+ ...defAny.env ?? {}
771
+ },
772
+ cwd: (0, import_node_process3.cwd)()
773
+ });
774
+ }
775
+ throw new Error(`Unsupported transport configuration: ${JSON.stringify(def)}`);
776
+ }
777
+ async function getOrCreateMcpClient(defKey, def) {
778
+ const pooled = mcpClientPool.get(defKey);
779
+ if (pooled) {
780
+ pooled.refCount += 1;
781
+ return pooled.client;
782
+ }
783
+ const existingConnecting = mcpClientConnecting.get(defKey);
784
+ if (existingConnecting) {
785
+ const client = await existingConnecting;
786
+ const entry = mcpClientPool.get(defKey);
787
+ if (entry) entry.refCount += 1;
788
+ return client;
789
+ }
790
+ const transport = createTransport(def);
791
+ const connecting = (async () => {
792
+ const client = new import_client.Client({
793
+ name: `mcp_${shortHash(defSignature(def))}`,
794
+ version: "1.0.0"
795
+ });
796
+ await client.connect(transport, {
797
+ timeout: 6e4 * 10
798
+ });
799
+ return client;
800
+ })();
801
+ mcpClientConnecting.set(defKey, connecting);
802
+ try {
803
+ const client = await connecting;
804
+ mcpClientPool.set(defKey, {
805
+ client,
806
+ refCount: 1
807
+ });
808
+ return client;
809
+ } finally {
810
+ mcpClientConnecting.delete(defKey);
811
+ }
812
+ }
813
+ async function releaseMcpClient(defKey) {
814
+ const entry = mcpClientPool.get(defKey);
815
+ if (!entry) return;
816
+ entry.refCount -= 1;
817
+ if (entry.refCount <= 0) {
818
+ mcpClientPool.delete(defKey);
819
+ try {
820
+ await entry.client.close();
821
+ } catch (err) {
822
+ console.error("Error closing MCP client:", err);
823
+ }
824
+ }
825
+ }
826
+ var cleanupAllPooledClients = async () => {
827
+ const entries = Array.from(mcpClientPool.entries());
828
+ mcpClientPool.clear();
829
+ await Promise.all(entries.map(async ([, { client }]) => {
830
+ try {
831
+ await client.close();
832
+ } catch (err) {
833
+ console.error("Error closing MCP client:", err);
834
+ }
835
+ }));
836
+ };
837
+ import_node_process4.default.once?.("exit", () => {
838
+ cleanupAllPooledClients();
839
+ });
840
+ import_node_process4.default.once?.("SIGINT", () => {
841
+ cleanupAllPooledClients().finally(() => import_node_process4.default.exit(0));
842
+ });
843
+ async function composeMcpDepTools(mcpConfig, filterIn) {
844
+ const allTools = {};
845
+ const allClients = {};
846
+ const acquiredKeys = [];
847
+ for (const [name, definition] of Object.entries(mcpConfig.mcpServers)) {
848
+ const def = definition;
849
+ if (def.disabled) continue;
850
+ const defKey = shortHash(defSignature(def));
851
+ const serverId = name;
852
+ try {
853
+ const client = await getOrCreateMcpClient(defKey, def);
854
+ acquiredKeys.push(defKey);
855
+ allClients[serverId] = client;
856
+ const { tools } = await client.listTools();
857
+ tools.forEach((tool) => {
858
+ const toolNameWithScope = `${name}.${tool.name}`;
859
+ const internalToolName = tool.name;
860
+ const rawToolId = `${serverId}_${internalToolName}`;
861
+ const toolId = sanitizePropertyKey(rawToolId);
862
+ if (filterIn && !filterIn({
863
+ action: internalToolName,
864
+ tool,
865
+ mcpName: name,
866
+ toolNameWithScope,
867
+ internalToolName,
868
+ toolId
869
+ })) {
870
+ return;
871
+ }
872
+ const execute = (args) => allClients[serverId].callTool({
873
+ name: internalToolName,
874
+ arguments: args
875
+ }, void 0, {
876
+ timeout: def.toolCallTimeout
877
+ });
878
+ allTools[toolId] = {
879
+ ...tool,
880
+ execute,
881
+ _originalName: toolNameWithScope
882
+ };
883
+ });
884
+ } catch (error) {
885
+ console.error(`Error creating MCP client for ${name}:`, error);
886
+ }
887
+ }
888
+ const cleanupClients = async () => {
889
+ await Promise.all(acquiredKeys.map((k) => releaseMcpClient(k)));
890
+ acquiredKeys.length = 0;
891
+ Object.keys(allTools).forEach((key) => delete allTools[key]);
892
+ Object.keys(allClients).forEach((key) => delete allClients[key]);
893
+ };
894
+ return {
895
+ tools: allTools,
896
+ clients: allClients,
897
+ cleanupClients
898
+ };
899
+ }
900
+
901
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/tool-tag-processor.js
902
+ var ALL_TOOLS_PLACEHOLDER = "__ALL__";
903
+ function findToolId(toolName, tools, toolNameMapping) {
904
+ const mappedId = toolNameMapping?.get(toolName);
905
+ if (mappedId) {
906
+ return mappedId;
907
+ }
908
+ return Object.keys(tools).find((id) => {
909
+ const dotNotation = id.replace(/_/g, ".");
910
+ return toolName === id || toolName === dotNotation;
911
+ });
912
+ }
913
+ function processToolTags({ description, tagToResults, $, tools, toolOverrides, toolNameMapping }) {
914
+ tagToResults.tool.forEach((toolEl) => {
915
+ const toolName = toolEl.attribs.name;
916
+ if (!toolName || toolName.includes(ALL_TOOLS_PLACEHOLDER)) {
917
+ $(toolEl).remove();
918
+ return;
919
+ }
920
+ const override = toolOverrides.get(toolName);
921
+ if (override?.visibility?.hidden) {
922
+ $(toolEl).remove();
923
+ } else if (override?.visibility?.public) {
924
+ $(toolEl).replaceWith(`<tool name="${toolName}"/>`);
925
+ } else {
926
+ const toolId = findToolId(toolName, tools, toolNameMapping);
927
+ if (toolId) {
928
+ $(toolEl).replaceWith(`<tool name="${toolId}"/>`);
929
+ } else {
930
+ $(toolEl).remove();
931
+ }
932
+ }
933
+ });
934
+ return $.root().html() ?? description;
935
+ }
936
+
937
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/config-plugin.js
938
+ var createConfigPlugin = () => ({
939
+ name: "built-in-config",
940
+ version: "1.0.0",
941
+ enforce: "pre",
942
+ transformTool: (tool, context2) => {
943
+ const server = context2.server;
944
+ const config = server.findToolConfig?.(context2.toolName);
945
+ if (config?.description) {
946
+ tool.description = config.description;
947
+ }
948
+ return tool;
949
+ }
950
+ });
951
+ var config_plugin_default = createConfigPlugin();
952
+
953
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/tool-name-mapping-plugin.js
954
+ var createToolNameMappingPlugin = () => ({
955
+ name: "built-in-tool-name-mapping",
956
+ version: "1.0.0",
957
+ enforce: "pre",
958
+ transformTool: (tool, context2) => {
959
+ const server = context2.server;
960
+ const toolName = context2.toolName;
961
+ const originalName = tool._originalName || toolName;
962
+ const dotNotation = originalName.replace(/_/g, ".");
963
+ const underscoreNotation = originalName.replace(/\./g, "_");
964
+ if (dotNotation !== originalName && server.toolNameMapping) {
965
+ server.toolNameMapping.set(dotNotation, toolName);
966
+ }
967
+ if (underscoreNotation !== originalName && server.toolNameMapping) {
968
+ server.toolNameMapping.set(underscoreNotation, toolName);
969
+ }
970
+ if (originalName !== toolName && server.toolNameMapping) {
971
+ server.toolNameMapping.set(originalName, toolName);
972
+ }
973
+ return tool;
974
+ }
975
+ });
976
+ var tool_name_mapping_plugin_default = createToolNameMappingPlugin();
977
+
978
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/logger.js
979
+ var LOG_LEVELS = {
980
+ debug: 0,
981
+ info: 1,
982
+ notice: 2,
983
+ warning: 3,
984
+ error: 4,
985
+ critical: 5,
986
+ alert: 6,
987
+ emergency: 7
988
+ };
989
+ var MCPLogger = class _MCPLogger {
990
+ server;
991
+ loggerName;
992
+ minLevel = "debug";
993
+ constructor(loggerName = "mcpc", server) {
994
+ this.loggerName = loggerName;
995
+ this.server = server;
996
+ }
997
+ setServer(server) {
998
+ this.server = server;
999
+ }
1000
+ setLevel(level) {
1001
+ this.minLevel = level;
1002
+ }
1003
+ async log(level, data) {
1004
+ if (LOG_LEVELS[level] < LOG_LEVELS[this.minLevel]) {
1005
+ return;
1006
+ }
1007
+ this.logToConsole(level, data);
1008
+ if (this.server) {
1009
+ try {
1010
+ await this.server.sendLoggingMessage({
1011
+ level,
1012
+ logger: this.loggerName,
1013
+ data
1014
+ });
1015
+ } catch {
1016
+ }
1017
+ }
1018
+ }
1019
+ logToConsole(level, data) {
1020
+ const message = typeof data === "string" ? data : JSON.stringify(data);
1021
+ const prefix = `[${this.loggerName}:${level}]`;
1022
+ console.error(prefix, message);
1023
+ }
1024
+ debug(data) {
1025
+ return this.log("debug", data);
1026
+ }
1027
+ info(data) {
1028
+ return this.log("info", data);
1029
+ }
1030
+ notice(data) {
1031
+ return this.log("notice", data);
1032
+ }
1033
+ warning(data) {
1034
+ return this.log("warning", data);
1035
+ }
1036
+ error(data) {
1037
+ return this.log("error", data);
1038
+ }
1039
+ critical(data) {
1040
+ return this.log("critical", data);
1041
+ }
1042
+ alert(data) {
1043
+ return this.log("alert", data);
1044
+ }
1045
+ emergency(data) {
1046
+ return this.log("emergency", data);
1047
+ }
1048
+ child(name) {
1049
+ const child = new _MCPLogger(`${this.loggerName}.${name}`, this.server);
1050
+ child.setLevel(this.minLevel);
1051
+ return child;
1052
+ }
1053
+ };
1054
+ var logger = new MCPLogger("mcpc");
1055
+ function createLogger(name, server) {
1056
+ return new MCPLogger(name, server);
1057
+ }
1058
+
1059
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/logging-plugin.js
1060
+ var createLoggingPlugin = (options = {}) => {
1061
+ const { enabled = true, verbose = false, compact: compact2 = true } = options;
1062
+ return {
1063
+ name: "built-in-logging",
1064
+ version: "1.0.0",
1065
+ composeEnd: async (context2) => {
1066
+ if (!enabled) return;
1067
+ const logger2 = createLogger("mcpc.plugin.logging", context2.server);
1068
+ if (compact2) {
1069
+ const pluginCount = context2.pluginNames.length;
1070
+ const { stats } = context2;
1071
+ await logger2.info(`[${context2.toolName}] ${pluginCount} plugins \u2022 ${stats.publicTools} public \u2022 ${stats.hiddenTools} hidden`);
1072
+ } else if (verbose) {
1073
+ await logger2.info(`[${context2.toolName}] Composition complete`);
1074
+ await logger2.info(` \u251C\u2500 Plugins: ${context2.pluginNames.join(", ")}`);
1075
+ const { stats } = context2;
1076
+ const server = context2.server;
1077
+ const publicTools = Array.from(new Set(server.getPublicToolNames().map(String)));
1078
+ const internalTools = Array.from(new Set(server.getInternalToolNames().map(String)));
1079
+ const hiddenTools = Array.from(new Set(server.getHiddenToolNames().map(String)));
1080
+ const normalInternal = internalTools.filter((name) => !hiddenTools.includes(name));
1081
+ if (publicTools.length > 0) {
1082
+ await logger2.info(` \u251C\u2500 Public: ${publicTools.join(", ")}`);
1083
+ }
1084
+ if (internalTools.length > 0) {
1085
+ const parts = [];
1086
+ if (normalInternal.length > 0) {
1087
+ parts.push(normalInternal.join(", "));
1088
+ }
1089
+ if (hiddenTools.length > 0) {
1090
+ parts.push(`(${hiddenTools.join(", ")})`);
1091
+ }
1092
+ await logger2.info(` \u251C\u2500 Internal: ${parts.join(", ")}`);
1093
+ }
1094
+ await logger2.info(` \u2514\u2500 Total: ${stats.totalTools} tools`);
1095
+ }
1096
+ }
1097
+ };
1098
+ };
1099
+ var logging_plugin_default = createLoggingPlugin({
1100
+ verbose: true,
1101
+ compact: false
1102
+ });
1103
+
1104
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/prompts/index.js
1105
+ var SystemPrompts = {
1106
+ /**
1107
+ * Base system prompt for autonomous MCP execution
1108
+ */
1109
+ AUTONOMOUS_EXECUTION: `Agentic tool \`{toolName}\` that executes complex tasks by iteratively selecting and calling tools, gathering results, and continuing until completion. Use this tool when the task matches the manual below.
1110
+
1111
+ You must follow the <manual/>, obey the <execution_rules/>, and use the <call_format/>.
1112
+
1113
+ <manual>
1114
+ {description}
1115
+ </manual>
1116
+
1117
+ <parameters>
1118
+ \`useTool\` - Which tool to execute this iteration
1119
+ \`hasDefinitions\` - Tool names whose schemas you already have
1120
+ \`definitionsOf\` - Tool names whose schemas you need
1121
+ </parameters>
1122
+
1123
+ <execution_rules>
1124
+ 1. **First call**: No tool definitions available\u2014you must request them via \`definitionsOf\`
1125
+ 2. **When executing tools**: Must provide \`hasDefinitions\` with ALL tools you have schemas for (avoid duplicate requests and reduce tokens)
1126
+ 3. **When requesting definitions**: Use \`definitionsOf\` to request tool schemas you need
1127
+ 4. **Both together**: Execute tool AND request new definitions in one call for efficiency
1128
+ 5. **Never request definitions you already have**
1129
+ 6. **Select** one tool to execute per call using \`useTool\`
1130
+ 7. **Provide** parameters matching the selected tool name
1131
+ 8. Note: You are an agent exposed as an MCP tool - **\`useTool\` is an internal parameter for choosing which tool to execute, NOT an external MCP tool you can call**
1132
+ </execution_rules>
1133
+
1134
+ <call_format>
1135
+ Initial definition request:
1136
+ \`\`\`json
1137
+ {
1138
+ "hasDefinitions": [],
1139
+ "definitionsOf": ["tool1", "tool2"]
1140
+ }
1141
+ \`\`\`
1142
+
1143
+ Execute tool + get new definitions:
1144
+ \`\`\`json
1145
+ {
1146
+ "useTool": "tool1",
1147
+ "tool1": { /* parameters */ },
1148
+ "hasDefinitions": ["tool1", "tool2"],
1149
+ "definitionsOf": ["tool3"]
1150
+ }
1151
+ \`\`\`
1152
+ </call_format>`,
1153
+ /**
1154
+ * Workflow execution system prompt
1155
+ */
1156
+ WORKFLOW_EXECUTION: `Workflow tool \`{toolName}\` that executes multi-step workflows. Use this when your task requires sequential steps.
1157
+
1158
+ <manual>
1159
+ {description}
1160
+ </manual>
1161
+
1162
+ <rules>
1163
+ 1. First call: {planningInstructions}
1164
+ 2. Subsequent calls: Provide only current step parameters
1165
+ 3. Use \`decision: "proceed"\` to advance, \`"retry"\` to retry, \`"complete"\` when done
1166
+ 4. Include \`steps\` ONLY with \`init: true\`, never during execution
1167
+ </rules>`,
1168
+ /**
1169
+ * JSON-only execution system prompt for autonomous sampling mode
1170
+ *
1171
+ * Note: Sampling mode runs an internal LLM loop that autonomously calls tools until complete.
1172
+ */
1173
+ SAMPLING_EXECUTION: `Agent \`{toolName}\` that completes tasks by calling tools in an autonomous loop.
1174
+
1175
+ <manual>
1176
+ {description}
1177
+ </manual>
1178
+
1179
+ <rules>
1180
+ 1. Return valid JSON only (no markdown, no explanations)
1181
+ 2. Execute one action per iteration
1182
+ 3. When \`action\` is "X", include parameter "X" with tool inputs
1183
+ 4. Adapt based on results from previous actions
1184
+ 5. Continue until task is complete
1185
+ </rules>
1186
+
1187
+ <format>
1188
+ During execution:
1189
+ \`\`\`json
1190
+ {
1191
+ "action": "tool_name",
1192
+ "decision": "proceed|retry",
1193
+ "tool_name": { /* parameters */ }
1194
+ }
1195
+ \`\`\`
1196
+
1197
+ When complete (omit action):
1198
+ \`\`\`json
1199
+ { "decision": "complete" }
1200
+ \`\`\`
1201
+
1202
+ Decisions:
1203
+ - \`proceed\` = action succeeded, continue
1204
+ - \`retry\` = action failed, try again
1205
+ - \`complete\` = task finished
1206
+ </format>
1207
+
1208
+ <tools>
1209
+ {toolList}
1210
+ </tools>`,
1211
+ /**
1212
+ * Sampling workflow execution system prompt combining sampling with workflow capabilities
1213
+ *
1214
+ * Note: Sampling mode runs an internal LLM loop that autonomously executes workflows.
1215
+ */
1216
+ SAMPLING_WORKFLOW_EXECUTION: `Workflow agent \`{toolName}\` that executes multi-step workflows autonomously.
1217
+
1218
+ <manual>
1219
+ {description}
1220
+ </manual>
1221
+
1222
+ <rules>
1223
+ 1. Return valid JSON only
1224
+ 2. First iteration: Plan workflow and initialize with \`init: true\`
1225
+ 3. Subsequent iterations: Execute current step
1226
+ 4. Adapt based on step results
1227
+ 5. Continue until all steps complete
1228
+ </rules>
1229
+
1230
+ <format>
1231
+ Initialize workflow (first iteration):
1232
+ \`\`\`json
1233
+ {
1234
+ "action": "{toolName}",
1235
+ "init": true,
1236
+ "steps": [/* workflow steps */]
1237
+ }
1238
+ \`\`\`
1239
+
1240
+ Execute step (subsequent iterations):
1241
+ \`\`\`json
1242
+ {
1243
+ "action": "{toolName}",
1244
+ "decision": "proceed|retry",
1245
+ /* step parameters */
1246
+ }
1247
+ \`\`\`
1248
+
1249
+ Complete workflow (omit action):
1250
+ \`\`\`json
1251
+ { "decision": "complete" }
1252
+ \`\`\`
1253
+
1254
+ Decisions:
1255
+ - \`proceed\` = step succeeded, next step
1256
+ - \`retry\` = step failed, retry current
1257
+ - \`complete\` = workflow finished
1258
+
1259
+ Rules:
1260
+ - Include \`steps\` ONLY with \`init: true\`
1261
+ - Omit \`steps\` during step execution
1262
+ - Use \`decision: "retry"\` for failed steps
1263
+ </format>`
1264
+ };
1265
+ var WorkflowPrompts = {
1266
+ /**
1267
+ * Workflow initialization instructions
1268
+ */
1269
+ WORKFLOW_INIT: `Workflow initialized with {stepCount} steps. Execute step 1: \`{currentStepDescription}\`
1270
+
1271
+ Schema: {schemaDefinition}
1272
+
1273
+ Call \`{toolName}\` with:
1274
+ - Parameters matching schema above
1275
+ - \`decision: "proceed"\` to advance, \`"retry"\` to retry, \`"complete"\` when done
1276
+ - Omit \`steps\` (only used with \`init: true\`)
1277
+
1278
+ {workflowSteps}`,
1279
+ /**
1280
+ * Tool description enhancement for workflow mode
1281
+ */
1282
+ WORKFLOW_TOOL_DESCRIPTION: `{description}
1283
+ {initTitle}
1284
+ {ensureStepActions}
1285
+ {schemaDefinition}`,
1286
+ /**
1287
+ * Planning instructions for predefined workflows
1288
+ */
1289
+ PREDEFINED_WORKFLOW_PLANNING: `- Set \`init: true\` (steps are predefined)`,
1290
+ /**
1291
+ * Planning instructions for dynamic workflows
1292
+ */
1293
+ DYNAMIC_WORKFLOW_PLANNING: `- Set \`init: true\` and define complete \`steps\` array`,
1294
+ /**
1295
+ * Next step decision prompt
1296
+ */
1297
+ NEXT_STEP_DECISION: `Previous step completed.
1298
+
1299
+ Choose action:
1300
+ - RETRY: Call \`{toolName}\` with \`decision: "retry"\`
1301
+ - PROCEED: Call \`{toolName}\` with \`decision: "proceed"\` and parameters below
1302
+
1303
+ Next: \`{nextStepDescription}\`
1304
+ {nextStepSchema}
1305
+
1306
+ (Omit \`steps\` parameter)`,
1307
+ /**
1308
+ * Final step completion prompt
1309
+ */
1310
+ FINAL_STEP_COMPLETION: `Final step executed {statusIcon} - {statusText}
1311
+
1312
+ Choose:
1313
+ - RETRY: \`decision: "retry"\`
1314
+ - COMPLETE: \`decision: "complete"\`
1315
+ - NEW: \`init: true\`{newWorkflowInstructions}`,
1316
+ /**
1317
+ * Workflow completion success message
1318
+ */
1319
+ WORKFLOW_COMPLETED: `Workflow completed ({totalSteps} steps)
1320
+
1321
+ Start new workflow: \`{toolName}\` with \`init: true\`{newWorkflowInstructions}`,
1322
+ /**
1323
+ * Error messages
1324
+ */
1325
+ ERRORS: {
1326
+ NOT_INITIALIZED: {
1327
+ WITH_PREDEFINED: "Error: Workflow not initialized. Please provide 'init' parameter to start a new workflow.",
1328
+ WITHOUT_PREDEFINED: "Error: Workflow not initialized. Please provide 'init' and 'steps' parameter to start a new workflow."
1329
+ },
1330
+ ALREADY_AT_FINAL: "Error: Cannot proceed, already at the final step.",
1331
+ CANNOT_COMPLETE_NOT_AT_FINAL: "Error: Cannot complete workflow - you are not at the final step. Please use decision=proceed to continue to the next step.",
1332
+ NO_STEPS_PROVIDED: "Error: No steps provided",
1333
+ NO_CURRENT_STEP: "Error: No current step to execute"
1334
+ }
1335
+ };
1336
+ var ResponseTemplates = {
1337
+ /**
1338
+ * Success response for action execution
1339
+ */
1340
+ ACTION_SUCCESS: `Action \`{currentAction}\` completed.
1341
+
1342
+ Next: Execute \`{nextAction}\` by calling \`{toolName}\` again.`,
1343
+ /**
1344
+ * Planning prompt when no next action is specified
1345
+ */
1346
+ PLANNING_PROMPT: `Action \`{currentAction}\` completed. Determine next step:
1347
+
1348
+ 1. Analyze results from \`{currentAction}\`
1349
+ 2. Decide: Continue with another action or Complete?
1350
+ 3. Call \`{toolName}\` with chosen action or \`decision: "complete"\``,
1351
+ /**
1352
+ * Error response templates
1353
+ */
1354
+ ERROR_RESPONSE: `Validation failed: {errorMessage}
1355
+
1356
+ Adjust parameters and retry.`,
1357
+ WORKFLOW_ERROR_RESPONSE: `Step failed: {errorMessage}
1358
+
1359
+ Fix parameters and call with \`decision: "retry"\``,
1360
+ /**
1361
+ * Completion message
1362
+ */
1363
+ COMPLETION_MESSAGE: `Task completed.`,
1364
+ /**
1365
+ * Security validation messages
1366
+ */
1367
+ SECURITY_VALIDATION: {
1368
+ PASSED: `Security check passed: {operation} on {path}`,
1369
+ FAILED: `Security check failed: {operation} on {path}`
1370
+ },
1371
+ /**
1372
+ * Audit log messages
1373
+ */
1374
+ AUDIT_LOG: `[{timestamp}] {level}: {action} on {resource}{userInfo}`
1375
+ };
1376
+ var CompiledPrompts = {
1377
+ autonomousExecution: p(SystemPrompts.AUTONOMOUS_EXECUTION),
1378
+ workflowExecution: p(SystemPrompts.WORKFLOW_EXECUTION),
1379
+ samplingExecution: p(SystemPrompts.SAMPLING_EXECUTION),
1380
+ samplingWorkflowExecution: p(SystemPrompts.SAMPLING_WORKFLOW_EXECUTION),
1381
+ workflowInit: p(WorkflowPrompts.WORKFLOW_INIT),
1382
+ workflowToolDescription: p(WorkflowPrompts.WORKFLOW_TOOL_DESCRIPTION),
1383
+ nextStepDecision: p(WorkflowPrompts.NEXT_STEP_DECISION),
1384
+ finalStepCompletion: p(WorkflowPrompts.FINAL_STEP_COMPLETION),
1385
+ workflowCompleted: p(WorkflowPrompts.WORKFLOW_COMPLETED),
1386
+ actionSuccess: p(ResponseTemplates.ACTION_SUCCESS),
1387
+ planningPrompt: p(ResponseTemplates.PLANNING_PROMPT),
1388
+ errorResponse: p(ResponseTemplates.ERROR_RESPONSE),
1389
+ workflowErrorResponse: p(ResponseTemplates.WORKFLOW_ERROR_RESPONSE),
1390
+ securityPassed: p(ResponseTemplates.SECURITY_VALIDATION.PASSED),
1391
+ securityFailed: p(ResponseTemplates.SECURITY_VALIDATION.FAILED),
1392
+ auditLog: p(ResponseTemplates.AUDIT_LOG),
1393
+ completionMessage: () => ResponseTemplates.COMPLETION_MESSAGE
1394
+ };
1395
+ var PromptUtils = {
1396
+ /**
1397
+ * Generate tool list for descriptions
1398
+ */
1399
+ generateToolList: (tools) => {
1400
+ return tools.filter((tool) => !tool.hide).map((tool) => `<tool name="${tool.name}"${tool.description ? ` description="${tool.description}"` : ""}/>`).join("\n");
1401
+ },
1402
+ /**
1403
+ * Generate hidden tool list for descriptions
1404
+ */
1405
+ generateHiddenToolList: (tools) => {
1406
+ return tools.filter((tool) => tool.hide).map((tool) => `<tool name="${tool.name}" hide/>`).join("\n");
1407
+ },
1408
+ /**
1409
+ * Format workflow steps for display
1410
+ */
1411
+ formatWorkflowSteps: (steps) => {
1412
+ if (!steps.length) return "";
1413
+ return `## Workflow Steps
1414
+ ${JSON.stringify(steps, null, 2)}`;
1415
+ },
1416
+ /**
1417
+ * Format workflow progress display with status icons
1418
+ */
1419
+ formatWorkflowProgress: (progressData) => {
1420
+ const statusIcons = {
1421
+ pending: "[PENDING]",
1422
+ running: "[RUNNING]",
1423
+ completed: "[DONE]",
1424
+ failed: "[FAILED]"
1425
+ };
1426
+ return progressData.steps.map((step, index) => {
1427
+ const status = progressData.statuses[index] || "pending";
1428
+ const icon = statusIcons[status] || "[PENDING]";
1429
+ const current = index === progressData.currentStepIndex ? " **[CURRENT]**" : "";
1430
+ const actions = step.actions.length > 0 ? ` | Action: ${step.actions.join(", ")}` : "";
1431
+ return `${icon} **Step ${index + 1}:** ${step.description}${actions}${current}`;
1432
+ }).join("\n");
1433
+ },
1434
+ /**
1435
+ * Generate user info for audit logs
1436
+ */
1437
+ formatUserInfo: (user) => {
1438
+ return user ? ` by ${user}` : "";
1439
+ },
1440
+ /**
1441
+ * Format timestamp for logs
1442
+ */
1443
+ formatTimestamp: () => {
1444
+ return (/* @__PURE__ */ new Date()).toISOString();
1445
+ }
1446
+ };
1447
+
1448
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/schema-validator.js
1449
+ var import_ajv = require("ajv");
1450
+ var import_ajv_formats = __toESM(require("ajv-formats"), 1);
1451
+ var import_ajv_errors = __toESM(require("ajv-errors"), 1);
1452
+ var import_ajv_human_errors = require("@segment/ajv-human-errors");
1453
+ var ajv = new import_ajv.Ajv({
1454
+ allErrors: true,
1455
+ verbose: true
1456
+ });
1457
+ import_ajv_formats.default.default(ajv);
1458
+ import_ajv_errors.default.default(ajv);
1459
+ function validateSchema(args, schema) {
1460
+ const validate = ajv.compile(schema);
1461
+ if (!validate(args)) {
1462
+ const errors = validate.errors;
1463
+ const customErrors = errors.filter((err) => err.keyword === "errorMessage");
1464
+ if (customErrors.length > 0) {
1465
+ const messages = [
1466
+ ...new Set(customErrors.map((err) => err.message))
1467
+ ];
1468
+ return {
1469
+ valid: false,
1470
+ error: messages.join("; ")
1471
+ };
1472
+ }
1473
+ const aggregateError = new import_ajv_human_errors.AggregateAjvError(errors);
1474
+ return {
1475
+ valid: false,
1476
+ error: aggregateError.message
1477
+ };
1478
+ }
1479
+ return {
1480
+ valid: true
1481
+ };
1482
+ }
1483
+
1484
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/tracing.js
1485
+ var import_api = require("@opentelemetry/api");
1486
+ var import_sdk_trace_node = require("@opentelemetry/sdk-trace-node");
1487
+ var import_sdk_trace_base = require("@opentelemetry/sdk-trace-base");
1488
+ var import_exporter_trace_otlp_http = require("@opentelemetry/exporter-trace-otlp-http");
1489
+ var import_resources = require("@opentelemetry/resources");
1490
+ var import_semantic_conventions = require("@opentelemetry/semantic-conventions");
1491
+ var tracerProvider = null;
1492
+ var tracer = null;
1493
+ var isInitialized = false;
1494
+ function initializeTracing(config = {}) {
1495
+ if (isInitialized) {
1496
+ return;
1497
+ }
1498
+ const { enabled = true, serviceName = "mcpc-sampling", serviceVersion = "0.2.0", exportTo = "console", otlpEndpoint = "http://localhost:4318/v1/traces", otlpHeaders = {} } = config;
1499
+ if (!enabled) {
1500
+ isInitialized = true;
1501
+ return;
1502
+ }
1503
+ const resource = import_resources.Resource.default().merge(new import_resources.Resource({
1504
+ [import_semantic_conventions.ATTR_SERVICE_NAME]: serviceName,
1505
+ [import_semantic_conventions.ATTR_SERVICE_VERSION]: serviceVersion
1506
+ }));
1507
+ tracerProvider = new import_sdk_trace_node.NodeTracerProvider({
1508
+ resource
1509
+ });
1510
+ if (exportTo === "console") {
1511
+ tracerProvider.addSpanProcessor(new import_sdk_trace_base.SimpleSpanProcessor(new import_sdk_trace_base.ConsoleSpanExporter()));
1512
+ } else if (exportTo === "otlp") {
1513
+ const otlpExporter = new import_exporter_trace_otlp_http.OTLPTraceExporter({
1514
+ url: otlpEndpoint,
1515
+ headers: otlpHeaders
1516
+ });
1517
+ tracerProvider.addSpanProcessor(new import_sdk_trace_base.BatchSpanProcessor(otlpExporter));
1518
+ }
1519
+ tracerProvider.register();
1520
+ tracer = import_api.trace.getTracer(serviceName, serviceVersion);
1521
+ isInitialized = true;
1522
+ }
1523
+ function getTracer() {
1524
+ if (!isInitialized) {
1525
+ initializeTracing();
1526
+ }
1527
+ return tracer;
1528
+ }
1529
+ function startSpan(name, attributes, parent) {
1530
+ const tracer2 = getTracer();
1531
+ const ctx = parent ? import_api.trace.setSpan(import_api.context.active(), parent) : void 0;
1532
+ return tracer2.startSpan(name, {
1533
+ attributes
1534
+ }, ctx);
1535
+ }
1536
+ function endSpan(span, error) {
1537
+ if (error) {
1538
+ span.setStatus({
1539
+ code: import_api.SpanStatusCode.ERROR,
1540
+ message: error.message
1541
+ });
1542
+ span.recordException(error);
1543
+ } else {
1544
+ span.setStatus({
1545
+ code: import_api.SpanStatusCode.OK
1546
+ });
1547
+ }
1548
+ span.end();
1549
+ }
1550
+
1551
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/agentic/agentic-executor.js
1552
+ var import_node_process5 = __toESM(require("node:process"), 1);
1553
+ var AgenticExecutor = class {
1554
+ name;
1555
+ allToolNames;
1556
+ toolNameToDetailList;
1557
+ server;
1558
+ USE_TOOL_KEY;
1559
+ logger;
1560
+ tracingEnabled;
1561
+ constructor(name, allToolNames, toolNameToDetailList, server, USE_TOOL_KEY = "useTool") {
1562
+ this.name = name;
1563
+ this.allToolNames = allToolNames;
1564
+ this.toolNameToDetailList = toolNameToDetailList;
1565
+ this.server = server;
1566
+ this.USE_TOOL_KEY = USE_TOOL_KEY;
1567
+ this.tracingEnabled = false;
1568
+ this.logger = createLogger(`mcpc.agentic.${name}`, server);
1569
+ try {
1570
+ this.tracingEnabled = import_node_process5.default.env.MCPC_TRACING_ENABLED === "true";
1571
+ if (this.tracingEnabled) {
1572
+ initializeTracing({
1573
+ enabled: true,
1574
+ serviceName: `mcpc-agentic-${name}`,
1575
+ exportTo: import_node_process5.default.env.MCPC_TRACING_EXPORT ?? "otlp",
1576
+ otlpEndpoint: import_node_process5.default.env.MCPC_TRACING_OTLP_ENDPOINT ?? "http://localhost:4318/v1/traces"
1577
+ });
1578
+ }
1579
+ } catch {
1580
+ this.tracingEnabled = false;
1581
+ }
1582
+ }
1583
+ async execute(args, schema, parentSpan) {
1584
+ const executeSpan = this.tracingEnabled ? startSpan("mcpc.agentic_execute", {
1585
+ agent: this.name,
1586
+ selectTool: String(args[this.USE_TOOL_KEY] ?? "unknown"),
1587
+ args: JSON.stringify(args)
1588
+ }, parentSpan ?? void 0) : null;
1589
+ try {
1590
+ const validationResult = this.validate(args, schema);
1591
+ if (!validationResult.valid) {
1592
+ if (executeSpan) {
1593
+ executeSpan.setAttributes({
1594
+ validationError: true,
1595
+ errorMessage: validationResult.error || "Validation failed"
1596
+ });
1597
+ endSpan(executeSpan);
1598
+ }
1599
+ this.logger.warning({
1600
+ message: "Validation failed",
1601
+ selectTool: args[this.USE_TOOL_KEY],
1602
+ error: validationResult.error
1603
+ });
1604
+ return {
1605
+ content: [
1606
+ {
1607
+ type: "text",
1608
+ text: CompiledPrompts.errorResponse({
1609
+ errorMessage: validationResult.error || "Validation failed"
1610
+ })
1611
+ }
1612
+ ],
1613
+ isError: true
1614
+ };
1615
+ }
1616
+ const useTool = args[this.USE_TOOL_KEY];
1617
+ const definitionsOf = args.definitionsOf || [];
1618
+ const hasDefinitions = args.hasDefinitions || [];
1619
+ if (!useTool) {
1620
+ if (executeSpan) {
1621
+ executeSpan.setAttributes({
1622
+ toolType: "none",
1623
+ completion: true
1624
+ });
1625
+ endSpan(executeSpan);
1626
+ }
1627
+ const result = {
1628
+ content: []
1629
+ };
1630
+ this.appendToolSchemas(result, definitionsOf, hasDefinitions);
1631
+ if (result.content.length === 0 && definitionsOf.length > 0) {
1632
+ result.content.push({
1633
+ type: "text",
1634
+ text: `All requested tool schemas are already in hasDefinitions. You can now call a tool using "${this.USE_TOOL_KEY}".`
1635
+ });
1636
+ }
1637
+ return result;
1638
+ }
1639
+ if (executeSpan) {
1640
+ try {
1641
+ const safeTool = String(useTool).replace(/\s+/g, "_");
1642
+ if (typeof executeSpan.updateName === "function") {
1643
+ executeSpan.updateName(`mcpc.agentic_execute.${safeTool}`);
1644
+ }
1645
+ } catch {
1646
+ }
1647
+ }
1648
+ const currentTool = this.toolNameToDetailList.find(([name, _detail]) => name === useTool)?.[1];
1649
+ if (currentTool) {
1650
+ if (executeSpan) {
1651
+ executeSpan.setAttributes({
1652
+ toolType: "external",
1653
+ selectedTool: useTool
1654
+ });
1655
+ }
1656
+ this.logger.debug({
1657
+ message: "Executing external tool",
1658
+ selectTool: useTool
1659
+ });
1660
+ const currentResult = await currentTool.execute({
1661
+ ...args[useTool]
1662
+ });
1663
+ this.appendToolSchemas(currentResult, definitionsOf, hasDefinitions);
1664
+ if (executeSpan) {
1665
+ executeSpan.setAttributes({
1666
+ success: true,
1667
+ isError: !!currentResult.isError,
1668
+ resultContentLength: currentResult.content?.length || 0,
1669
+ toolResult: JSON.stringify(currentResult)
1670
+ });
1671
+ endSpan(executeSpan);
1672
+ }
1673
+ return currentResult;
1674
+ }
1675
+ if (this.allToolNames.includes(useTool)) {
1676
+ if (executeSpan) {
1677
+ executeSpan.setAttributes({
1678
+ toolType: "internal",
1679
+ selectedTool: useTool
1680
+ });
1681
+ }
1682
+ this.logger.debug({
1683
+ message: "Executing internal tool",
1684
+ selectTool: useTool
1685
+ });
1686
+ try {
1687
+ const result = await this.server.callTool(useTool, args[useTool]);
1688
+ const callToolResult = result ?? {
1689
+ content: []
1690
+ };
1691
+ this.appendToolSchemas(callToolResult, definitionsOf, hasDefinitions);
1692
+ if (executeSpan) {
1693
+ executeSpan.setAttributes({
1694
+ success: true,
1695
+ isError: !!callToolResult.isError,
1696
+ resultContentLength: callToolResult.content?.length || 0,
1697
+ toolResult: JSON.stringify(callToolResult)
1698
+ });
1699
+ endSpan(executeSpan);
1700
+ }
1701
+ return callToolResult;
1702
+ } catch (error) {
1703
+ if (executeSpan) {
1704
+ endSpan(executeSpan, error);
1705
+ }
1706
+ this.logger.error({
1707
+ message: "Error executing internal tool",
1708
+ useTool,
1709
+ error: String(error)
1710
+ });
1711
+ return {
1712
+ content: [
1713
+ {
1714
+ type: "text",
1715
+ text: `Error executing internal tool ${useTool}: ${error instanceof Error ? error.message : String(error)}`
1716
+ }
1717
+ ],
1718
+ isError: true
1719
+ };
1720
+ }
1721
+ }
1722
+ if (executeSpan) {
1723
+ executeSpan.setAttributes({
1724
+ toolType: "not_found",
1725
+ useTool
1726
+ });
1727
+ endSpan(executeSpan);
1728
+ }
1729
+ return {
1730
+ content: [
1731
+ {
1732
+ type: "text",
1733
+ text: `Tool "${useTool}" not found. Available tools: ${this.allToolNames.join(", ")}.`
1734
+ }
1735
+ ],
1736
+ isError: true
1737
+ };
1738
+ } catch (error) {
1739
+ if (executeSpan) {
1740
+ endSpan(executeSpan, error);
1741
+ }
1742
+ this.logger.error({
1743
+ message: "Unexpected error in execute",
1744
+ error: String(error)
1745
+ });
1746
+ return {
1747
+ content: [
1748
+ {
1749
+ type: "text",
1750
+ text: `Unexpected error: ${error instanceof Error ? error.message : String(error)}`
1751
+ }
1752
+ ],
1753
+ isError: true
1754
+ };
1755
+ }
1756
+ }
1757
+ // Append tool schemas to result if requested
1758
+ appendToolSchemas(result, definitionsOf, hasDefinitions) {
1759
+ const schemasToProvide = definitionsOf.filter((toolName) => !hasDefinitions.includes(toolName));
1760
+ if (schemasToProvide.length === 0) {
1761
+ return;
1762
+ }
1763
+ const definitionTexts = [];
1764
+ for (const toolName of schemasToProvide) {
1765
+ const toolDetail = this.toolNameToDetailList.find(([name]) => name === toolName);
1766
+ if (toolDetail) {
1767
+ const [name, schema] = toolDetail;
1768
+ const schemaJson = JSON.stringify(schema, null, 2);
1769
+ definitionTexts.push(`<tool_definition name="${name}">
1770
+ ${schemaJson}
1771
+ </tool_definition>`);
1772
+ }
1773
+ }
1774
+ if (definitionTexts.length > 0) {
1775
+ result.content.push({
1776
+ type: "text",
1777
+ text: `${definitionTexts.join("\n\n")}`
1778
+ });
1779
+ }
1780
+ }
1781
+ // Validate arguments using JSON schema
1782
+ validate(args, schema) {
1783
+ return validateSchema(args, schema);
1784
+ }
1785
+ };
1786
+
1787
+ // __mcpc__cli_latest/node_modules/@jsr/es-toolkit__es-toolkit/src/function/partial.js
1788
+ function partial(func, ...partialArgs) {
1789
+ return partialImpl(func, placeholderSymbol, ...partialArgs);
1790
+ }
1791
+ function partialImpl(func, placeholder, ...partialArgs) {
1792
+ const partialed = function(...providedArgs) {
1793
+ let providedArgsIndex = 0;
1794
+ const substitutedArgs = partialArgs.slice().map((arg) => arg === placeholder ? providedArgs[providedArgsIndex++] : arg);
1795
+ const remainingArgs = providedArgs.slice(providedArgsIndex);
1796
+ return func.apply(this, substitutedArgs.concat(remainingArgs));
1797
+ };
1798
+ if (func.prototype) {
1799
+ partialed.prototype = Object.create(func.prototype);
1800
+ }
1801
+ return partialed;
1802
+ }
1803
+ var placeholderSymbol = Symbol("partial.placeholder");
1804
+ partial.placeholder = placeholderSymbol;
1805
+
1806
+ // __mcpc__cli_latest/node_modules/@jsr/es-toolkit__es-toolkit/src/function/partialRight.js
1807
+ function partialRight(func, ...partialArgs) {
1808
+ return partialRightImpl(func, placeholderSymbol2, ...partialArgs);
1809
+ }
1810
+ function partialRightImpl(func, placeholder, ...partialArgs) {
1811
+ const partialedRight = function(...providedArgs) {
1812
+ const placeholderLength = partialArgs.filter((arg) => arg === placeholder).length;
1813
+ const rangeLength = Math.max(providedArgs.length - placeholderLength, 0);
1814
+ const remainingArgs = providedArgs.slice(0, rangeLength);
1815
+ let providedArgsIndex = rangeLength;
1816
+ const substitutedArgs = partialArgs.slice().map((arg) => arg === placeholder ? providedArgs[providedArgsIndex++] : arg);
1817
+ return func.apply(this, remainingArgs.concat(substitutedArgs));
1818
+ };
1819
+ if (func.prototype) {
1820
+ partialedRight.prototype = Object.create(func.prototype);
1821
+ }
1822
+ return partialedRight;
1823
+ }
1824
+ var placeholderSymbol2 = Symbol("partialRight.placeholder");
1825
+ partialRight.placeholder = placeholderSymbol2;
1826
+
1827
+ // __mcpc__cli_latest/node_modules/@jsr/es-toolkit__es-toolkit/src/function/retry.js
1828
+ var DEFAULT_RETRIES = Number.POSITIVE_INFINITY;
1829
+
1830
+ // __mcpc__cli_latest/node_modules/@jsr/es-toolkit__es-toolkit/src/object/pick.js
1831
+ function pick(obj, keys) {
1832
+ const result = {};
1833
+ for (let i = 0; i < keys.length; i++) {
1834
+ const key = keys[i];
1835
+ if (Object.hasOwn(obj, key)) {
1836
+ result[key] = obj[key];
1837
+ }
1838
+ }
1839
+ return result;
1840
+ }
1841
+
1842
+ // __mcpc__cli_latest/node_modules/@jsr/es-toolkit__es-toolkit/src/string/deburr.js
1843
+ var deburrMap = new Map(
1844
+ // eslint-disable-next-line no-restricted-syntax
1845
+ Object.entries({
1846
+ \u00C6: "Ae",
1847
+ \u00D0: "D",
1848
+ \u00D8: "O",
1849
+ \u00DE: "Th",
1850
+ \u00DF: "ss",
1851
+ \u00E6: "ae",
1852
+ \u00F0: "d",
1853
+ \u00F8: "o",
1854
+ \u00FE: "th",
1855
+ \u0110: "D",
1856
+ \u0111: "d",
1857
+ \u0126: "H",
1858
+ \u0127: "h",
1859
+ \u0131: "i",
1860
+ \u0132: "IJ",
1861
+ \u0133: "ij",
1862
+ \u0138: "k",
1863
+ \u013F: "L",
1864
+ \u0140: "l",
1865
+ \u0141: "L",
1866
+ \u0142: "l",
1867
+ \u0149: "'n",
1868
+ \u014A: "N",
1869
+ \u014B: "n",
1870
+ \u0152: "Oe",
1871
+ \u0153: "oe",
1872
+ \u0166: "T",
1873
+ \u0167: "t",
1874
+ \u017F: "s"
1875
+ })
1876
+ );
1877
+
1878
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/factories/args-def-factory.js
1879
+ var DECISION_OPTIONS = {
1880
+ RETRY: "retry",
1881
+ PROCEED: "proceed",
1882
+ COMPLETE: "complete"
1883
+ };
1884
+ function createArgsDefFactory(name, allToolNames, depGroups, predefinedSteps, ensureStepActions) {
1885
+ const formatEnsureStepActions = () => {
1886
+ if (!ensureStepActions || ensureStepActions.length === 0) {
1887
+ return "";
1888
+ }
1889
+ return `
1890
+
1891
+ ## Required Actions
1892
+ The workflow MUST include at least one of these actions:
1893
+ ${ensureStepActions.map((action) => `- \`${action}\``).join("\n")}`;
1894
+ };
1895
+ return {
1896
+ common: (extra, optionalFields = []) => {
1897
+ const requiredFields = Object.keys(extra).filter((key) => !optionalFields.includes(key));
1898
+ return {
1899
+ type: "object",
1900
+ description: `**Tool parameters dynamically update per workflow step**`,
1901
+ properties: {
1902
+ ...extra
1903
+ },
1904
+ required: requiredFields
1905
+ };
1906
+ },
1907
+ steps: () => ({
1908
+ type: "array",
1909
+ description: `
1910
+ Workflow step definitions - provide ONLY on initial call.
1911
+
1912
+ **CRITICAL RULES:**
1913
+ - **Sequential Dependency:** If Action B depends on Action A's result \u2192 separate steps
1914
+ - **Concurrent Actions:** Independent actions can share one step
1915
+ - **Complete Mapping:** Include ALL requested operations
1916
+ - **Predefined Steps:** Leave unspecified if predefined steps exist
1917
+
1918
+ **BEST PRACTICES:**
1919
+ - Atomic, focused steps
1920
+ - Idempotent actions for safe retries
1921
+ - Clear step descriptions with input/output context`,
1922
+ items: {
1923
+ type: "object",
1924
+ description: `A single step containing actions that execute concurrently. All actions in this step run simultaneously with no guaranteed order.`,
1925
+ properties: {
1926
+ description: {
1927
+ type: "string",
1928
+ description: `**Step purpose, required inputs, and expected outputs**`
1929
+ },
1930
+ actions: {
1931
+ type: "array",
1932
+ description: `Array of action names for this step. **CURRENT LIMITATION: Only 1 action per step is allowed.** Action names must match available tool names exactly.`,
1933
+ items: {
1934
+ ...{
1935
+ enum: allToolNames
1936
+ },
1937
+ type: "string",
1938
+ description: `Individual action name from available tools. Must be exactly one of the allowed tool names.`
1939
+ },
1940
+ uniqueItems: true,
1941
+ minItems: 0,
1942
+ // TODO: remove this restriction when workflow planning is good enough
1943
+ maxItems: 1
1944
+ }
1945
+ },
1946
+ required: [
1947
+ "description",
1948
+ "actions"
1949
+ ],
1950
+ additionalProperties: false
1951
+ },
1952
+ default: predefinedSteps ? predefinedSteps : void 0,
1953
+ minItems: 1
1954
+ }),
1955
+ init: () => ({
1956
+ type: "boolean",
1957
+ description: `Init a new workflow`,
1958
+ enum: [
1959
+ true
1960
+ ]
1961
+ }),
1962
+ decision: () => ({
1963
+ type: "string",
1964
+ enum: Object.values(DECISION_OPTIONS),
1965
+ description: `**Step control: \`${DECISION_OPTIONS.PROCEED}\` = next step, \`${DECISION_OPTIONS.RETRY}\` = retry/repeat current, \`${DECISION_OPTIONS.COMPLETE}\` = finish workflow**`,
1966
+ errorMessage: {
1967
+ enum: `Invalid decision. Must be one of: ${Object.values(DECISION_OPTIONS).join(", ")}.`
1968
+ }
1969
+ }),
1970
+ action: () => ({
1971
+ type: "string",
1972
+ description: "Define the current workflow action to be performed",
1973
+ enum: allToolNames,
1974
+ required: [
1975
+ "action"
1976
+ ],
1977
+ errorMessage: {
1978
+ enum: `Invalid action. Must be one of: ${allToolNames.join(", ")}.`
1979
+ }
1980
+ }),
1981
+ forTool: function() {
1982
+ return this.common({});
1983
+ },
1984
+ forCurrentState: function(state) {
1985
+ const currentStep = state.getCurrentStep();
1986
+ if (!state.isWorkflowInitialized() || !currentStep) {
1987
+ state.reset();
1988
+ const initSchema = {
1989
+ init: this.init()
1990
+ };
1991
+ if (!predefinedSteps) {
1992
+ initSchema.steps = this.steps();
1993
+ }
1994
+ return this.common(initSchema);
1995
+ }
1996
+ const stepDependencies = {
1997
+ ...pick(depGroups, currentStep.actions)
1998
+ };
1999
+ stepDependencies["decision"] = this.decision();
2000
+ stepDependencies["action"] = this.action();
2001
+ return this.common(stepDependencies);
2002
+ },
2003
+ forSampling: function() {
2004
+ return {
2005
+ type: "object",
2006
+ description: "Provide user request for autonomous tool execution",
2007
+ properties: {
2008
+ userRequest: {
2009
+ type: "string",
2010
+ description: "The task or request that should be completed autonomously by the agentic system using available tools"
2011
+ },
2012
+ context: {
2013
+ type: "object",
2014
+ description: "Necessary context for the request, e.g., the absolute path of the current working directory. This is just an example; any relevant context fields are allowed.",
2015
+ additionalProperties: true
2016
+ }
2017
+ },
2018
+ required: [
2019
+ "userRequest",
2020
+ "context"
2021
+ ],
2022
+ errorMessage: {
2023
+ required: {
2024
+ userRequest: "Missing required field 'userRequest'. Please provide a clear task description.",
2025
+ context: "Missing required field 'context'. Please provide relevant context (e.g., current working directory)."
2026
+ }
2027
+ }
2028
+ };
2029
+ },
2030
+ forAgentic: function(toolNameToDetailList, _sampling = false, USE_TOOL_KEY = "useTool") {
2031
+ const allOf = [
2032
+ // When a specific tool is selected, its parameters must be provided
2033
+ ...toolNameToDetailList.map(([toolName, _toolDetail]) => {
2034
+ return {
2035
+ if: {
2036
+ properties: {
2037
+ [USE_TOOL_KEY]: {
2038
+ const: toolName
2039
+ }
2040
+ },
2041
+ required: [
2042
+ USE_TOOL_KEY
2043
+ ]
2044
+ },
2045
+ then: {
2046
+ required: [
2047
+ toolName
2048
+ ],
2049
+ errorMessage: {
2050
+ required: {
2051
+ [toolName]: `Tool "${toolName}" is selected but its parameters are missing. Please provide "${toolName}": { ...parameters }.`
2052
+ }
2053
+ }
2054
+ }
2055
+ };
2056
+ })
2057
+ ];
2058
+ const useToolDescription = `Specifies which tool to execute from the available options. **When setting \`useTool: "example_tool"\`, you MUST also provide \`"example_tool": { ...parameters }\` with that tool's parameters**`;
2059
+ const toolItems = allToolNames.length > 0 ? {
2060
+ type: "string",
2061
+ enum: allToolNames
2062
+ } : {
2063
+ type: "string"
2064
+ };
2065
+ const baseProperties = {
2066
+ [USE_TOOL_KEY]: {
2067
+ type: "string",
2068
+ enum: allToolNames,
2069
+ description: useToolDescription,
2070
+ errorMessage: {
2071
+ enum: `Invalid tool name. Available tools: ${allToolNames.join(", ")}.`
2072
+ }
2073
+ },
2074
+ hasDefinitions: {
2075
+ type: "array",
2076
+ items: toolItems,
2077
+ description: "Tool names whose schemas you already have. List all tools you have schemas for to avoid duplicate schema requests and reduce token usage."
2078
+ },
2079
+ definitionsOf: {
2080
+ type: "array",
2081
+ items: toolItems,
2082
+ description: "Tool names whose schemas you need. Request tool schemas before calling them to understand their parameters."
2083
+ }
2084
+ };
2085
+ const requiredFields = [];
2086
+ const schema = {
2087
+ additionalProperties: true,
2088
+ type: "object",
2089
+ properties: baseProperties,
2090
+ required: requiredFields
2091
+ };
2092
+ if (allOf.length > 0) {
2093
+ schema.allOf = allOf;
2094
+ }
2095
+ if (allToolNames.length > 0) {
2096
+ const thenClause = {
2097
+ required: [
2098
+ USE_TOOL_KEY
2099
+ ],
2100
+ errorMessage: {
2101
+ required: {
2102
+ [USE_TOOL_KEY]: `No tool selected. Please specify "${USE_TOOL_KEY}" to select one of: ${allToolNames.join(", ")}. Or use "definitionsOf" with tool names to get their schemas first.`
2103
+ }
2104
+ }
2105
+ };
2106
+ Object.assign(schema, {
2107
+ if: {
2108
+ // definitionsOf is not provided OR is empty array
2109
+ anyOf: [
2110
+ {
2111
+ not: {
2112
+ required: [
2113
+ "definitionsOf"
2114
+ ]
2115
+ }
2116
+ },
2117
+ {
2118
+ properties: {
2119
+ definitionsOf: {
2120
+ type: "array",
2121
+ maxItems: 0
2122
+ }
2123
+ }
2124
+ }
2125
+ ]
2126
+ },
2127
+ then: thenClause
2128
+ });
2129
+ }
2130
+ return schema;
2131
+ },
2132
+ forNextState: function(state) {
2133
+ if (!state.isWorkflowInitialized() || !state.hasNextStep()) {
2134
+ throw new Error(`Cannot get next state schema: no next step available`);
2135
+ }
2136
+ const currentStepIndex = state.getCurrentStepIndex();
2137
+ const allSteps = state.getSteps();
2138
+ const nextStep = allSteps[currentStepIndex + 1];
2139
+ if (!nextStep) {
2140
+ throw new Error(`Next step not found`);
2141
+ }
2142
+ const stepDependencies = {
2143
+ ...pick(depGroups, nextStep.actions)
2144
+ };
2145
+ stepDependencies["decision"] = this.decision();
2146
+ stepDependencies["action"] = this.action();
2147
+ return this.common(stepDependencies);
2148
+ },
2149
+ forToolDescription: function(description, state) {
2150
+ const enforceToolArgs = this.forCurrentState(state);
2151
+ const initTitle = predefinedSteps ? `**YOU MUST execute this tool with following tool arguments to init the workflow**
2152
+ NOTE: The \`steps\` has been predefined` : `**You MUST execute this tool with following tool arguments to plan and init the workflow**`;
2153
+ return CompiledPrompts.workflowToolDescription({
2154
+ description,
2155
+ initTitle,
2156
+ ensureStepActions: formatEnsureStepActions(),
2157
+ schemaDefinition: JSON.stringify(enforceToolArgs, null, 2)
2158
+ });
2159
+ },
2160
+ forInitialStepDescription: function(steps, state) {
2161
+ return CompiledPrompts.workflowInit({
2162
+ stepCount: steps.length.toString(),
2163
+ currentStepDescription: state.getCurrentStep()?.description || "",
2164
+ toolName: name,
2165
+ schemaDefinition: JSON.stringify(this.forCurrentState(state), null, 2),
2166
+ // Remove redundant workflow steps display
2167
+ workflowSteps: ""
2168
+ });
2169
+ }
2170
+ };
2171
+ }
2172
+
2173
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/agentic/agentic-tool-registrar.js
2174
+ function registerAgenticTool(server, { description, name, allToolNames, depGroups, toolNameToDetailList }) {
2175
+ const createArgsDef = createArgsDefFactory(name, allToolNames, depGroups, void 0, void 0);
2176
+ const agenticExecutor = new AgenticExecutor(name, allToolNames, toolNameToDetailList, server);
2177
+ description = CompiledPrompts.autonomousExecution({
2178
+ toolName: name,
2179
+ description
2180
+ });
2181
+ const agenticArgsDef = createArgsDef.forAgentic(toolNameToDetailList, false);
2182
+ const argsDef = agenticArgsDef;
2183
+ const schema = allToolNames.length > 0 ? argsDef : {
2184
+ type: "object",
2185
+ properties: {}
2186
+ };
2187
+ server.tool(name, description, jsonSchema(createModelCompatibleJSONSchema(schema)), async (args) => {
2188
+ return await agenticExecutor.execute(args, schema);
2189
+ });
2190
+ }
2191
+
2192
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/mode-agentic-plugin.js
2193
+ var createAgenticModePlugin = () => ({
2194
+ name: "mode-agentic",
2195
+ version: "1.0.0",
2196
+ // Only apply to agentic mode
2197
+ apply: "agentic",
2198
+ // Register the agent tool
2199
+ registerAgentTool: (context2) => {
2200
+ registerAgenticTool(context2.server, {
2201
+ description: context2.description,
2202
+ name: context2.name,
2203
+ allToolNames: context2.allToolNames,
2204
+ depGroups: context2.depGroups,
2205
+ toolNameToDetailList: context2.toolNameToDetailList
2206
+ });
2207
+ }
2208
+ });
2209
+ var mode_agentic_plugin_default = createAgenticModePlugin();
2210
+
2211
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/state.js
2212
+ var WorkflowState = class {
2213
+ currentStepIndex = -1;
2214
+ steps = [];
2215
+ stepStatuses = [];
2216
+ stepResults = [];
2217
+ stepErrors = [];
2218
+ isInitialized = false;
2219
+ isStarted = false;
2220
+ constructor(steps) {
2221
+ if (steps) {
2222
+ this.initialize(steps);
2223
+ }
2224
+ }
2225
+ getCurrentStepIndex() {
2226
+ return this.currentStepIndex;
2227
+ }
2228
+ getSteps() {
2229
+ return this.steps;
2230
+ }
2231
+ isWorkflowInitialized() {
2232
+ return this.isInitialized;
2233
+ }
2234
+ getCurrentStep() {
2235
+ if (!this.isInitialized || this.currentStepIndex < 0) {
2236
+ return null;
2237
+ }
2238
+ return this.steps[this.currentStepIndex] || null;
2239
+ }
2240
+ getNextStep() {
2241
+ if (!this.isInitialized) return null;
2242
+ const nextIndex = this.currentStepIndex + 1;
2243
+ return this.steps[nextIndex] || null;
2244
+ }
2245
+ // Get the previous step in the workflow
2246
+ getPreviousStep() {
2247
+ if (!this.isInitialized) return null;
2248
+ const prevIndex = this.currentStepIndex - 1;
2249
+ return this.steps[prevIndex] || null;
2250
+ }
2251
+ hasNextStep() {
2252
+ return this.getNextStep() !== null;
2253
+ }
2254
+ // Check if there is a previous step available
2255
+ hasPreviousStep() {
2256
+ return this.getPreviousStep() !== null;
2257
+ }
2258
+ // Check if currently at the first step
2259
+ isAtFirstStep() {
2260
+ return this.isInitialized && this.currentStepIndex === 0;
2261
+ }
2262
+ // Check if currently at the last step
2263
+ isAtLastStep() {
2264
+ return this.isInitialized && this.currentStepIndex >= this.steps.length - 1;
2265
+ }
2266
+ isWorkflowStarted() {
2267
+ return this.isStarted;
2268
+ }
2269
+ isCompleted() {
2270
+ return this.isInitialized && this.currentStepIndex > this.steps.length - 1;
2271
+ }
2272
+ // Mark workflow as completed by moving beyond the last step
2273
+ markCompleted() {
2274
+ if (this.isInitialized) {
2275
+ this.currentStepIndex = this.steps.length;
2276
+ }
2277
+ }
2278
+ initialize(steps) {
2279
+ this.steps = steps;
2280
+ this.stepStatuses = new Array(steps.length).fill("pending");
2281
+ this.stepResults = new Array(steps.length).fill("");
2282
+ this.stepErrors = new Array(steps.length).fill("");
2283
+ this.currentStepIndex = 0;
2284
+ this.isInitialized = true;
2285
+ this.isStarted = false;
2286
+ }
2287
+ // Mark current step as running
2288
+ markCurrentStepRunning() {
2289
+ if (this.isInitialized && this.currentStepIndex >= 0 && this.currentStepIndex < this.steps.length) {
2290
+ this.stepStatuses[this.currentStepIndex] = "running";
2291
+ }
2292
+ }
2293
+ // Mark current step as completed
2294
+ markCurrentStepCompleted(result) {
2295
+ if (this.isInitialized && this.currentStepIndex >= 0 && this.currentStepIndex < this.steps.length) {
2296
+ this.stepStatuses[this.currentStepIndex] = "completed";
2297
+ if (result) {
2298
+ this.stepResults[this.currentStepIndex] = result;
2299
+ }
2300
+ }
2301
+ }
2302
+ // Mark current step as failed
2303
+ markCurrentStepFailed(error) {
2304
+ if (this.isInitialized && this.currentStepIndex >= 0 && this.currentStepIndex < this.steps.length) {
2305
+ this.stepStatuses[this.currentStepIndex] = "failed";
2306
+ if (error) {
2307
+ this.stepErrors[this.currentStepIndex] = error;
2308
+ }
2309
+ }
2310
+ }
2311
+ // Get steps with their status
2312
+ getStepsWithStatus() {
2313
+ return this.steps.map((step, index) => ({
2314
+ ...step,
2315
+ status: this.stepStatuses[index] || "pending",
2316
+ result: this.stepResults[index] || void 0,
2317
+ error: this.stepErrors[index] || void 0
2318
+ }));
2319
+ }
2320
+ // Get basic workflow progress data for template rendering
2321
+ getProgressData() {
2322
+ return {
2323
+ steps: this.steps,
2324
+ statuses: this.stepStatuses,
2325
+ results: this.stepResults,
2326
+ errors: this.stepErrors,
2327
+ currentStepIndex: this.currentStepIndex,
2328
+ totalSteps: this.steps.length
2329
+ };
2330
+ }
2331
+ start() {
2332
+ this.isStarted = true;
2333
+ }
2334
+ moveToNextStep() {
2335
+ if (!this.hasNextStep()) {
2336
+ return false;
2337
+ }
2338
+ this.currentStepIndex++;
2339
+ return true;
2340
+ }
2341
+ // Move to the previous step in the workflow
2342
+ moveToPreviousStep() {
2343
+ if (!this.hasPreviousStep()) {
2344
+ return false;
2345
+ }
2346
+ this.currentStepIndex--;
2347
+ return true;
2348
+ }
2349
+ // Move to a specific step by index (optional feature)
2350
+ moveToStep(stepIndex) {
2351
+ if (!this.isInitialized || stepIndex < 0 || stepIndex >= this.steps.length) {
2352
+ return false;
2353
+ }
2354
+ this.currentStepIndex = stepIndex;
2355
+ return true;
2356
+ }
2357
+ reset() {
2358
+ this.currentStepIndex = -1;
2359
+ this.steps = [];
2360
+ this.stepStatuses = [];
2361
+ this.stepResults = [];
2362
+ this.stepErrors = [];
2363
+ this.isInitialized = false;
2364
+ this.isStarted = false;
2365
+ }
2366
+ getDebugInfo() {
2367
+ return {
2368
+ currentStepIndex: this.currentStepIndex,
2369
+ totalSteps: this.steps.length,
2370
+ isInitialized: this.isInitialized,
2371
+ currentStep: this.getCurrentStep()?.description,
2372
+ nextStep: this.getNextStep()?.description,
2373
+ previousStep: this.getPreviousStep()?.description,
2374
+ isAtFirstStep: this.isAtFirstStep(),
2375
+ hasPreviousStep: this.hasPreviousStep()
2376
+ };
2377
+ }
2378
+ };
2379
+
2380
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/workflow/workflow-executor.js
2381
+ var WorkflowExecutor = class {
2382
+ name;
2383
+ allToolNames;
2384
+ toolNameToDetailList;
2385
+ createArgsDef;
2386
+ server;
2387
+ predefinedSteps;
2388
+ ensureStepActions;
2389
+ toolNameToIdMapping;
2390
+ constructor(name, allToolNames, toolNameToDetailList, createArgsDef, server, predefinedSteps, ensureStepActions, toolNameToIdMapping) {
2391
+ this.name = name;
2392
+ this.allToolNames = allToolNames;
2393
+ this.toolNameToDetailList = toolNameToDetailList;
2394
+ this.createArgsDef = createArgsDef;
2395
+ this.server = server;
2396
+ this.predefinedSteps = predefinedSteps;
2397
+ this.ensureStepActions = ensureStepActions;
2398
+ this.toolNameToIdMapping = toolNameToIdMapping;
2399
+ }
2400
+ // Helper method to validate required actions are present in workflow steps
2401
+ validateRequiredActions(steps) {
2402
+ if (!this.ensureStepActions || this.ensureStepActions.length === 0) {
2403
+ return {
2404
+ valid: true,
2405
+ missing: []
2406
+ };
2407
+ }
2408
+ const allStepActions = /* @__PURE__ */ new Set();
2409
+ steps.forEach((step) => {
2410
+ step.actions.forEach((action) => allStepActions.add(action));
2411
+ });
2412
+ const missing = [];
2413
+ for (const requiredAction of this.ensureStepActions) {
2414
+ if (allStepActions.has(requiredAction)) {
2415
+ continue;
2416
+ }
2417
+ if (this.toolNameToIdMapping) {
2418
+ const mappedToolId = this.toolNameToIdMapping.get(requiredAction);
2419
+ if (mappedToolId && allStepActions.has(mappedToolId)) {
2420
+ continue;
2421
+ }
2422
+ }
2423
+ missing.push(requiredAction);
2424
+ }
2425
+ return {
2426
+ valid: missing.length === 0,
2427
+ missing
2428
+ };
2429
+ }
2430
+ // Helper method to format workflow progress
2431
+ formatProgress(state) {
2432
+ const progressData = state.getProgressData();
2433
+ return PromptUtils.formatWorkflowProgress(progressData);
2434
+ }
2435
+ async execute(args, state) {
2436
+ if (args.init) {
2437
+ state.reset();
2438
+ } else {
2439
+ if (!state.isWorkflowInitialized() && !args.init) {
2440
+ return {
2441
+ content: [
2442
+ {
2443
+ type: "text",
2444
+ text: this.predefinedSteps ? WorkflowPrompts.ERRORS.NOT_INITIALIZED.WITH_PREDEFINED : WorkflowPrompts.ERRORS.NOT_INITIALIZED.WITHOUT_PREDEFINED
2445
+ }
2446
+ ],
2447
+ isError: true
2448
+ };
2449
+ }
2450
+ const decision2 = args.decision;
2451
+ if (decision2 === "proceed") {
2452
+ if (state.isAtLastStep() && state.isWorkflowStarted()) {
2453
+ state.markCompleted();
2454
+ return {
2455
+ content: [
2456
+ {
2457
+ type: "text",
2458
+ text: `## Workflow Completed!
2459
+
2460
+ ${this.formatProgress(state)}
2461
+
2462
+ ${CompiledPrompts.workflowCompleted({
2463
+ totalSteps: state.getSteps().length,
2464
+ toolName: this.name,
2465
+ newWorkflowInstructions: this.predefinedSteps ? "" : " and new `steps` array"
2466
+ })}`
2467
+ }
2468
+ ],
2469
+ isError: false
2470
+ };
2471
+ }
2472
+ if (state.isCompleted()) {
2473
+ return {
2474
+ content: [
2475
+ {
2476
+ type: "text",
2477
+ text: WorkflowPrompts.ERRORS.ALREADY_AT_FINAL
2478
+ }
2479
+ ],
2480
+ isError: true
2481
+ };
2482
+ }
2483
+ const currentStepIndex = state.getCurrentStepIndex();
2484
+ const wasStarted = state.isWorkflowStarted();
2485
+ if (state.isWorkflowStarted()) {
2486
+ state.moveToNextStep();
2487
+ } else {
2488
+ state.start();
2489
+ }
2490
+ const nextStepValidationSchema = this.createArgsDef.forCurrentState(state);
2491
+ const nextStepValidationResult = this.validateInput(args, nextStepValidationSchema);
2492
+ if (!nextStepValidationResult.valid) {
2493
+ if (wasStarted) {
2494
+ state.moveToStep(currentStepIndex);
2495
+ } else {
2496
+ state.moveToStep(currentStepIndex);
2497
+ }
2498
+ return {
2499
+ content: [
2500
+ {
2501
+ type: "text",
2502
+ text: CompiledPrompts.workflowErrorResponse({
2503
+ errorMessage: `Cannot proceed to next step: ${nextStepValidationResult.error || "Arguments validation failed"}`
2504
+ })
2505
+ }
2506
+ ],
2507
+ isError: true
2508
+ };
2509
+ }
2510
+ } else if (decision2 === "complete") {
2511
+ if (state.isAtLastStep() && state.isWorkflowStarted()) {
2512
+ state.markCompleted();
2513
+ return {
2514
+ content: [
2515
+ {
2516
+ type: "text",
2517
+ text: `## Workflow Completed!
2518
+
2519
+ ${this.formatProgress(state)}
2520
+
2521
+ ${CompiledPrompts.workflowCompleted({
2522
+ totalSteps: state.getSteps().length,
2523
+ toolName: this.name,
2524
+ newWorkflowInstructions: this.predefinedSteps ? "" : " and new `steps` array"
2525
+ })}`
2526
+ }
2527
+ ],
2528
+ isError: false
2529
+ };
2530
+ } else {
2531
+ return {
2532
+ content: [
2533
+ {
2534
+ type: "text",
2535
+ text: WorkflowPrompts.ERRORS.CANNOT_COMPLETE_NOT_AT_FINAL
2536
+ }
2537
+ ],
2538
+ isError: true
2539
+ };
2540
+ }
2541
+ }
2542
+ }
2543
+ const decision = args.decision;
2544
+ if (decision !== "proceed") {
2545
+ const validationSchema = this.createArgsDef.forCurrentState(state);
2546
+ const validationResult = this.validateInput(args, validationSchema);
2547
+ if (!validationResult.valid) {
2548
+ return {
2549
+ content: [
2550
+ {
2551
+ type: "text",
2552
+ text: CompiledPrompts.workflowErrorResponse({
2553
+ errorMessage: validationResult.error || "Arguments validation failed"
2554
+ })
2555
+ }
2556
+ ],
2557
+ isError: true
2558
+ };
2559
+ }
2560
+ }
2561
+ if (args.init) {
2562
+ return this.initialize(args, state);
2563
+ }
2564
+ return await this.executeStep(args, state);
2565
+ }
2566
+ initialize(args, state) {
2567
+ const steps = args.steps ?? this.predefinedSteps;
2568
+ if (!steps || steps.length === 0) {
2569
+ return {
2570
+ content: [
2571
+ {
2572
+ type: "text",
2573
+ text: WorkflowPrompts.ERRORS.NO_STEPS_PROVIDED
2574
+ }
2575
+ ],
2576
+ isError: true
2577
+ };
2578
+ }
2579
+ const validation = this.validateRequiredActions(steps);
2580
+ if (!validation.valid) {
2581
+ return {
2582
+ content: [
2583
+ {
2584
+ type: "text",
2585
+ text: `## Workflow Validation Failed \u274C
2586
+
2587
+ **Missing Required Actions:** The following actions must be included in the workflow steps:
2588
+
2589
+ ${validation.missing.map((action) => `- \`${this.toolNameToIdMapping?.get(action) ?? action}\``).join("\n")}`
2590
+ }
2591
+ ],
2592
+ isError: true
2593
+ };
2594
+ }
2595
+ state.initialize(steps);
2596
+ return {
2597
+ content: [
2598
+ {
2599
+ type: "text",
2600
+ text: `## Workflow Initialized
2601
+ ${this.formatProgress(state)}
2602
+ ${this.createArgsDef.forInitialStepDescription(steps, state)}`
2603
+ }
2604
+ ],
2605
+ isError: false
2606
+ };
2607
+ }
2608
+ async executeStep(args, state) {
2609
+ const currentStep = state.getCurrentStep();
2610
+ if (!currentStep) {
2611
+ return {
2612
+ content: [
2613
+ {
2614
+ type: "text",
2615
+ text: WorkflowPrompts.ERRORS.NO_CURRENT_STEP
2616
+ }
2617
+ ],
2618
+ isError: true
2619
+ };
2620
+ }
2621
+ state.markCurrentStepRunning();
2622
+ const results = {
2623
+ content: [],
2624
+ isError: false
2625
+ };
2626
+ for (const action of currentStep.actions) {
2627
+ try {
2628
+ const actionArgs = args[action] || {};
2629
+ const actionResult = await this.server.callTool(action, actionArgs);
2630
+ if (!results.isError) {
2631
+ results.isError = actionResult.isError;
2632
+ }
2633
+ results.content = results.content.concat(actionResult.content ?? []);
2634
+ results.content.push({
2635
+ type: "text",
2636
+ text: `Action \`${action}\` executed ${actionResult.isError ? "\u274C **FAILED**" : "\u2705 **SUCCESS**"}:`
2637
+ });
2638
+ } catch (error) {
2639
+ results.content.push({
2640
+ type: "text",
2641
+ text: `${error.message}`
2642
+ });
2643
+ results.content.push({
2644
+ type: "text",
2645
+ text: `Action \`${action}\` \u274C **FAILED** with error: `
2646
+ });
2647
+ results.isError = true;
2648
+ }
2649
+ }
2650
+ if (results.isError) {
2651
+ state.markCurrentStepFailed("Step execution failed");
2652
+ } else {
2653
+ state.markCurrentStepCompleted("Step completed successfully");
2654
+ }
2655
+ if (state.hasNextStep()) {
2656
+ const nextStepArgsDef = this.createArgsDef.forNextState(state);
2657
+ results.content.push({
2658
+ type: "text",
2659
+ text: CompiledPrompts.nextStepDecision({
2660
+ toolName: this.name,
2661
+ nextStepDescription: state.getNextStep()?.description || "Unknown step",
2662
+ nextStepSchema: JSON.stringify(nextStepArgsDef, null, 2)
2663
+ })
2664
+ });
2665
+ } else {
2666
+ results.content.push({
2667
+ type: "text",
2668
+ text: CompiledPrompts.finalStepCompletion({
2669
+ statusIcon: results.isError ? "\u274C" : "\u2705",
2670
+ statusText: results.isError ? "with errors" : "successfully",
2671
+ toolName: this.name,
2672
+ newWorkflowInstructions: this.predefinedSteps ? "" : " and new `steps` array"
2673
+ })
2674
+ });
2675
+ }
2676
+ results.content.push({
2677
+ type: "text",
2678
+ text: `## Workflow Progress
2679
+ ${this.formatProgress(state)}`
2680
+ });
2681
+ return results;
2682
+ }
2683
+ // Validate arguments using JSON schema
2684
+ validateInput(args, schema) {
2685
+ return validateSchema(args, schema);
2686
+ }
2687
+ };
2688
+
2689
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/workflow/workflow-tool-registrar.js
2690
+ function registerAgenticWorkflowTool(server, { description, name, allToolNames, depGroups, toolNameToDetailList, predefinedSteps, ensureStepActions, toolNameToIdMapping }) {
2691
+ const createArgsDef = createArgsDefFactory(name, allToolNames, depGroups, predefinedSteps, ensureStepActions);
2692
+ const workflowExecutor = new WorkflowExecutor(name, allToolNames, toolNameToDetailList, createArgsDef, server, predefinedSteps, ensureStepActions, toolNameToIdMapping);
2693
+ const workflowState = new WorkflowState();
2694
+ const planningInstructions = predefinedSteps ? "- Set `init: true` (steps are predefined)" : "- Set `init: true` and define complete `steps` array";
2695
+ const baseDescription = CompiledPrompts.workflowExecution({
2696
+ toolName: name,
2697
+ description,
2698
+ planningInstructions
2699
+ });
2700
+ const argsDef = createArgsDef.forTool();
2701
+ const toolDescription = createArgsDef.forToolDescription(baseDescription, workflowState);
2702
+ server.tool(name, toolDescription, jsonSchema(createModelCompatibleJSONSchema(argsDef)), async (args) => {
2703
+ try {
2704
+ return await workflowExecutor.execute(args, workflowState);
2705
+ } catch (error) {
2706
+ workflowState.reset();
2707
+ return {
2708
+ content: [
2709
+ {
2710
+ type: "text",
2711
+ text: `Workflow execution error: ${error.message}`
2712
+ }
2713
+ ],
2714
+ isError: true
2715
+ };
2716
+ }
2717
+ });
2718
+ }
2719
+
2720
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/mode-workflow-plugin.js
2721
+ var createWorkflowModePlugin = () => ({
2722
+ name: "mode-workflow",
2723
+ version: "1.0.0",
2724
+ // Only apply to workflow mode
2725
+ apply: "agentic_workflow",
2726
+ // Register the agent tool
2727
+ registerAgentTool: (context2) => {
2728
+ registerAgenticWorkflowTool(context2.server, {
2729
+ description: context2.description,
2730
+ name: context2.name,
2731
+ allToolNames: context2.allToolNames,
2732
+ depGroups: context2.depGroups,
2733
+ toolNameToDetailList: context2.toolNameToDetailList,
2734
+ predefinedSteps: context2.options.steps,
2735
+ ensureStepActions: context2.options.ensureStepActions,
2736
+ toolNameToIdMapping: context2.toolNameToIdMapping
2737
+ });
2738
+ }
2739
+ });
2740
+ var mode_workflow_plugin_default = createWorkflowModePlugin();
2741
+
2742
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/sampling/base-sampling-executor.js
2743
+ var import_node_process6 = __toESM(require("node:process"), 1);
2744
+ var BaseSamplingExecutor = class {
2745
+ name;
2746
+ description;
2747
+ allToolNames;
2748
+ toolNameToDetailList;
2749
+ server;
2750
+ conversationHistory;
2751
+ maxIterations;
2752
+ currentIteration;
2753
+ logger;
2754
+ tracingEnabled;
2755
+ summarize;
2756
+ constructor(name, description, allToolNames, toolNameToDetailList, server, config) {
2757
+ this.name = name;
2758
+ this.description = description;
2759
+ this.allToolNames = allToolNames;
2760
+ this.toolNameToDetailList = toolNameToDetailList;
2761
+ this.server = server;
2762
+ this.conversationHistory = [];
2763
+ this.maxIterations = 55;
2764
+ this.currentIteration = 0;
2765
+ this.tracingEnabled = false;
2766
+ this.summarize = true;
2767
+ if (config?.maxIterations) {
2768
+ this.maxIterations = config.maxIterations;
2769
+ }
2770
+ if (config?.summarize !== void 0) {
2771
+ this.summarize = config.summarize;
2772
+ }
2773
+ this.logger = createLogger(`mcpc.sampling.${name}`, server);
2774
+ try {
2775
+ const tracingConfig = {
2776
+ enabled: import_node_process6.default.env.MCPC_TRACING_ENABLED === "true",
2777
+ serviceName: `mcpc-sampling-${name}`,
2778
+ exportTo: import_node_process6.default.env.MCPC_TRACING_EXPORT ?? "otlp",
2779
+ otlpEndpoint: import_node_process6.default.env.MCPC_TRACING_OTLP_ENDPOINT ?? "http://localhost:4318/v1/traces"
2780
+ };
2781
+ this.tracingEnabled = tracingConfig.enabled;
2782
+ if (this.tracingEnabled) {
2783
+ initializeTracing(tracingConfig);
2784
+ }
2785
+ } catch {
2786
+ this.tracingEnabled = false;
2787
+ }
2788
+ }
2789
+ async runSamplingLoop(systemPrompt, schema, state) {
2790
+ this.conversationHistory = [
2791
+ {
2792
+ role: "user",
2793
+ content: {
2794
+ type: "text",
2795
+ text: 'Return ONE AND ONLY ONE raw JSON object (no code fences, explanations, or multiple objects). During execution provide: {"action":"<tool>","decision":"proceed|retry","<tool>":{}}. When complete provide: {"decision":"complete"}'
2796
+ }
2797
+ }
2798
+ ];
2799
+ const loopSpan = this.tracingEnabled ? startSpan("mcpc.sampling_loop", {
2800
+ agent: this.name,
2801
+ maxIterations: this.maxIterations,
2802
+ systemPrompt: systemPrompt()
2803
+ }) : null;
2804
+ try {
2805
+ for (this.currentIteration = 0; this.currentIteration < this.maxIterations; this.currentIteration++) {
2806
+ let iterationSpan = null;
2807
+ try {
2808
+ const response = await this.server.createMessage({
2809
+ systemPrompt: systemPrompt(),
2810
+ messages: this.conversationHistory,
2811
+ maxTokens: 55e3
2812
+ });
2813
+ const responseContent = response.content.text || "{}";
2814
+ const model = response.model;
2815
+ const stopReason = response.stopReason;
2816
+ const role = response.role;
2817
+ let parsedData;
2818
+ try {
2819
+ parsedData = parseJSON(responseContent.trim(), true);
2820
+ } catch (parseError) {
2821
+ iterationSpan = this.tracingEnabled ? startSpan("mcpc.sampling_iteration.parse_error", {
2822
+ iteration: this.currentIteration + 1,
2823
+ agent: this.name,
2824
+ error: String(parseError),
2825
+ maxIterations: this.maxIterations
2826
+ }, loopSpan ?? void 0) : null;
2827
+ this.addParsingErrorToHistory(responseContent, parseError);
2828
+ if (iterationSpan) endSpan(iterationSpan);
2829
+ continue;
2830
+ }
2831
+ this.conversationHistory.push({
2832
+ role: "assistant",
2833
+ content: {
2834
+ type: "text",
2835
+ text: JSON.stringify(parsedData, null, 2)
2836
+ }
2837
+ });
2838
+ const action = parsedData["action"];
2839
+ const decision = parsedData["decision"];
2840
+ if (typeof decision !== "string") {
2841
+ this.conversationHistory.push({
2842
+ role: "user",
2843
+ content: {
2844
+ type: "text",
2845
+ text: 'Missing required field "decision". Provide: {"action":"<tool>","decision":"proceed|retry","<tool>":{}} or {"decision":"complete"}'
2846
+ }
2847
+ });
2848
+ if (iterationSpan) endSpan(iterationSpan);
2849
+ continue;
2850
+ }
2851
+ if (decision === "complete" && action) {
2852
+ this.conversationHistory.push({
2853
+ role: "user",
2854
+ content: {
2855
+ type: "text",
2856
+ text: 'Invalid: Cannot have both "decision":"complete" and "action" field. When complete, only provide {"decision":"complete"}.'
2857
+ }
2858
+ });
2859
+ if (iterationSpan) endSpan(iterationSpan);
2860
+ continue;
2861
+ }
2862
+ if (decision !== "complete" && !action) {
2863
+ this.conversationHistory.push({
2864
+ role: "user",
2865
+ content: {
2866
+ type: "text",
2867
+ text: 'Missing required field "action". When executing, provide: {"action":"<tool>","decision":"proceed|retry","<tool>":{}}'
2868
+ }
2869
+ });
2870
+ if (iterationSpan) endSpan(iterationSpan);
2871
+ continue;
2872
+ }
2873
+ const actionStr = decision === "complete" ? "completion" : action && typeof action === "string" ? String(action) : "unknown_action";
2874
+ const spanName = `mcpc.sampling_iteration.${actionStr}`;
2875
+ iterationSpan = this.tracingEnabled ? startSpan(spanName, {
2876
+ iteration: this.currentIteration + 1,
2877
+ agent: this.name,
2878
+ action: actionStr,
2879
+ systemPrompt: systemPrompt(),
2880
+ maxTokens: String(Number.MAX_SAFE_INTEGER),
2881
+ maxIterations: this.maxIterations,
2882
+ messages: JSON.stringify(this.conversationHistory)
2883
+ }, loopSpan ?? void 0) : null;
2884
+ const result = await this.processAction(parsedData, schema, state, iterationSpan);
2885
+ this.logIterationProgress(parsedData, result, model, stopReason, role);
2886
+ if (iterationSpan) {
2887
+ let rawJson = "{}";
2888
+ try {
2889
+ rawJson = parsedData ? JSON.stringify(parsedData) : "{}";
2890
+ } catch {
2891
+ }
2892
+ const attr = {
2893
+ isError: !!result.isError,
2894
+ isComplete: !!result.isComplete,
2895
+ iteration: this.currentIteration + 1,
2896
+ maxIterations: this.maxIterations,
2897
+ parsed: rawJson,
2898
+ action: typeof action === "string" ? action : String(action),
2899
+ decision: typeof decision === "string" ? decision : String(decision),
2900
+ samplingResponse: responseContent,
2901
+ toolResult: JSON.stringify(result),
2902
+ model,
2903
+ role
2904
+ };
2905
+ if (stopReason) {
2906
+ attr.stopReason = stopReason;
2907
+ }
2908
+ iterationSpan.setAttributes(attr);
2909
+ }
2910
+ if (result.isError) {
2911
+ this.conversationHistory.push({
2912
+ role: "user",
2913
+ content: {
2914
+ type: "text",
2915
+ text: result.content[0].text
2916
+ }
2917
+ });
2918
+ if (iterationSpan) endSpan(iterationSpan);
2919
+ continue;
2920
+ }
2921
+ if (result.isComplete) {
2922
+ if (iterationSpan) endSpan(iterationSpan);
2923
+ if (loopSpan) endSpan(loopSpan);
2924
+ return result;
2925
+ }
2926
+ if (iterationSpan) endSpan(iterationSpan);
2927
+ } catch (iterError) {
2928
+ if (iterationSpan) endSpan(iterationSpan, iterError);
2929
+ throw iterError;
2930
+ }
2931
+ }
2932
+ if (loopSpan) endSpan(loopSpan);
2933
+ return await this.createMaxIterationsError(loopSpan);
2934
+ } catch (error) {
2935
+ if (loopSpan) endSpan(loopSpan, error);
2936
+ return await this.createExecutionError(error, loopSpan);
2937
+ }
2938
+ }
2939
+ addParsingErrorToHistory(_responseText, parseError) {
2940
+ const errorMsg = parseError instanceof Error ? parseError.message : String(parseError);
2941
+ this.conversationHistory.push({
2942
+ role: "user",
2943
+ content: {
2944
+ type: "text",
2945
+ text: `Invalid JSON: ${errorMsg}
2946
+
2947
+ Respond with valid JSON.`
2948
+ }
2949
+ });
2950
+ }
2951
+ async createMaxIterationsError(parentSpan) {
2952
+ const result = await this.createCompletionResult(`Reached max iterations (${this.maxIterations}). Try a more specific request.`, parentSpan);
2953
+ result.isError = true;
2954
+ result.isComplete = false;
2955
+ return result;
2956
+ }
2957
+ async createExecutionError(error, parentSpan) {
2958
+ const result = await this.createCompletionResult(`Execution error: ${error instanceof Error ? error.message : String(error)}`, parentSpan);
2959
+ result.isError = true;
2960
+ result.isComplete = false;
2961
+ return result;
2962
+ }
2963
+ async createCompletionResult(text, parentSpan) {
2964
+ const summary = this.summarize ? await this.summarizeConversation(parentSpan) : this.formatConversation();
2965
+ return {
2966
+ content: [
2967
+ {
2968
+ type: "text",
2969
+ text: `${text}
2970
+
2971
+ **Execution Summary:**
2972
+ - Iterations used: ${this.currentIteration + 1}/${this.maxIterations}
2973
+ - Agent: ${this.name}
2974
+ ${summary}`
2975
+ }
2976
+ ],
2977
+ isError: false,
2978
+ isComplete: true
2979
+ };
2980
+ }
2981
+ // Use LLM to create high-signal summary for parent agent
2982
+ async summarizeConversation(parentSpan) {
2983
+ if (this.conversationHistory.length === 0) {
2984
+ return "\n\n**No conversation history**";
2985
+ }
2986
+ if (this.conversationHistory.length <= 3) {
2987
+ return this.formatConversation();
2988
+ }
2989
+ const summarizeSpan = this.tracingEnabled ? startSpan("mcpc.sampling_summarize", {
2990
+ agent: this.name,
2991
+ messageCount: this.conversationHistory.length
2992
+ }, parentSpan ?? void 0) : null;
2993
+ try {
2994
+ this.logger.debug({
2995
+ message: "Starting conversation summarization",
2996
+ messageCount: this.conversationHistory.length
2997
+ });
2998
+ const history = this.conversationHistory.map((msg, i) => {
2999
+ const prefix = `[${i + 1}] ${msg.role.toUpperCase()}`;
3000
+ return `${prefix}:
3001
+ ${msg.content.text}`;
3002
+ }).join("\n\n---\n\n");
3003
+ const response = await this.server.createMessage({
3004
+ systemPrompt: `Summarize this agent execution:
3005
+
3006
+ Final Decision: (include complete JSON if present)
3007
+ Key Findings: (most important)
3008
+ Actions Taken: (high-level flow)
3009
+ Errors/Warnings: (if any)
3010
+
3011
+ ${history}`,
3012
+ messages: [
3013
+ {
3014
+ role: "user",
3015
+ content: {
3016
+ type: "text",
3017
+ text: "Please provide a concise summary."
3018
+ }
3019
+ }
3020
+ ],
3021
+ maxTokens: 3e3
3022
+ });
3023
+ const summary = "\n\n" + response.content.text;
3024
+ this.logger.debug({
3025
+ message: "Summarization completed",
3026
+ summaryLength: summary.length
3027
+ });
3028
+ if (summarizeSpan) {
3029
+ summarizeSpan.setAttributes({
3030
+ summaryLength: summary.length,
3031
+ summary,
3032
+ success: true
3033
+ });
3034
+ endSpan(summarizeSpan);
3035
+ }
3036
+ return summary;
3037
+ } catch (error) {
3038
+ this.logger.warning({
3039
+ message: "Summarization failed, falling back to full history",
3040
+ error: String(error)
3041
+ });
3042
+ if (summarizeSpan) {
3043
+ endSpan(summarizeSpan, error);
3044
+ }
3045
+ return this.formatConversation();
3046
+ }
3047
+ }
3048
+ // Format full conversation history (for debugging)
3049
+ formatConversation() {
3050
+ if (this.conversationHistory.length === 0) {
3051
+ return "\n\n**No conversation history**";
3052
+ }
3053
+ const messages = this.conversationHistory.map((msg, i) => {
3054
+ const header = `### Message ${i + 1}: ${msg.role}`;
3055
+ try {
3056
+ const parsed = JSON.parse(msg.content.text);
3057
+ if (JSON.stringify(parsed).length < 100) {
3058
+ return `${header}
3059
+ ${JSON.stringify(parsed)}`;
3060
+ }
3061
+ return `${header}
3062
+ \`\`\`json
3063
+ ${JSON.stringify(parsed, null, 2)}
3064
+ \`\`\``;
3065
+ } catch {
3066
+ return `${header}
3067
+ ${msg.content.text}`;
3068
+ }
3069
+ });
3070
+ return "\n\n**Conversation History:**\n" + messages.join("\n\n");
3071
+ }
3072
+ logIterationProgress(parsedData, result, model, stopReason, role) {
3073
+ this.logger.debug({
3074
+ iteration: `${this.currentIteration + 1}/${this.maxIterations}`,
3075
+ parsedData,
3076
+ isError: result.isError,
3077
+ isComplete: result.isComplete,
3078
+ model,
3079
+ stopReason,
3080
+ role,
3081
+ result
3082
+ });
3083
+ }
3084
+ injectJsonInstruction({ prompt, schema, schemaPrefix = "JSON schema:", schemaSuffix = `STRICT REQUIREMENTS:
3085
+ 1. Return ONE AND ONLY ONE raw JSON object that passes JSON.parse() - no markdown, code blocks, explanatory text, or multiple JSON objects
3086
+ 2. Include ALL required fields with correct data types and satisfy ALL schema constraints (anyOf, oneOf, allOf, not, enum, pattern, min/max, conditionals)
3087
+ 3. Your response must be a single JSON object, nothing else
3088
+
3089
+ INVALID: \`\`\`json{"key":"value"}\`\`\` or "Here is: {"key":"value"}" or {"key":"value"}{"key":"value"}
3090
+ VALID: {"key":"value"}` }) {
3091
+ return [
3092
+ prompt != null && prompt.length > 0 ? prompt : void 0,
3093
+ prompt != null && prompt.length > 0 ? "" : void 0,
3094
+ schemaPrefix,
3095
+ schema != null ? JSON.stringify(schema, null, 2) : void 0,
3096
+ schemaSuffix
3097
+ ].filter((line) => line != null).join("\n");
3098
+ }
3099
+ // Validate arguments using JSON schema
3100
+ validateInput(args, schema) {
3101
+ return validateSchema(args, schema);
3102
+ }
3103
+ };
3104
+
3105
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/sampling/agentic-sampling-executor.js
3106
+ var SamplingExecutor = class extends BaseSamplingExecutor {
3107
+ agenticExecutor;
3108
+ constructor(name, description, allToolNames, toolNameToDetailList, server, config) {
3109
+ super(name, description, allToolNames, toolNameToDetailList, server, config);
3110
+ this.agenticExecutor = new AgenticExecutor(name, allToolNames, toolNameToDetailList, server);
3111
+ }
3112
+ buildDepGroups() {
3113
+ const depGroups = {};
3114
+ this.toolNameToDetailList.forEach(([toolName, tool]) => {
3115
+ if (tool?.inputSchema) {
3116
+ depGroups[toolName] = {
3117
+ type: "object",
3118
+ description: tool.description || `Tool: ${toolName}`,
3119
+ ...tool.inputSchema
3120
+ };
3121
+ } else {
3122
+ const toolSchema = this.server.getHiddenToolSchema(toolName);
3123
+ if (toolSchema) {
3124
+ depGroups[toolName] = {
3125
+ ...toolSchema.schema,
3126
+ description: toolSchema.description
3127
+ };
3128
+ }
3129
+ }
3130
+ });
3131
+ return depGroups;
3132
+ }
3133
+ executeSampling(args, schema) {
3134
+ const validationResult = validateSchema(args, schema);
3135
+ if (!validationResult.valid) {
3136
+ return {
3137
+ content: [
3138
+ {
3139
+ type: "text",
3140
+ text: CompiledPrompts.errorResponse({
3141
+ errorMessage: validationResult.error || "Validation failed"
3142
+ })
3143
+ }
3144
+ ],
3145
+ isError: true
3146
+ };
3147
+ }
3148
+ const createArgsDef = createArgsDefFactory(this.name, this.allToolNames, this.buildDepGroups(), void 0, void 0);
3149
+ const agenticSchema = createArgsDef.forAgentic(this.toolNameToDetailList, true);
3150
+ const systemPrompt = this.buildSystemPrompt(args.userRequest, agenticSchema, args.context && typeof args.context === "object" ? args.context : void 0);
3151
+ return this.runSamplingLoop(() => systemPrompt, agenticSchema);
3152
+ }
3153
+ async processAction(parsedData, schema, _state, parentSpan) {
3154
+ const toolCallData = parsedData;
3155
+ if (toolCallData.decision === "complete") {
3156
+ return await this.createCompletionResult("Task completed", parentSpan);
3157
+ }
3158
+ try {
3159
+ const { action: _action, decision: _decision, ..._toolArgs } = toolCallData;
3160
+ const toolResult = await this.agenticExecutor.execute(toolCallData, schema, parentSpan);
3161
+ const resultText = toolResult.content?.filter((content) => content.type === "text")?.map((content) => content.text)?.join("\n") || "No result";
3162
+ this.conversationHistory.push({
3163
+ role: "assistant",
3164
+ content: {
3165
+ type: "text",
3166
+ text: resultText
3167
+ }
3168
+ });
3169
+ return toolResult;
3170
+ } catch (error) {
3171
+ return this.createExecutionError(error, parentSpan);
3172
+ }
3173
+ }
3174
+ buildSystemPrompt(userRequest, agenticSchema, context2) {
3175
+ const toolList = this.allToolNames.map((name) => {
3176
+ const tool = this.toolNameToDetailList.find(([toolName]) => toolName === name);
3177
+ const toolSchema = this.server.getHiddenToolSchema(name);
3178
+ if (tool && tool[1]) {
3179
+ return `- ${name}: ${tool[1].description || `Tool: ${name}`}`;
3180
+ } else if (toolSchema) {
3181
+ return `- ${name}: ${toolSchema.description}`;
3182
+ }
3183
+ return `- ${name}`;
3184
+ }).join("\n");
3185
+ let contextInfo = "";
3186
+ if (context2 && typeof context2 === "object" && Object.keys(context2).length > 0) {
3187
+ contextInfo = `
3188
+
3189
+ Context:
3190
+ ${JSON.stringify(context2, null, 2)}`;
3191
+ }
3192
+ const basePrompt = CompiledPrompts.samplingExecution({
3193
+ toolName: this.name,
3194
+ description: this.description,
3195
+ toolList
3196
+ });
3197
+ const taskPrompt = `
3198
+
3199
+ ## Current Task
3200
+ You will now use agentic sampling to complete the following task: "${userRequest}"${contextInfo}
3201
+
3202
+ When you need to use a tool, specify the tool name in 'action' and provide tool-specific parameters as additional properties.`;
3203
+ return this.injectJsonInstruction({
3204
+ prompt: basePrompt + taskPrompt,
3205
+ schema: agenticSchema
3206
+ });
3207
+ }
3208
+ };
3209
+
3210
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/agentic/agentic-sampling-registrar.js
3211
+ function registerAgenticSamplingTool(server, { description, name, allToolNames, depGroups, toolNameToDetailList, samplingConfig }) {
3212
+ const createArgsDef = createArgsDefFactory(name, allToolNames, depGroups, void 0, void 0);
3213
+ const samplingExecutor = new SamplingExecutor(name, description, allToolNames, toolNameToDetailList, server, samplingConfig);
3214
+ description = CompiledPrompts.samplingExecution({
3215
+ toolName: name,
3216
+ description,
3217
+ toolList: allToolNames.map((name2) => `- ${name2}`).join("\n")
3218
+ });
3219
+ const argsDef = createArgsDef.forSampling();
3220
+ const schema = allToolNames.length > 0 ? argsDef : {
3221
+ type: "object",
3222
+ properties: {}
3223
+ };
3224
+ server.tool(name, description, jsonSchema(createModelCompatibleJSONSchema(schema)), async (args) => {
3225
+ return await samplingExecutor.executeSampling(args, schema);
3226
+ });
3227
+ }
3228
+
3229
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/mode-agentic-sampling-plugin.js
3230
+ var createAgenticSamplingModePlugin = () => ({
3231
+ name: "mode-agentic-sampling",
3232
+ version: "1.0.0",
3233
+ // Only apply to agentic_sampling mode
3234
+ apply: "agentic_sampling",
3235
+ // Register the agent tool with sampling
3236
+ registerAgentTool: (context2) => {
3237
+ registerAgenticSamplingTool(context2.server, {
3238
+ description: context2.description,
3239
+ name: context2.name,
3240
+ allToolNames: context2.allToolNames,
3241
+ depGroups: context2.depGroups,
3242
+ toolNameToDetailList: context2.toolNameToDetailList,
3243
+ samplingConfig: context2.options.samplingConfig
3244
+ });
3245
+ }
3246
+ });
3247
+ var mode_agentic_sampling_plugin_default = createAgenticSamplingModePlugin();
3248
+
3249
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/sampling/workflow-sampling-executor.js
3250
+ var WorkflowSamplingExecutor = class extends BaseSamplingExecutor {
3251
+ createArgsDef;
3252
+ predefinedSteps;
3253
+ workflowExecutor;
3254
+ constructor(name, description, allToolNames, toolNameToDetailList, createArgsDef, server, predefinedSteps, config) {
3255
+ super(name, description, allToolNames, toolNameToDetailList, server, config), this.createArgsDef = createArgsDef, this.predefinedSteps = predefinedSteps;
3256
+ this.workflowExecutor = new WorkflowExecutor(name, allToolNames, toolNameToDetailList, createArgsDef, server, predefinedSteps);
3257
+ }
3258
+ async executeWorkflowSampling(args, schema, state) {
3259
+ const validationResult = validateSchema(args, schema);
3260
+ if (!validationResult.valid) {
3261
+ return {
3262
+ content: [
3263
+ {
3264
+ type: "text",
3265
+ text: CompiledPrompts.workflowErrorResponse({
3266
+ errorMessage: validationResult.error || "Validation failed"
3267
+ })
3268
+ }
3269
+ ],
3270
+ isError: true
3271
+ };
3272
+ }
3273
+ return await this.runSamplingLoop(() => this.buildWorkflowSystemPrompt(args, state), schema, state);
3274
+ }
3275
+ async processAction(parsedData, _schema, state, parentSpan) {
3276
+ const workflowState = state;
3277
+ if (!workflowState) {
3278
+ throw new Error("WorkflowState is required for workflow");
3279
+ }
3280
+ const toolCallData = parsedData;
3281
+ if (toolCallData.decision === "complete") {
3282
+ return await this.createCompletionResult("Task completed", parentSpan);
3283
+ }
3284
+ try {
3285
+ const workflowResult = await this.workflowExecutor.execute(parsedData, workflowState);
3286
+ const resultText = workflowResult.content?.filter((content) => content.type === "text")?.map((content) => content.text)?.join("\n") || "No result";
3287
+ this.conversationHistory.push({
3288
+ role: "assistant",
3289
+ content: {
3290
+ type: "text",
3291
+ text: resultText
3292
+ }
3293
+ });
3294
+ return workflowResult;
3295
+ } catch (error) {
3296
+ return this.createExecutionError(error, parentSpan);
3297
+ }
3298
+ }
3299
+ buildWorkflowSystemPrompt(args, state) {
3300
+ const workflowSchema = this.createArgsDef.forCurrentState(state);
3301
+ const basePrompt = CompiledPrompts.samplingWorkflowExecution({
3302
+ toolName: this.name,
3303
+ description: this.description,
3304
+ workflowSchema: `${JSON.stringify(workflowSchema, null, 2)}`
3305
+ });
3306
+ let contextInfo = "";
3307
+ if (args.context && typeof args.context === "object" && Object.keys(args.context).length > 0) {
3308
+ contextInfo = `
3309
+
3310
+ Context:
3311
+ ${JSON.stringify(args.context, null, 2)}`;
3312
+ }
3313
+ const workflowPrompt = `
3314
+
3315
+ Current Task: <user_request>${args.userRequest}</user_request>${contextInfo}`;
3316
+ return this.injectJsonInstruction({
3317
+ prompt: basePrompt + workflowPrompt,
3318
+ schema: workflowSchema
3319
+ });
3320
+ }
3321
+ };
3322
+
3323
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/executors/workflow/workflow-sampling-registrar.js
3324
+ function registerWorkflowSamplingTool(server, { description, name, allToolNames, depGroups, toolNameToDetailList, predefinedSteps, samplingConfig, ensureStepActions, toolNameToIdMapping: _toolNameToIdMapping }) {
3325
+ const createArgsDef = createArgsDefFactory(name, allToolNames, depGroups, predefinedSteps, ensureStepActions);
3326
+ const workflowSamplingExecutor = new WorkflowSamplingExecutor(name, description, allToolNames, toolNameToDetailList, createArgsDef, server, predefinedSteps, samplingConfig);
3327
+ const workflowState = new WorkflowState();
3328
+ const baseDescription = CompiledPrompts.samplingExecution({
3329
+ toolName: name,
3330
+ description,
3331
+ toolList: allToolNames.map((name2) => `- ${name2}`).join("\n")
3332
+ });
3333
+ const argsDef = createArgsDef.forSampling();
3334
+ const schema = allToolNames.length > 0 ? argsDef : {
3335
+ type: "object",
3336
+ properties: {}
3337
+ };
3338
+ server.tool(name, baseDescription, jsonSchema(createModelCompatibleJSONSchema(schema)), async (args) => {
3339
+ try {
3340
+ return await workflowSamplingExecutor.executeWorkflowSampling(args, schema, workflowState);
3341
+ } catch (error) {
3342
+ workflowState.reset();
3343
+ return {
3344
+ content: [
3345
+ {
3346
+ type: "text",
3347
+ text: `Workflow execution error: ${error.message}`
3348
+ }
3349
+ ],
3350
+ isError: true
3351
+ };
3352
+ }
3353
+ });
3354
+ }
3355
+
3356
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/mode-workflow-sampling-plugin.js
3357
+ var createWorkflowSamplingModePlugin = () => ({
3358
+ name: "mode-agentic-workflow-sampling",
3359
+ version: "1.0.0",
3360
+ // Only apply to agentic_workflow_sampling mode
3361
+ apply: "agentic_workflow_sampling",
3362
+ // Register the agent tool with sampling
3363
+ registerAgentTool: (context2) => {
3364
+ registerWorkflowSamplingTool(context2.server, {
3365
+ description: context2.description,
3366
+ name: context2.name,
3367
+ allToolNames: context2.allToolNames,
3368
+ depGroups: context2.depGroups,
3369
+ toolNameToDetailList: context2.toolNameToDetailList,
3370
+ predefinedSteps: context2.options.steps,
3371
+ samplingConfig: context2.options.samplingConfig,
3372
+ ensureStepActions: context2.options.ensureStepActions,
3373
+ toolNameToIdMapping: context2.toolNameToIdMapping
3374
+ });
3375
+ }
3376
+ });
3377
+ var mode_workflow_sampling_plugin_default = createWorkflowSamplingModePlugin();
3378
+
3379
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/built-in/index.js
3380
+ function getBuiltInPlugins() {
3381
+ return [
3382
+ tool_name_mapping_plugin_default,
3383
+ config_plugin_default,
3384
+ mode_agentic_plugin_default,
3385
+ mode_workflow_plugin_default,
3386
+ mode_agentic_sampling_plugin_default,
3387
+ mode_workflow_sampling_plugin_default,
3388
+ logging_plugin_default
3389
+ ];
3390
+ }
3391
+
3392
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugin-utils.js
3393
+ var import_meta = {};
3394
+ var pluginCache = /* @__PURE__ */ new Map();
3395
+ function shouldApplyPlugin(plugin, mode) {
3396
+ if (!plugin.apply) return true;
3397
+ if (typeof plugin.apply === "string") {
3398
+ return mode === plugin.apply;
3399
+ }
3400
+ if (typeof plugin.apply === "function") {
3401
+ try {
3402
+ return plugin.apply(mode);
3403
+ } catch (error) {
3404
+ console.warn(`Plugin "${plugin.name}" apply function failed: ${error}. Defaulting to true.`);
3405
+ return true;
3406
+ }
3407
+ }
3408
+ return true;
3409
+ }
3410
+ function sortPluginsByOrder(plugins) {
3411
+ const pluginMap = /* @__PURE__ */ new Map();
3412
+ for (const plugin of plugins) {
3413
+ pluginMap.set(plugin.name, plugin);
3414
+ }
3415
+ const visited = /* @__PURE__ */ new Set();
3416
+ const sorted = [];
3417
+ function visit(plugin) {
3418
+ if (visited.has(plugin.name)) return;
3419
+ visited.add(plugin.name);
3420
+ if (plugin.dependencies) {
3421
+ for (const depName of plugin.dependencies) {
3422
+ const dep = pluginMap.get(depName);
3423
+ if (dep) {
3424
+ visit(dep);
3425
+ } else {
3426
+ console.warn(`Plugin "${plugin.name}" depends on "${depName}" which is not loaded`);
3427
+ }
3428
+ }
3429
+ }
3430
+ sorted.push(plugin);
3431
+ }
3432
+ const prePlugins = plugins.filter((p2) => p2.enforce === "pre");
3433
+ const normalPlugins = plugins.filter((p2) => !p2.enforce);
3434
+ const postPlugins = plugins.filter((p2) => p2.enforce === "post");
3435
+ [
3436
+ ...prePlugins,
3437
+ ...normalPlugins,
3438
+ ...postPlugins
3439
+ ].forEach(visit);
3440
+ return sorted;
3441
+ }
3442
+ function isValidPlugin(plugin) {
3443
+ if (!plugin || typeof plugin !== "object") return false;
3444
+ const p2 = plugin;
3445
+ if (!p2.name || typeof p2.name !== "string" || p2.name.trim() === "") {
3446
+ return false;
3447
+ }
3448
+ const hasHook = typeof p2.configureServer === "function" || typeof p2.composeStart === "function" || typeof p2.transformTool === "function" || typeof p2.finalizeComposition === "function" || typeof p2.registerAgentTool === "function" || typeof p2.composeEnd === "function" || typeof p2.transformInput === "function" || typeof p2.transformOutput === "function" || typeof p2.dispose === "function";
3449
+ if (!hasHook) return false;
3450
+ if (p2.enforce && p2.enforce !== "pre" && p2.enforce !== "post") {
3451
+ return false;
3452
+ }
3453
+ if (p2.apply && typeof p2.apply !== "string" && typeof p2.apply !== "function") {
3454
+ return false;
3455
+ }
3456
+ if (p2.dependencies && !Array.isArray(p2.dependencies)) {
3457
+ return false;
3458
+ }
3459
+ return true;
3460
+ }
3461
+ function parseQueryParams(params) {
3462
+ const typedParams = {};
3463
+ for (const [key, value] of Object.entries(params)) {
3464
+ const numValue = Number(value);
3465
+ if (!isNaN(numValue) && value.trim() !== "") {
3466
+ typedParams[key] = numValue;
3467
+ continue;
3468
+ }
3469
+ if (value === "true") {
3470
+ typedParams[key] = true;
3471
+ continue;
3472
+ }
3473
+ if (value === "false") {
3474
+ typedParams[key] = false;
3475
+ continue;
3476
+ }
3477
+ if (value.includes(",")) {
3478
+ typedParams[key] = value.split(",").map((v) => v.trim());
3479
+ continue;
3480
+ }
3481
+ typedParams[key] = value;
3482
+ }
3483
+ return typedParams;
3484
+ }
3485
+ async function loadPlugin(pluginPath, options = {
3486
+ cache: true
3487
+ }) {
3488
+ if (options.cache && pluginCache.has(pluginPath)) {
3489
+ return pluginCache.get(pluginPath);
3490
+ }
3491
+ try {
3492
+ const [rawPath, queryString] = pluginPath.split("?", 2);
3493
+ const searchParams = new URLSearchParams(queryString || "");
3494
+ const params = Object.fromEntries(searchParams.entries());
3495
+ const resolveFn = import_meta.resolve;
3496
+ const importPath = typeof resolveFn === "function" ? resolveFn(rawPath) : new URL(rawPath, import_meta.url).href;
3497
+ const pluginModule = await import(importPath);
3498
+ const pluginFactory = pluginModule.createPlugin;
3499
+ const defaultPlugin = pluginModule.default;
3500
+ let plugin;
3501
+ if (Object.keys(params).length > 0) {
3502
+ if (typeof pluginFactory !== "function") {
3503
+ throw new Error(`Plugin "${rawPath}" has parameters but no createPlugin export function`);
3504
+ }
3505
+ const typedParams = parseQueryParams(params);
3506
+ plugin = pluginFactory(typedParams);
3507
+ } else {
3508
+ if (defaultPlugin) {
3509
+ plugin = defaultPlugin;
3510
+ } else if (typeof pluginFactory === "function") {
3511
+ plugin = pluginFactory();
3512
+ } else {
3513
+ throw new Error(`Plugin "${rawPath}" has no default export or createPlugin function`);
3514
+ }
3515
+ }
3516
+ if (!isValidPlugin(plugin)) {
3517
+ throw new Error(`Invalid plugin format in "${rawPath}": must have a unique name and at least one lifecycle hook`);
3518
+ }
3519
+ if (options.cache) {
3520
+ pluginCache.set(pluginPath, plugin);
3521
+ }
3522
+ return plugin;
3523
+ } catch (error) {
3524
+ const errorMsg = error instanceof Error ? error.message : String(error);
3525
+ throw new Error(`Failed to load plugin from "${pluginPath}": ${errorMsg}`);
3526
+ }
3527
+ }
3528
+ function checkCircularDependencies(plugins) {
3529
+ const errors = [];
3530
+ const pluginMap = /* @__PURE__ */ new Map();
3531
+ for (const plugin of plugins) {
3532
+ pluginMap.set(plugin.name, plugin);
3533
+ }
3534
+ function checkCircular(pluginName, visited, path) {
3535
+ if (visited.has(pluginName)) {
3536
+ const cycle = [
3537
+ ...path,
3538
+ pluginName
3539
+ ].join(" -> ");
3540
+ errors.push(`Circular dependency detected: ${cycle}`);
3541
+ return;
3542
+ }
3543
+ const plugin = pluginMap.get(pluginName);
3544
+ if (!plugin || !plugin.dependencies) return;
3545
+ visited.add(pluginName);
3546
+ path.push(pluginName);
3547
+ for (const dep of plugin.dependencies) {
3548
+ checkCircular(dep, new Set(visited), [
3549
+ ...path
3550
+ ]);
3551
+ }
3552
+ }
3553
+ for (const plugin of plugins) {
3554
+ checkCircular(plugin.name, /* @__PURE__ */ new Set(), []);
3555
+ }
3556
+ return errors;
3557
+ }
3558
+ function validatePlugins(plugins) {
3559
+ const errors = [];
3560
+ const names = /* @__PURE__ */ new Map();
3561
+ for (const plugin of plugins) {
3562
+ const count = names.get(plugin.name) || 0;
3563
+ names.set(plugin.name, count + 1);
3564
+ }
3565
+ for (const [name, count] of names.entries()) {
3566
+ if (count > 1) {
3567
+ errors.push(`Duplicate plugin name: "${name}" (${count} instances)`);
3568
+ }
3569
+ }
3570
+ const circularErrors = checkCircularDependencies(plugins);
3571
+ errors.push(...circularErrors);
3572
+ for (const plugin of plugins) {
3573
+ if (!isValidPlugin(plugin)) {
3574
+ const name = plugin.name || "unknown";
3575
+ errors.push(`Invalid plugin: "${name}"`);
3576
+ }
3577
+ }
3578
+ return {
3579
+ valid: errors.length === 0,
3580
+ errors
3581
+ };
3582
+ }
3583
+
3584
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/plugin-manager.js
3585
+ var PluginManager = class {
3586
+ server;
3587
+ plugins;
3588
+ logger;
3589
+ constructor(server) {
3590
+ this.server = server;
3591
+ this.plugins = [];
3592
+ this.logger = createLogger("mcpc.plugin-manager");
3593
+ this.logger.setServer(server);
3594
+ }
3595
+ /**
3596
+ * Get all registered plugins
3597
+ */
3598
+ getPlugins() {
3599
+ return [
3600
+ ...this.plugins
3601
+ ];
3602
+ }
3603
+ /**
3604
+ * Get plugin names
3605
+ */
3606
+ getPluginNames() {
3607
+ return this.plugins.map((p2) => p2.name);
3608
+ }
3609
+ /**
3610
+ * Check if a plugin is registered
3611
+ */
3612
+ hasPlugin(name) {
3613
+ return this.plugins.some((p2) => p2.name === name);
3614
+ }
3615
+ /**
3616
+ * Add a plugin with validation and error handling
3617
+ */
3618
+ async addPlugin(plugin) {
3619
+ const validation = validatePlugins([
3620
+ plugin
3621
+ ]);
3622
+ if (!validation.valid) {
3623
+ const errorMsg = validation.errors.join(", ");
3624
+ throw new Error(`Invalid plugin "${plugin.name}": ${errorMsg}`);
3625
+ }
3626
+ if (this.plugins.some((p2) => p2.name === plugin.name)) {
3627
+ await this.logger.warning(`Plugin "${plugin.name}" already registered, skipping`);
3628
+ return;
3629
+ }
3630
+ if (plugin.dependencies) {
3631
+ const missingDeps = plugin.dependencies.filter((dep) => !this.plugins.some((p2) => p2.name === dep));
3632
+ if (missingDeps.length > 0) {
3633
+ throw new Error(`Plugin "${plugin.name}" has missing dependencies: ${missingDeps.join(", ")}`);
3634
+ }
3635
+ }
3636
+ this.plugins.push(plugin);
3637
+ if (plugin.configureServer) {
3638
+ try {
3639
+ await plugin.configureServer(this.server);
3640
+ } catch (error) {
3641
+ this.plugins = this.plugins.filter((p2) => p2.name !== plugin.name);
3642
+ const errorMsg = error instanceof Error ? error.message : String(error);
3643
+ throw new Error(`Plugin "${plugin.name}" configuration failed: ${errorMsg}`);
3644
+ }
3645
+ }
3646
+ }
3647
+ /**
3648
+ * Load and register a plugin from a file path
3649
+ */
3650
+ async loadPluginFromPath(pluginPath, options = {
3651
+ cache: true
3652
+ }) {
3653
+ const plugin = await loadPlugin(pluginPath, options);
3654
+ await this.addPlugin(plugin);
3655
+ }
3656
+ /**
3657
+ * Trigger composeStart hooks for all applicable plugins
3658
+ */
3659
+ async triggerComposeStart(context2) {
3660
+ const startPlugins = this.plugins.filter((p2) => p2.composeStart && shouldApplyPlugin(p2, context2.mode));
3661
+ const sortedPlugins = sortPluginsByOrder(startPlugins);
3662
+ for (const plugin of sortedPlugins) {
3663
+ if (plugin.composeStart) {
3664
+ try {
3665
+ await plugin.composeStart(context2);
3666
+ } catch (error) {
3667
+ const errorMsg = error instanceof Error ? error.message : String(error);
3668
+ await this.logger.error(`Plugin "${plugin.name}" composeStart failed: ${errorMsg}`);
3669
+ }
3670
+ }
3671
+ }
3672
+ }
3673
+ /**
3674
+ * Apply transformTool hooks to a tool during composition
3675
+ */
3676
+ async applyTransformToolHooks(tool, context2) {
3677
+ const transformPlugins = this.plugins.filter((p2) => p2.transformTool && shouldApplyPlugin(p2, context2.mode));
3678
+ if (transformPlugins.length === 0) {
3679
+ return tool;
3680
+ }
3681
+ const sortedPlugins = sortPluginsByOrder(transformPlugins);
3682
+ let currentTool = tool;
3683
+ for (const plugin of sortedPlugins) {
3684
+ if (plugin.transformTool) {
3685
+ try {
3686
+ const result = await plugin.transformTool(currentTool, context2);
3687
+ if (result) {
3688
+ currentTool = result;
3689
+ }
3690
+ } catch (error) {
3691
+ const errorMsg = error instanceof Error ? error.message : String(error);
3692
+ await this.logger.error(`Plugin "${plugin.name}" transformTool failed for "${context2.toolName}": ${errorMsg}`);
3693
+ }
3694
+ }
3695
+ }
3696
+ return currentTool;
3697
+ }
3698
+ /**
3699
+ * Trigger finalizeComposition hooks for all applicable plugins
3700
+ */
3701
+ async triggerFinalizeComposition(tools, context2) {
3702
+ const finalizePlugins = this.plugins.filter((p2) => p2.finalizeComposition && shouldApplyPlugin(p2, context2.mode));
3703
+ const sortedPlugins = sortPluginsByOrder(finalizePlugins);
3704
+ for (const plugin of sortedPlugins) {
3705
+ if (plugin.finalizeComposition) {
3706
+ try {
3707
+ await plugin.finalizeComposition(tools, context2);
3708
+ } catch (error) {
3709
+ const errorMsg = error instanceof Error ? error.message : String(error);
3710
+ await this.logger.error(`Plugin "${plugin.name}" finalizeComposition failed: ${errorMsg}`);
3711
+ }
3712
+ }
3713
+ }
3714
+ }
3715
+ /**
3716
+ * Trigger composeEnd hooks for all applicable plugins
3717
+ */
3718
+ async triggerComposeEnd(context2) {
3719
+ const endPlugins = this.plugins.filter((p2) => p2.composeEnd && shouldApplyPlugin(p2, context2.mode));
3720
+ const sortedPlugins = sortPluginsByOrder(endPlugins);
3721
+ for (const plugin of sortedPlugins) {
3722
+ if (plugin.composeEnd) {
3723
+ try {
3724
+ await plugin.composeEnd(context2);
3725
+ } catch (error) {
3726
+ const errorMsg = error instanceof Error ? error.message : String(error);
3727
+ await this.logger.error(`Plugin "${plugin.name}" composeEnd failed: ${errorMsg}`);
3728
+ }
3729
+ }
3730
+ }
3731
+ }
3732
+ /**
3733
+ * Trigger registerAgentTool hook - allows plugins to register the main agent tool
3734
+ * Returns true if any plugin handled the registration
3735
+ */
3736
+ async triggerRegisterAgentTool(context2) {
3737
+ const registerPlugins = this.plugins.filter((p2) => p2.registerAgentTool && shouldApplyPlugin(p2, context2.mode));
3738
+ if (registerPlugins.length === 0) {
3739
+ return false;
3740
+ }
3741
+ const sortedPlugins = sortPluginsByOrder(registerPlugins).reverse();
3742
+ for (const plugin of sortedPlugins) {
3743
+ if (plugin.registerAgentTool) {
3744
+ try {
3745
+ await plugin.registerAgentTool(context2);
3746
+ return true;
3747
+ } catch (error) {
3748
+ const errorMsg = error instanceof Error ? error.message : String(error);
3749
+ await this.logger.error(`Plugin "${plugin.name}" registerAgentTool failed: ${errorMsg}`);
3750
+ }
3751
+ }
3752
+ }
3753
+ return false;
3754
+ }
3755
+ /**
3756
+ * Dispose all plugins and cleanup resources
3757
+ */
3758
+ async dispose() {
3759
+ for (const plugin of this.plugins) {
3760
+ if (plugin.dispose) {
3761
+ try {
3762
+ await plugin.dispose();
3763
+ } catch (error) {
3764
+ const errorMsg = error instanceof Error ? error.message : String(error);
3765
+ await this.logger.error(`Plugin "${plugin.name}" dispose failed: ${errorMsg}`);
3766
+ }
3767
+ }
3768
+ }
3769
+ this.plugins = [];
3770
+ }
3771
+ };
3772
+
3773
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/tool-manager.js
3774
+ var ToolManager = class {
3775
+ toolRegistry = /* @__PURE__ */ new Map();
3776
+ toolConfigs = /* @__PURE__ */ new Map();
3777
+ toolNameMapping = /* @__PURE__ */ new Map();
3778
+ publicTools = [];
3779
+ /**
3780
+ * Get tool name mapping (for external access)
3781
+ */
3782
+ getToolNameMapping() {
3783
+ return this.toolNameMapping;
3784
+ }
3785
+ /**
3786
+ * Register a tool in the registry
3787
+ */
3788
+ registerTool(name, description, schema, callback, options = {}) {
3789
+ this.toolRegistry.set(name, {
3790
+ callback,
3791
+ description,
3792
+ schema
3793
+ });
3794
+ if (options.internal) {
3795
+ this.toolConfigs.set(name, {
3796
+ visibility: {
3797
+ hidden: true
3798
+ }
3799
+ });
3800
+ }
3801
+ }
3802
+ /**
3803
+ * Explicitly mark a tool as public (exposed to MCP clients)
3804
+ */
3805
+ addPublicTool(name, description, schema) {
3806
+ const existingTool = this.publicTools.find((t) => t.name === name);
3807
+ if (!existingTool) {
3808
+ this.publicTools.push({
3809
+ name,
3810
+ description,
3811
+ inputSchema: schema
3812
+ });
3813
+ }
3814
+ }
3815
+ /**
3816
+ * Check if a tool is public (exposed to MCP clients)
3817
+ */
3818
+ isPublic(name) {
3819
+ const config = this.toolConfigs.get(name);
3820
+ return config?.visibility?.public === true;
3821
+ }
3822
+ /**
3823
+ * Check if a tool is hidden from agent context
3824
+ */
3825
+ isHidden(name) {
3826
+ const config = this.toolConfigs.get(name);
3827
+ return config?.visibility?.hidden === true;
3828
+ }
3829
+ /**
3830
+ * Get all public tool names (exposed to MCP clients)
3831
+ */
3832
+ getPublicToolNames() {
3833
+ return Array.from(this.toolConfigs.entries()).filter(([_name, config]) => config.visibility?.public === true).map(([name]) => this.resolveToolName(name) ?? name);
3834
+ }
3835
+ /**
3836
+ * Get all hidden tool names
3837
+ */
3838
+ getHiddenToolNames() {
3839
+ return Array.from(this.toolConfigs.entries()).filter(([_name, config]) => config.visibility?.hidden === true).map(([name]) => this.resolveToolName(name) ?? name);
3840
+ }
3841
+ /**
3842
+ * Get all public tools
3843
+ */
3844
+ getPublicTools() {
3845
+ return [
3846
+ ...this.publicTools
3847
+ ];
3848
+ }
3849
+ /**
3850
+ * Set public tools list
3851
+ */
3852
+ setPublicTools(tools) {
3853
+ this.publicTools = [
3854
+ ...tools
3855
+ ];
3856
+ }
3857
+ /**
3858
+ * Get tool callback by name
3859
+ */
3860
+ getToolCallback(name) {
3861
+ return this.toolRegistry.get(name)?.callback;
3862
+ }
3863
+ /**
3864
+ * Check if tool exists in registry
3865
+ */
3866
+ hasToolNamed(name) {
3867
+ return this.toolRegistry.has(name) || this.toolNameMapping.has(name) && this.toolRegistry.has(this.toolNameMapping.get(name));
3868
+ }
3869
+ /**
3870
+ * Resolve a tool name to its internal format
3871
+ */
3872
+ resolveToolName(name) {
3873
+ if (this.toolRegistry.has(name)) {
3874
+ return name;
3875
+ }
3876
+ const mappedName = this.toolNameMapping.get(name);
3877
+ if (mappedName && this.toolRegistry.has(mappedName)) {
3878
+ return mappedName;
3879
+ }
3880
+ if (this.toolConfigs.has(name)) {
3881
+ const cfgMapped = this.toolNameMapping.get(name);
3882
+ if (cfgMapped && this.toolRegistry.has(cfgMapped)) {
3883
+ return cfgMapped;
3884
+ }
3885
+ }
3886
+ return void 0;
3887
+ }
3888
+ /**
3889
+ * Configure tool behavior
3890
+ */
3891
+ configTool(toolName, config) {
3892
+ this.toolConfigs.set(toolName, config);
3893
+ }
3894
+ /**
3895
+ * Get tool configuration
3896
+ */
3897
+ getToolConfig(toolName) {
3898
+ return this.toolConfigs.get(toolName);
3899
+ }
3900
+ /**
3901
+ * Find tool configuration (with mapping fallback)
3902
+ */
3903
+ findToolConfig(toolId) {
3904
+ const directConfig = this.toolConfigs.get(toolId);
3905
+ if (directConfig) {
3906
+ return directConfig;
3907
+ }
3908
+ const mappedName = this.toolNameMapping.get(toolId);
3909
+ if (mappedName && this.toolConfigs.has(mappedName)) {
3910
+ return this.toolConfigs.get(mappedName);
3911
+ }
3912
+ return void 0;
3913
+ }
3914
+ /**
3915
+ * Remove tool configuration
3916
+ */
3917
+ removeToolConfig(toolName) {
3918
+ return this.toolConfigs.delete(toolName);
3919
+ }
3920
+ /**
3921
+ * Set tool name mapping
3922
+ */
3923
+ setToolNameMapping(from, to) {
3924
+ this.toolNameMapping.set(from, to);
3925
+ }
3926
+ /**
3927
+ * Get tool schema if it's hidden (for internal access)
3928
+ */
3929
+ getHiddenToolSchema(name) {
3930
+ const tool = this.toolRegistry.get(name);
3931
+ const config = this.toolConfigs.get(name);
3932
+ if (tool && config?.visibility?.hidden && tool.schema) {
3933
+ return {
3934
+ description: tool.description,
3935
+ schema: tool.schema
3936
+ };
3937
+ }
3938
+ return void 0;
3939
+ }
3940
+ /**
3941
+ * Get total tool count
3942
+ */
3943
+ getTotalToolCount() {
3944
+ return this.toolRegistry.size;
3945
+ }
3946
+ /**
3947
+ * Get all tool entries
3948
+ */
3949
+ getToolEntries() {
3950
+ return Array.from(this.toolRegistry.entries());
3951
+ }
3952
+ /**
3953
+ * Get tool registry (for external access)
3954
+ */
3955
+ getToolRegistry() {
3956
+ return this.toolRegistry;
3957
+ }
3958
+ /**
3959
+ * Get all registered tools as ComposedTool objects
3960
+ * This includes tools registered via server.tool() in setup hooks
3961
+ */
3962
+ getRegisteredToolsAsComposed() {
3963
+ const composedTools = {};
3964
+ for (const [name, tool] of this.toolRegistry.entries()) {
3965
+ if (this.toolConfigs.get(name)?.visibility?.public === true) {
3966
+ continue;
3967
+ }
3968
+ composedTools[name] = {
3969
+ name,
3970
+ description: tool.description,
3971
+ inputSchema: jsonSchema(tool.schema || {
3972
+ type: "object",
3973
+ properties: {}
3974
+ }),
3975
+ execute: tool.callback
3976
+ };
3977
+ }
3978
+ return composedTools;
3979
+ }
3980
+ };
3981
+
3982
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/schema.js
3983
+ var import_json_schema_traverse = __toESM(require("json-schema-traverse"), 1);
3984
+ function updateRefPaths(schema, wrapperPath) {
3985
+ if (!schema || typeof schema !== "object") {
3986
+ return schema;
3987
+ }
3988
+ if (!wrapperPath || typeof wrapperPath !== "string") {
3989
+ throw new Error("wrapperPath must be a non-empty string");
3990
+ }
3991
+ const clonedSchema = JSON.parse(JSON.stringify(schema));
3992
+ try {
3993
+ (0, import_json_schema_traverse.default)(clonedSchema, {
3994
+ allKeys: true,
3995
+ cb: function(schemaNode, _jsonPtr, _rootSchema, _parentJsonPtr, _parentKeyword, _parentSchema, _keyIndex) {
3996
+ if (schemaNode && typeof schemaNode === "object" && schemaNode.$ref) {
3997
+ const ref = schemaNode.$ref;
3998
+ if (ref.startsWith("#/properties/")) {
3999
+ const relativePath = ref.substring(13);
4000
+ schemaNode.$ref = `#/properties/${wrapperPath}/properties/${relativePath}`;
4001
+ } else if (ref === "#") {
4002
+ schemaNode.$ref = `#/properties/${wrapperPath}`;
4003
+ }
4004
+ }
4005
+ }
4006
+ });
4007
+ } catch (error) {
4008
+ console.warn(`Failed to traverse schema for path "${wrapperPath}":`, error);
4009
+ return clonedSchema;
4010
+ }
4011
+ return clonedSchema;
4012
+ }
4013
+
4014
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/compose-helpers.js
4015
+ async function processToolsWithPlugins(server, _externalTools, mode) {
4016
+ const toolManager = server.toolManager;
4017
+ const pluginManager = server.pluginManager;
4018
+ for (const [toolId, toolData] of toolManager.getToolEntries()) {
4019
+ const defaultSchema = {
4020
+ type: "object",
4021
+ properties: {},
4022
+ additionalProperties: true
4023
+ };
4024
+ const tempTool = {
4025
+ name: toolId,
4026
+ description: toolData.description,
4027
+ inputSchema: toolData.schema || defaultSchema,
4028
+ execute: toolData.callback
4029
+ };
4030
+ const processedTool = await pluginManager.applyTransformToolHooks(tempTool, {
4031
+ toolName: toolId,
4032
+ server,
4033
+ mode,
4034
+ originalTool: {
4035
+ ...tempTool
4036
+ },
4037
+ transformationIndex: 0
4038
+ });
4039
+ toolManager.registerTool(toolId, processedTool.description || toolData.description, processedTool.inputSchema, processedTool.execute);
4040
+ }
4041
+ }
4042
+ function buildDependencyGroups(toolNameToDetailList, hiddenToolNames, publicToolNames, server) {
4043
+ const depGroups = {};
4044
+ const toolManager = server.toolManager;
4045
+ toolNameToDetailList.forEach(([toolName, tool]) => {
4046
+ const resolvedName = toolManager.resolveToolName(toolName);
4047
+ if (hiddenToolNames.includes(resolvedName ?? "") || publicToolNames.includes(resolvedName ?? "")) {
4048
+ return;
4049
+ }
4050
+ if (!tool) {
4051
+ const allToolNames = [
4052
+ ...toolNameToDetailList.map(([n]) => n)
4053
+ ];
4054
+ throw new Error(`Action ${toolName} not found, available action list: ${allToolNames.join(", ")}`);
4055
+ }
4056
+ const baseSchema = tool.inputSchema.jsonSchema ?? tool.inputSchema ?? {
4057
+ type: "object",
4058
+ properties: {},
4059
+ required: []
4060
+ };
4061
+ const baseProperties = baseSchema.type === "object" && baseSchema.properties ? baseSchema.properties : {};
4062
+ const baseRequired = baseSchema.type === "object" && Array.isArray(baseSchema.required) ? baseSchema.required : [];
4063
+ const updatedProperties = updateRefPaths(baseProperties, toolName);
4064
+ const sanitizedKey = sanitizePropertyKey(toolName);
4065
+ depGroups[sanitizedKey] = {
4066
+ type: "object",
4067
+ description: tool.description,
4068
+ properties: updatedProperties,
4069
+ required: [
4070
+ ...baseRequired
4071
+ ],
4072
+ additionalProperties: false
4073
+ };
4074
+ });
4075
+ return depGroups;
4076
+ }
4077
+
4078
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/compose.js
4079
+ var ALL_TOOLS_PLACEHOLDER2 = "__ALL__";
4080
+ var ComposableMCPServer = class extends import_server.Server {
4081
+ pluginManager;
4082
+ toolManager;
4083
+ logger = createLogger("mcpc.compose");
4084
+ // Legacy property for backward compatibility
4085
+ get toolNameMapping() {
4086
+ return this.toolManager.getToolNameMapping();
4087
+ }
4088
+ constructor(_serverInfo, options) {
4089
+ const enhancedOptions = {
4090
+ ...options,
4091
+ capabilities: {
4092
+ logging: {},
4093
+ tools: {},
4094
+ sampling: {},
4095
+ ...options?.capabilities ?? {}
4096
+ }
4097
+ };
4098
+ super(_serverInfo, enhancedOptions);
4099
+ this.logger.setServer(this);
4100
+ this.pluginManager = new PluginManager(this);
4101
+ this.toolManager = new ToolManager();
4102
+ }
4103
+ /**
4104
+ * Initialize built-in plugins - called during setup
4105
+ */
4106
+ async initBuiltInPlugins() {
4107
+ const builtInPlugins = getBuiltInPlugins();
4108
+ const validation = validatePlugins(builtInPlugins);
4109
+ if (!validation.valid) {
4110
+ await this.logger.warning("Built-in plugin validation issues:");
4111
+ for (const error of validation.errors) {
4112
+ await this.logger.warning(` - ${error}`);
4113
+ }
4114
+ }
4115
+ for (const plugin of builtInPlugins) {
4116
+ await this.pluginManager.addPlugin(plugin);
4117
+ }
4118
+ }
4119
+ /**
4120
+ * Apply plugin transformations to tool arguments/results
4121
+ * Supports runtime transformation hooks for input/output processing
4122
+ */
4123
+ async applyPluginTransforms(toolName, data, direction, originalArgs) {
4124
+ const hookName = direction === "input" ? "transformInput" : "transformOutput";
4125
+ const plugins = this.pluginManager.getPlugins().filter((p2) => p2[hookName]);
4126
+ if (plugins.length === 0) {
4127
+ return data;
4128
+ }
4129
+ const sortedPlugins = sortPluginsByOrder(plugins);
4130
+ let currentData = data;
4131
+ const context2 = {
4132
+ toolName,
4133
+ server: this,
4134
+ direction,
4135
+ originalArgs
4136
+ };
4137
+ for (const plugin of sortedPlugins) {
4138
+ const hook = plugin[hookName];
4139
+ if (hook) {
4140
+ try {
4141
+ const result = await hook(currentData, context2);
4142
+ if (result !== void 0) {
4143
+ currentData = result;
4144
+ }
4145
+ } catch (error) {
4146
+ const errorMsg = error instanceof Error ? error.message : String(error);
4147
+ await this.logger.error(`Plugin "${plugin.name}" ${hookName} failed for "${toolName}": ${errorMsg}`);
4148
+ }
4149
+ }
4150
+ }
4151
+ return currentData;
4152
+ }
4153
+ /**
4154
+ * Resolve a tool name to its internal format
4155
+ */
4156
+ resolveToolName(name) {
4157
+ return this.toolManager.resolveToolName(name);
4158
+ }
4159
+ tool(name, description, paramsSchema, cb, options = {}) {
4160
+ const jsonSchemaObj = extractJsonSchema(paramsSchema);
4161
+ this.toolManager.registerTool(name, description, jsonSchemaObj, cb, options);
4162
+ if (!options.internal) {
4163
+ this.toolManager.addPublicTool(name, description, jsonSchemaObj);
4164
+ }
4165
+ if (options.plugins) {
4166
+ for (const plugin of options.plugins) {
4167
+ this.pluginManager.addPlugin(plugin);
4168
+ }
4169
+ }
4170
+ this.setRequestHandler(import_types2.ListToolsRequestSchema, () => {
4171
+ return {
4172
+ tools: this.toolManager.getPublicTools()
4173
+ };
4174
+ });
4175
+ this.setRequestHandler(import_types2.CallToolRequestSchema, async (request, extra) => {
4176
+ const { name: toolName, arguments: args } = request.params;
4177
+ const handler = this.getToolCallback(toolName);
4178
+ if (!handler) {
4179
+ throw new Error(`Tool ${toolName} not found`);
4180
+ }
4181
+ const processedArgs = await this.applyPluginTransforms(toolName, args, "input");
4182
+ const result = await handler(processedArgs, extra);
4183
+ return await this.applyPluginTransforms(toolName, result, "output", args);
4184
+ });
4185
+ this.setRequestHandler(import_types2.SetLevelRequestSchema, (request) => {
4186
+ const { level } = request.params;
4187
+ this.logger.setLevel(level);
4188
+ return {};
4189
+ });
4190
+ }
4191
+ /**
4192
+ * Get tool callback from registry
4193
+ */
4194
+ getToolCallback(name) {
4195
+ return this.toolManager.getToolCallback(name);
4196
+ }
4197
+ /**
4198
+ * Find tool configuration
4199
+ */
4200
+ findToolConfig(toolId) {
4201
+ return this.toolManager.findToolConfig(toolId);
4202
+ }
4203
+ /**
4204
+ * Call any registered tool directly, whether it's public or internal
4205
+ */
4206
+ async callTool(name, args) {
4207
+ const resolvedName = this.resolveToolName(name);
4208
+ if (!resolvedName) {
4209
+ throw new Error(`Tool ${name} not found`);
4210
+ }
4211
+ const callback = this.getToolCallback(resolvedName);
4212
+ if (!callback) {
4213
+ throw new Error(`Tool ${name} not found`);
4214
+ }
4215
+ const processedArgs = await this.applyPluginTransforms(resolvedName, args, "input");
4216
+ const result = await callback(processedArgs);
4217
+ return await this.applyPluginTransforms(resolvedName, result, "output", args);
4218
+ }
4219
+ /**
4220
+ * Get all public tool names (exposed to MCP clients)
4221
+ */
4222
+ getPublicToolNames() {
4223
+ return this.toolManager.getPublicToolNames();
4224
+ }
4225
+ /**
4226
+ * Get all public tools (for AI SDK integration)
4227
+ */
4228
+ getPublicTools() {
4229
+ return this.toolManager.getPublicTools();
4230
+ }
4231
+ /**
4232
+ * Get all hidden tool names
4233
+ */
4234
+ getHiddenToolNames() {
4235
+ return this.toolManager.getHiddenToolNames();
4236
+ }
4237
+ /**
4238
+ * Get all internal tool names (tools that are not public)
4239
+ */
4240
+ getInternalToolNames() {
4241
+ const allToolNames = Array.from(this.toolManager.getToolRegistry().keys());
4242
+ const publicToolNames = this.getPublicToolNames();
4243
+ return allToolNames.filter((name) => !publicToolNames.includes(name));
4244
+ }
4245
+ /**
4246
+ * Get hidden tool schema by name (for internal access)
4247
+ */
4248
+ getHiddenToolSchema(name) {
4249
+ return this.toolManager.getHiddenToolSchema(name);
4250
+ }
4251
+ /**
4252
+ * Check if a tool exists (visible or hidden)
4253
+ */
4254
+ hasToolNamed(name) {
4255
+ return this.toolManager.hasToolNamed(name);
4256
+ }
4257
+ /**
4258
+ * Configure tool behavior
4259
+ */
4260
+ configTool(toolName, config) {
4261
+ this.toolManager.configTool(toolName, config);
4262
+ }
4263
+ /**
4264
+ * Get tool configuration
4265
+ */
4266
+ getToolConfig(toolName) {
4267
+ return this.toolManager.getToolConfig(toolName);
4268
+ }
4269
+ /**
4270
+ * Remove tool configuration
4271
+ */
4272
+ removeToolConfig(toolName) {
4273
+ return this.toolManager.removeToolConfig(toolName);
4274
+ }
4275
+ /**
4276
+ * Register a tool plugin with validation and error handling
4277
+ */
4278
+ async addPlugin(plugin) {
4279
+ await this.pluginManager.addPlugin(plugin);
4280
+ }
4281
+ /**
4282
+ * Load and register a plugin from a file path with optional parameters
4283
+ */
4284
+ async loadPluginFromPath(pluginPath, options = {
4285
+ cache: true
4286
+ }) {
4287
+ await this.pluginManager.loadPluginFromPath(pluginPath, options);
4288
+ }
4289
+ /**
4290
+ * Apply plugins to all tools in registry and handle visibility configurations
4291
+ */
4292
+ async processToolsWithPlugins(externalTools, mode) {
4293
+ await processToolsWithPlugins(this, externalTools, mode);
4294
+ }
4295
+ /**
4296
+ * Dispose all plugins and cleanup resources
4297
+ */
4298
+ async disposePlugins() {
4299
+ await this.pluginManager.dispose();
4300
+ }
4301
+ /**
4302
+ * Close the server and ensure all plugins are disposed
4303
+ */
4304
+ async close() {
4305
+ await this.disposePlugins();
4306
+ await super.close();
4307
+ }
4308
+ async compose(name, description, depsConfig = {
4309
+ mcpServers: {}
4310
+ }, options = {
4311
+ mode: "agentic"
4312
+ }) {
4313
+ const refDesc = options.refs?.join("") ?? "";
4314
+ const { tagToResults } = parseTags(description + refDesc, [
4315
+ "tool",
4316
+ "fn"
4317
+ ]);
4318
+ await this.pluginManager.triggerComposeStart({
4319
+ serverName: name ?? "anonymous",
4320
+ description,
4321
+ mode: options.mode ?? "agentic",
4322
+ server: this,
4323
+ availableTools: []
4324
+ });
4325
+ tagToResults.tool.forEach((toolEl) => {
4326
+ const toolName = toolEl.attribs.name;
4327
+ const toolDescription = toolEl.attribs.description;
4328
+ const isHidden = toolEl.attribs.hide !== void 0;
4329
+ const isPublic = toolEl.attribs.global !== void 0;
4330
+ if (toolName) {
4331
+ this.toolManager.configTool(toolName, {
4332
+ description: toolDescription,
4333
+ visibility: {
4334
+ hidden: isHidden,
4335
+ public: isPublic
4336
+ }
4337
+ });
4338
+ }
4339
+ });
4340
+ const toolNameToIdMapping = /* @__PURE__ */ new Map();
4341
+ const requestedToolNames = /* @__PURE__ */ new Set();
4342
+ const availableToolNames = /* @__PURE__ */ new Set();
4343
+ const allPlaceholderUsages = [];
4344
+ tagToResults.tool.forEach((tool) => {
4345
+ if (tool.attribs.name) {
4346
+ const originalName = tool.attribs.name;
4347
+ const toolName = sanitizePropertyKey(originalName);
4348
+ if (toolName.endsWith(`_${ALL_TOOLS_PLACEHOLDER2}`) || toolName === ALL_TOOLS_PLACEHOLDER2) {
4349
+ allPlaceholderUsages.push(originalName);
4350
+ } else {
4351
+ requestedToolNames.add(toolName);
4352
+ }
4353
+ }
4354
+ });
4355
+ const { tools, cleanupClients } = await composeMcpDepTools(depsConfig, ({ mcpName, toolNameWithScope, toolId }) => {
4356
+ toolNameToIdMapping.set(toolNameWithScope, toolId);
4357
+ availableToolNames.add(toolNameWithScope);
4358
+ availableToolNames.add(toolId);
4359
+ this.toolManager.setToolNameMapping(toolNameWithScope, toolId);
4360
+ const internalName = toolNameWithScope.includes(".") ? toolNameWithScope.split(".").slice(1).join(".") : toolNameWithScope;
4361
+ if (!this.toolNameMapping.has(internalName)) {
4362
+ this.toolManager.setToolNameMapping(internalName, toolId);
4363
+ }
4364
+ const matchingStep = options.steps?.find((step) => step.actions.includes(toolNameWithScope));
4365
+ if (matchingStep) {
4366
+ const actionIndex = matchingStep.actions.indexOf(toolNameWithScope);
4367
+ if (actionIndex !== -1) {
4368
+ matchingStep.actions[actionIndex] = toolId;
4369
+ }
4370
+ return true;
4371
+ }
4372
+ return tagToResults.tool.find((tool) => {
4373
+ const selectAll = tool.attribs.name === `${mcpName}.${ALL_TOOLS_PLACEHOLDER2}` || tool.attribs.name === `${mcpName}`;
4374
+ if (selectAll) {
4375
+ return true;
4376
+ }
4377
+ return tool.attribs.name === toolNameWithScope || tool.attribs.name === toolId;
4378
+ });
4379
+ });
4380
+ Object.entries(tools).forEach(([toolId, tool]) => {
4381
+ this.toolManager.registerTool(toolId, tool.description || "", tool.inputSchema, tool.execute);
4382
+ });
4383
+ const registeredTools = this.toolManager.getRegisteredToolsAsComposed();
4384
+ const allTools = {
4385
+ ...tools
4386
+ };
4387
+ Object.entries(registeredTools).forEach(([toolName, tool]) => {
4388
+ if (!allTools[toolName]) {
4389
+ allTools[toolName] = tool;
4390
+ }
4391
+ availableToolNames.add(toolName);
4392
+ });
4393
+ if (allPlaceholderUsages.length > 0) {
4394
+ await this.logger.warning(`Found ${allPlaceholderUsages.length} __ALL__ placeholder(s) for agent "${name}":`);
4395
+ allPlaceholderUsages.forEach((usage) => {
4396
+ this.logger.warning(` \u2022 "${usage}" - consider using specific tool names`);
4397
+ });
4398
+ const available = Array.from(availableToolNames).sort().join(", ");
4399
+ await this.logger.warning(` Available tools: ${available}`);
4400
+ }
4401
+ const unmatchedTools = Array.from(requestedToolNames).filter((toolName) => !allTools[toolName]);
4402
+ if (unmatchedTools.length > 0) {
4403
+ await this.logger.warning(`Tool matching warnings for agent "${name}":`);
4404
+ unmatchedTools.forEach((toolName) => {
4405
+ this.logger.warning(` \u2022 Tool not found: "${toolName}"`);
4406
+ });
4407
+ const available = Array.from(availableToolNames).sort().join(", ");
4408
+ await this.logger.warning(` Available tools: ${available}`);
4409
+ }
4410
+ await this.processToolsWithPlugins(allTools, options.mode ?? "agentic");
4411
+ await this.pluginManager.triggerFinalizeComposition(allTools, {
4412
+ serverName: name ?? "anonymous",
4413
+ mode: options.mode ?? "agentic",
4414
+ server: this,
4415
+ toolNames: Object.keys(allTools)
4416
+ });
4417
+ this.onclose = async () => {
4418
+ await cleanupClients();
4419
+ await this.disposePlugins();
4420
+ await this.logger.info(`[${name}] Event: closed - cleaned up dependent clients and plugins`);
4421
+ };
4422
+ this.onerror = async (error) => {
4423
+ await this.logger.error(`[${name}] Event: error - ${error?.stack ?? String(error)}`);
4424
+ await cleanupClients();
4425
+ await this.disposePlugins();
4426
+ await this.logger.info(`[${name}] Action: cleaned up dependent clients and plugins`);
4427
+ };
4428
+ const toolNameToDetailList = Object.entries(allTools);
4429
+ const publicToolNames = this.getPublicToolNames();
4430
+ const hiddenToolNames = this.getHiddenToolNames();
4431
+ const contextToolNames = toolNameToDetailList.map(([name2]) => name2).filter((n) => !hiddenToolNames.includes(n));
4432
+ publicToolNames.forEach((toolId) => {
4433
+ const tool = allTools[toolId];
4434
+ if (!tool) {
4435
+ throw new Error(`Public tool ${toolId} not found in registry, available: ${Object.keys(allTools).join(", ")}`);
4436
+ }
4437
+ this.tool(toolId, tool.description || "", jsonSchema(tool.inputSchema), tool.execute, {
4438
+ internal: false
4439
+ });
4440
+ });
4441
+ await this.pluginManager.triggerComposeEnd({
4442
+ toolName: name,
4443
+ pluginNames: this.pluginManager.getPluginNames(),
4444
+ mode: options.mode ?? "agentic",
4445
+ server: this,
4446
+ stats: {
4447
+ totalTools: this.toolManager.getTotalToolCount(),
4448
+ publicTools: publicToolNames.length,
4449
+ hiddenTools: hiddenToolNames.length
4450
+ }
4451
+ });
4452
+ if (!name) {
4453
+ return;
4454
+ }
4455
+ const desTags = parseTags(description, [
4456
+ "tool",
4457
+ "fn"
4458
+ ]);
4459
+ description = processToolTags({
4460
+ ...desTags,
4461
+ description,
4462
+ tools: allTools,
4463
+ toolOverrides: /* @__PURE__ */ new Map(),
4464
+ toolNameMapping: toolNameToIdMapping
4465
+ });
4466
+ const allToolNames = contextToolNames;
4467
+ const depGroups = buildDependencyGroups(toolNameToDetailList, hiddenToolNames, publicToolNames, this);
4468
+ const mode = options.mode ?? "agentic";
4469
+ const context2 = {
4470
+ server: this,
4471
+ name,
4472
+ description,
4473
+ mode,
4474
+ allToolNames,
4475
+ toolNameToDetailList,
4476
+ depGroups,
4477
+ toolNameToIdMapping,
4478
+ publicToolNames,
4479
+ hiddenToolNames,
4480
+ options
4481
+ };
4482
+ const handled = await this.pluginManager.triggerRegisterAgentTool(context2);
4483
+ if (!handled) {
4484
+ throw new Error(`No plugin registered to handle execution mode "${mode}". Did you override the default mode plugin, but in the wrong way?`);
4485
+ }
4486
+ }
4487
+ };
4488
+
4489
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/utils/common/env.js
4490
+ var import_node_process7 = __toESM(require("node:process"), 1);
4491
+ var isSCF = () => Boolean(import_node_process7.default.env.SCF_RUNTIME || import_node_process7.default.env.PROD_SCF);
4492
+ if (isSCF()) {
4493
+ console.log({
4494
+ isSCF: isSCF(),
4495
+ SCF_RUNTIME: import_node_process7.default.env.SCF_RUNTIME
4496
+ });
4497
+ }
4498
+
4499
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/set-up-mcp-compose.js
4500
+ function parseMcpcConfigs(conf) {
4501
+ return conf ?? [];
4502
+ }
4503
+ async function mcpc(serverConf, composeConf, setupCallback) {
4504
+ const server = new ComposableMCPServer(...serverConf);
4505
+ const parsed = parseMcpcConfigs(composeConf);
4506
+ await server.initBuiltInPlugins();
4507
+ for (const mcpcConfig of parsed) {
4508
+ if (mcpcConfig.plugins) {
4509
+ for (const plugin of mcpcConfig.plugins) {
4510
+ if (typeof plugin === "string") {
4511
+ await server.loadPluginFromPath(plugin);
4512
+ } else {
4513
+ await server.addPlugin(plugin);
4514
+ }
4515
+ }
4516
+ }
4517
+ }
4518
+ if (setupCallback) {
4519
+ await setupCallback(server);
4520
+ }
4521
+ for (const mcpcConfig of parsed) {
4522
+ await server.compose(mcpcConfig.name, mcpcConfig.description ?? "", mcpcConfig.deps, mcpcConfig.options);
4523
+ }
4524
+ return server;
4525
+ }
4526
+
4527
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/large-result.js
4528
+ var import_promises2 = require("node:fs/promises");
4529
+ var import_node_path4 = require("node:path");
4530
+ var import_node_os3 = require("node:os");
4531
+
4532
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/search-tool.js
4533
+ var import_ripgrep_napi = __toESM(require("@mcpc-tech/ripgrep-napi"), 1);
4534
+ var import_node_os2 = require("node:os");
4535
+ var import_node_path2 = require("node:path");
4536
+ var import_node_path3 = require("node:path");
4537
+ function createSearchPlugin(options = {}) {
4538
+ const maxResults = options.maxResults || 20;
4539
+ const maxOutputSize = options.maxOutputSize || 5e3;
4540
+ const allowedSearchDir = options.allowedDir || (0, import_node_os2.tmpdir)();
4541
+ const timeoutMs = options.timeoutMs || 3e4;
4542
+ const global = options.global ?? true;
4543
+ const activeTimeouts = /* @__PURE__ */ new Set();
4544
+ return {
4545
+ name: "plugin-search",
4546
+ version: "1.0.0",
4547
+ configureServer: (server) => {
4548
+ server.tool("search-tool-result", `Search for text patterns in files and directories. Use this to find specific content, code, or information within files. Provide a simple literal string or a regular expression. If your pattern is a regex, ensure it's valid; otherwise use quotes or escape special characters to treat it as a literal string.
4549
+ Only search within the allowed directory: ${allowedSearchDir}`, jsonSchema({
4550
+ type: "object",
4551
+ properties: {
4552
+ pattern: {
4553
+ type: "string",
4554
+ description: "Text to search for. Can be a plain string or a regular expression. For regexes, don't include delimiters (e.g. use `^foo` not `/^foo/`). If you get a regex parse error, try escaping special chars or using a simpler literal search."
4555
+ },
4556
+ path: {
4557
+ type: "string",
4558
+ description: "File or folder path to limit the search (optional). Must be within the allowed directory."
4559
+ },
4560
+ maxResults: {
4561
+ type: "number",
4562
+ description: "Maximum number of matches to return (optional). Lower this to reduce output size and runtime."
4563
+ }
4564
+ },
4565
+ required: [
4566
+ "pattern"
4567
+ ]
4568
+ }), async (args) => {
4569
+ const isBroad = (raw) => {
4570
+ const t = (raw ?? "").trim();
4571
+ if (!t) return true;
4572
+ if (/^[*.\s]{2,}$/.test(t)) return true;
4573
+ if (t === ".*" || t === "." || t === "^.*$") return true;
4574
+ if (/^\^?\.\*\$?$/.test(t)) return true;
4575
+ if (/^\\s?\*+$/.test(t)) return true;
4576
+ return false;
4577
+ };
4578
+ const appendMatchSafely = (current, addition, limit) => {
4579
+ if ((current + addition).length > limit) {
4580
+ return {
4581
+ current,
4582
+ added: false
4583
+ };
4584
+ }
4585
+ return {
4586
+ current: current + addition,
4587
+ added: true
4588
+ };
4589
+ };
4590
+ let timeoutId;
4591
+ try {
4592
+ const requestedPath = args.path || allowedSearchDir;
4593
+ const limit = args.maxResults || maxResults;
4594
+ if (args.path) {
4595
+ const resolvedRequested = (0, import_node_path2.resolve)(args.path);
4596
+ const resolvedAllowed = (0, import_node_path2.resolve)(allowedSearchDir);
4597
+ const relativePath = (0, import_node_path3.relative)(resolvedAllowed, resolvedRequested);
4598
+ if (relativePath && relativePath.startsWith("..")) {
4599
+ return {
4600
+ content: [
4601
+ {
4602
+ type: "text",
4603
+ text: `\u274C Path "${args.path}" not allowed. Must be within: ${allowedSearchDir}`
4604
+ }
4605
+ ],
4606
+ isError: true
4607
+ };
4608
+ }
4609
+ }
4610
+ const searchPath = requestedPath;
4611
+ const rawPattern = args.pattern ?? "";
4612
+ if (isBroad(rawPattern)) {
4613
+ return {
4614
+ content: [
4615
+ {
4616
+ type: "text",
4617
+ text: `\u274C Search pattern too broad: "${rawPattern}"
4618
+ Provide a more specific pattern (e.g. include a filename fragment, a keyword, or limit with the "path" parameter). Avoid patterns that only contain wildcards like "*" or ".*".`
4619
+ }
4620
+ ],
4621
+ isError: true
4622
+ };
4623
+ }
4624
+ const timeoutPromise = new Promise((_, reject) => {
4625
+ timeoutId = setTimeout(() => {
4626
+ reject(new Error(`Search timeout after ${timeoutMs}ms`));
4627
+ }, timeoutMs);
4628
+ activeTimeouts.add(timeoutId);
4629
+ });
4630
+ const searchPromise = new Promise((resolve3, reject) => {
4631
+ try {
4632
+ const result2 = import_ripgrep_napi.default.search(args.pattern, [
4633
+ searchPath
4634
+ ]);
4635
+ resolve3(result2);
4636
+ } catch (error) {
4637
+ reject(error);
4638
+ }
4639
+ });
4640
+ const result = await Promise.race([
4641
+ searchPromise,
4642
+ timeoutPromise
4643
+ ]);
4644
+ if (timeoutId) {
4645
+ clearTimeout(timeoutId);
4646
+ activeTimeouts.delete(timeoutId);
4647
+ }
4648
+ if (!result.success || !result.matches?.length) {
4649
+ return {
4650
+ content: [
4651
+ {
4652
+ type: "text",
4653
+ text: `No matches found for: "${args.pattern}"
4654
+
4655
+ Try:
4656
+ - **Simpler pattern** or \`*\`
4657
+ - Check if files exist in: ${searchPath}
4658
+ - Use specific file path`
4659
+ }
4660
+ ]
4661
+ };
4662
+ }
4663
+ const matches = result.matches.slice(0, limit);
4664
+ let output = `Found ${result.matches.length} matches (showing up to ${matches.length}):
4665
+
4666
+ `;
4667
+ let matchesIncluded = 0;
4668
+ for (const match of matches) {
4669
+ const baseMatchText = `**${match.path}:${match.lineNumber}**
4670
+ `;
4671
+ const fullMatchText = `${baseMatchText}\`\`\`
4672
+ ${match.line}
4673
+ \`\`\`
4674
+
4675
+ `;
4676
+ const res = appendMatchSafely(output, fullMatchText, maxOutputSize);
4677
+ if (!res.added) {
4678
+ if (matchesIncluded === 0) {
4679
+ const remainingSpace = maxOutputSize - output.length - 100;
4680
+ if (remainingSpace > 50) {
4681
+ const truncatedLine = match.line.slice(0, remainingSpace);
4682
+ output += `${baseMatchText}\`\`\`
4683
+ ${truncatedLine}...
4684
+ \`\`\`
4685
+
4686
+ `;
4687
+ output += `\u26A0\uFE0F Content truncated
4688
+ `;
4689
+ matchesIncluded++;
4690
+ } else {
4691
+ output += `\u26A0\uFE0F Content too large, use specific file path
4692
+ `;
4693
+ }
4694
+ }
4695
+ break;
4696
+ }
4697
+ output = res.current;
4698
+ matchesIncluded++;
4699
+ }
4700
+ if (matchesIncluded < matches.length) {
4701
+ output += `
4702
+ \u26A0\uFE0F Showing ${matchesIncluded}/${matches.length} matches (size limit)
4703
+ `;
4704
+ output += `
4705
+ For more results:
4706
+ `;
4707
+ output += `- Use specific pattern: "${args.pattern} keyword"
4708
+ `;
4709
+ output += `- Search specific file: {"pattern": "${args.pattern}", "path": "/file.txt"}
4710
+ `;
4711
+ output += `- Use fewer results: {"maxResults": 5}`;
4712
+ }
4713
+ return {
4714
+ content: [
4715
+ {
4716
+ type: "text",
4717
+ text: output
4718
+ }
4719
+ ]
4720
+ };
4721
+ } catch (error) {
4722
+ if (timeoutId) {
4723
+ clearTimeout(timeoutId);
4724
+ activeTimeouts.delete(timeoutId);
4725
+ }
4726
+ const errorMsg = error instanceof Error ? error.message : String(error);
4727
+ const isTimeout = errorMsg.includes("timeout");
4728
+ return {
4729
+ content: [
4730
+ {
4731
+ type: "text",
4732
+ text: `Search error: ${errorMsg}
4733
+
4734
+ ${isTimeout ? `Timeout after ${timeoutMs}ms. Try simpler pattern or smaller directory.` : `Check pattern syntax or directory exists.`}`
4735
+ }
4736
+ ]
4737
+ };
4738
+ }
4739
+ }, {
4740
+ internal: !global
4741
+ });
4742
+ },
4743
+ dispose: () => {
4744
+ for (const timeoutId of activeTimeouts) {
4745
+ clearTimeout(timeoutId);
4746
+ }
4747
+ activeTimeouts.clear();
4748
+ }
4749
+ };
4750
+ }
4751
+ var defaultSearchPlugin = createSearchPlugin({
4752
+ global: true,
4753
+ maxResults: 20,
4754
+ maxOutputSize: 5e3,
4755
+ caseSensitive: false,
4756
+ timeoutMs: 3e4
4757
+ });
4758
+
4759
+ // __mcpc__cli_latest/node_modules/@jsr/mcpc__core/src/plugins/large-result.js
4760
+ function createLargeResultPlugin(options = {}) {
4761
+ const maxSize = options.maxSize || 8e3;
4762
+ const previewSize = options.previewSize || 4e3;
4763
+ let tempDir = options.tempDir || null;
4764
+ const configuredServers = /* @__PURE__ */ new Map();
4765
+ const searchConfig = {
4766
+ maxResults: options.search?.maxResults || 15,
4767
+ maxOutputSize: options.search?.maxOutputSize || 4e3,
4768
+ global: true
4769
+ };
4770
+ return {
4771
+ name: "plugin-large-result-handler",
4772
+ version: "1.0.0",
4773
+ dependencies: [],
4774
+ configureServer: async (server) => {
4775
+ if (!configuredServers.has(server)) {
4776
+ const searchPlugin = createSearchPlugin(searchConfig);
4777
+ await server.addPlugin(searchPlugin);
4778
+ configuredServers.set(server, true);
4779
+ }
4780
+ },
4781
+ transformTool: (tool, context2) => {
4782
+ const originalExecute = tool.execute;
4783
+ tool.execute = async (args) => {
4784
+ try {
4785
+ const result = await originalExecute(args);
4786
+ const resultText = JSON.stringify(result);
4787
+ if (resultText.length <= maxSize) {
4788
+ return result;
4789
+ }
4790
+ if (!tempDir) {
4791
+ tempDir = await (0, import_promises2.mkdtemp)((0, import_node_path4.join)((0, import_node_os3.tmpdir)(), "mcpc-results-"));
4792
+ }
4793
+ const safeToolName = encodeURIComponent(context2.toolName ?? "tool");
4794
+ const fileName = `${safeToolName}-${Date.now()}.txt`;
4795
+ const filePath = (0, import_node_path4.join)(tempDir, fileName);
4796
+ await (0, import_promises2.writeFile)(filePath, resultText);
4797
+ const preview = resultText.slice(0, previewSize);
4798
+ const sizeKB = (resultText.length / 1024).toFixed(1);
4799
+ return {
4800
+ content: [
4801
+ {
4802
+ type: "text",
4803
+ text: `**Result too large (${resultText.length} chars), saved to file**
4804
+
4805
+ \u{1F4C1} **File:** ${filePath}
4806
+ \u{1F4CA} **Size:** ${sizeKB} KB
4807
+
4808
+ **Preview (${previewSize} chars):**
4809
+ \`\`\`
4810
+ ${preview}
4811
+ \`\`\`
4812
+
4813
+ **To read/understand the full content:**
4814
+ - Use the \`search-tool-result\` tool with pattern: \`search-tool-result {"pattern": "your-search-term"}\`
4815
+ - Search supports regex patterns for advanced queries`
4816
+ }
4817
+ ]
4818
+ };
4819
+ } catch (error) {
4820
+ const errorMsg = error instanceof Error ? error.message : String(error);
4821
+ console.error(`Large result plugin error for ${context2.toolName}: ${errorMsg}`);
4822
+ throw error;
4823
+ }
4824
+ };
4825
+ return tool;
4826
+ },
4827
+ dispose: () => {
4828
+ configuredServers.clear();
4829
+ tempDir = null;
4830
+ }
4831
+ };
4832
+ }
4833
+ var defaultLargeResultPlugin = createLargeResultPlugin({
4834
+ maxSize: 8e3,
4835
+ previewSize: 4e3
4836
+ });
4837
+
4838
+ // __mcpc__cli_latest/node_modules/@mcpc/cli/src/app.js
4839
+ var import_plugin_code_execution = require("@mcpc-tech/plugin-code-execution");
4840
+ var createServer = async (config) => {
4841
+ const serverConfig = config || {
4842
+ name: "mcpc-server",
4843
+ version: "0.1.0",
4844
+ agents: [
4845
+ {
4846
+ name: null,
4847
+ description: "",
4848
+ plugins: [
4849
+ createLargeResultPlugin({}),
4850
+ import_plugin_code_execution.codeExecutionPlugin
4851
+ ],
4852
+ options: {
4853
+ mode: "code_execution"
4854
+ }
4855
+ }
4856
+ ]
4857
+ };
4858
+ return await mcpc([
4859
+ {
4860
+ name: serverConfig.name || "mcpc-server",
4861
+ version: serverConfig.version || "0.1.0"
4862
+ },
4863
+ {
4864
+ capabilities: serverConfig?.capabilities || {
4865
+ tools: {},
4866
+ sampling: {},
4867
+ logging: {}
4868
+ }
4869
+ }
4870
+ ], serverConfig.agents);
4871
+ };
4872
+
4873
+ // __mcpc__cli_latest/node_modules/@mcpc/cli/src/bin.ts
4874
+ var import_plugin_code_execution2 = require("@mcpc-tech/plugin-code-execution");
4875
+ (async () => {
4876
+ const config = await loadConfig();
4877
+ config?.agents.forEach((agent) => {
4878
+ if (agent.plugins?.length ?? true) {
4879
+ agent.plugins = [];
4880
+ }
4881
+ agent.plugins?.push(
4882
+ (0, import_plugin_code_execution2.createCodeExecutionPlugin)({
4883
+ sandbox: {
4884
+ timeout: 3e5
4885
+ }
4886
+ })
4887
+ );
4888
+ });
4889
+ if (config) {
4890
+ console.error(`Loaded configuration with ${config.agents.length} agent(s)`);
4891
+ } else {
4892
+ console.error(
4893
+ "No configuration found, using default example configuration"
4894
+ );
4895
+ }
4896
+ const server = await createServer(config || void 0);
4897
+ const transport = new import_stdio2.StdioServerTransport();
4898
+ await server.connect(transport);
4899
+ })();