@mcpc-tech/core 0.3.9 → 0.3.10

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