@mcpc-tech/core 0.2.0-beta.10 → 0.2.1

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.
@@ -1,3 +1,4 @@
1
+ #!/usr/bin/env node
1
2
  var __defProp = Object.defineProperty;
2
3
  var __getOwnPropNames = Object.getOwnPropertyNames;
3
4
  var __esm = (fn, res) => function __init() {
@@ -8,16 +9,141 @@ var __export = (target, all) => {
8
9
  __defProp(target, name, { get: all[name], enumerable: true });
9
10
  };
10
11
 
11
- // ../__mcpc__core_0.2.0-beta.10/node_modules/@mcpc/core/src/plugins/built-in/config-plugin.js
12
+ // ../__mcpc__core_latest/node_modules/@mcpc/core/src/utils/schema.js
13
+ function jsonSchema(schema, options = {}) {
14
+ if (isWrappedSchema(schema)) {
15
+ return schema;
16
+ }
17
+ return {
18
+ [schemaSymbol]: true,
19
+ [validatorSymbol]: true,
20
+ _type: void 0,
21
+ jsonSchema: schema,
22
+ validate: options.validate
23
+ };
24
+ }
25
+ function isWrappedSchema(value) {
26
+ return typeof value === "object" && value !== null && schemaSymbol in value && value[schemaSymbol] === true;
27
+ }
28
+ function extractJsonSchema(schema) {
29
+ if (isWrappedSchema(schema)) {
30
+ return schema.jsonSchema;
31
+ }
32
+ return schema;
33
+ }
34
+ var schemaSymbol, validatorSymbol;
35
+ var init_schema = __esm({
36
+ "../__mcpc__core_latest/node_modules/@mcpc/core/src/utils/schema.js"() {
37
+ schemaSymbol = Symbol.for("mcpc.schema");
38
+ validatorSymbol = Symbol.for("mcpc.validator");
39
+ }
40
+ });
41
+
42
+ // ../__mcpc__core_latest/node_modules/@mcpc/core/src/utils/logger.js
43
+ function createLogger(name, server) {
44
+ return new MCPLogger(name, server);
45
+ }
46
+ var LOG_LEVELS, MCPLogger, logger;
47
+ var init_logger = __esm({
48
+ "../__mcpc__core_latest/node_modules/@mcpc/core/src/utils/logger.js"() {
49
+ LOG_LEVELS = {
50
+ debug: 0,
51
+ info: 1,
52
+ notice: 2,
53
+ warning: 3,
54
+ error: 4,
55
+ critical: 5,
56
+ alert: 6,
57
+ emergency: 7
58
+ };
59
+ MCPLogger = class _MCPLogger {
60
+ server;
61
+ loggerName;
62
+ minLevel = "debug";
63
+ constructor(loggerName = "mcpc", server) {
64
+ this.loggerName = loggerName;
65
+ this.server = server;
66
+ }
67
+ setServer(server) {
68
+ this.server = server;
69
+ }
70
+ setLevel(level) {
71
+ this.minLevel = level;
72
+ }
73
+ async log(level, data) {
74
+ if (LOG_LEVELS[level] < LOG_LEVELS[this.minLevel]) {
75
+ return;
76
+ }
77
+ this.logToConsole(level, data);
78
+ if (this.server) {
79
+ try {
80
+ await this.server.sendLoggingMessage({
81
+ level,
82
+ logger: this.loggerName,
83
+ data
84
+ });
85
+ } catch {
86
+ }
87
+ }
88
+ }
89
+ logToConsole(level, data) {
90
+ const message = typeof data === "string" ? data : JSON.stringify(data);
91
+ const prefix = `[${this.loggerName}]`;
92
+ if (level === "debug") {
93
+ console.debug(prefix, message);
94
+ } else if (level === "info" || level === "notice") {
95
+ console.info(prefix, message);
96
+ } else if (level === "warning") {
97
+ console.warn(prefix, message);
98
+ } else {
99
+ console.error(prefix, message);
100
+ }
101
+ }
102
+ debug(data) {
103
+ return this.log("debug", data);
104
+ }
105
+ info(data) {
106
+ return this.log("info", data);
107
+ }
108
+ notice(data) {
109
+ return this.log("notice", data);
110
+ }
111
+ warning(data) {
112
+ return this.log("warning", data);
113
+ }
114
+ error(data) {
115
+ return this.log("error", data);
116
+ }
117
+ critical(data) {
118
+ return this.log("critical", data);
119
+ }
120
+ alert(data) {
121
+ return this.log("alert", data);
122
+ }
123
+ emergency(data) {
124
+ return this.log("emergency", data);
125
+ }
126
+ child(name) {
127
+ const child = new _MCPLogger(`${this.loggerName}.${name}`, this.server);
128
+ child.setLevel(this.minLevel);
129
+ return child;
130
+ }
131
+ };
132
+ logger = new MCPLogger("mcpc");
133
+ }
134
+ });
135
+
136
+ // ../__mcpc__core_latest/node_modules/@mcpc/core/src/plugins/built-in/config-plugin.js
12
137
  var createConfigPlugin, config_plugin_default;
13
138
  var init_config_plugin = __esm({
14
- "../__mcpc__core_0.2.0-beta.10/node_modules/@mcpc/core/src/plugins/built-in/config-plugin.js"() {
139
+ "../__mcpc__core_latest/node_modules/@mcpc/core/src/plugins/built-in/config-plugin.js"() {
15
140
  createConfigPlugin = () => ({
16
141
  name: "built-in-config",
142
+ version: "1.0.0",
17
143
  enforce: "pre",
18
- transformTool: (tool, context) => {
19
- const server = context.server;
20
- const config = server.findToolConfig?.(context.toolName);
144
+ transformTool: (tool, context2) => {
145
+ const server = context2.server;
146
+ const config = server.findToolConfig?.(context2.toolName);
21
147
  if (config?.description) {
22
148
  tool.description = config.description;
23
149
  }
@@ -28,16 +154,17 @@ var init_config_plugin = __esm({
28
154
  }
29
155
  });
30
156
 
31
- // ../__mcpc__core_0.2.0-beta.10/node_modules/@mcpc/core/src/plugins/built-in/tool-name-mapping-plugin.js
157
+ // ../__mcpc__core_latest/node_modules/@mcpc/core/src/plugins/built-in/tool-name-mapping-plugin.js
32
158
  var createToolNameMappingPlugin, tool_name_mapping_plugin_default;
33
159
  var init_tool_name_mapping_plugin = __esm({
34
- "../__mcpc__core_0.2.0-beta.10/node_modules/@mcpc/core/src/plugins/built-in/tool-name-mapping-plugin.js"() {
160
+ "../__mcpc__core_latest/node_modules/@mcpc/core/src/plugins/built-in/tool-name-mapping-plugin.js"() {
35
161
  createToolNameMappingPlugin = () => ({
36
162
  name: "built-in-tool-name-mapping",
163
+ version: "1.0.0",
37
164
  enforce: "pre",
38
- transformTool: (tool, context) => {
39
- const server = context.server;
40
- const toolName = context.toolName;
165
+ transformTool: (tool, context2) => {
166
+ const server = context2.server;
167
+ const toolName = context2.toolName;
41
168
  const dotNotation = toolName.replace(/_/g, ".");
42
169
  const underscoreNotation = toolName.replace(/\./g, "_");
43
170
  if (dotNotation !== toolName && server.toolNameMapping) {
@@ -55,58 +182,37 @@ var init_tool_name_mapping_plugin = __esm({
55
182
  }
56
183
  });
57
184
 
58
- // ../__mcpc__core_0.2.0-beta.10/node_modules/@mcpc/core/src/plugins/built-in/logging-plugin.js
185
+ // ../__mcpc__core_latest/node_modules/@mcpc/core/src/plugins/built-in/logging-plugin.js
59
186
  var createLoggingPlugin, logging_plugin_default;
60
187
  var init_logging_plugin = __esm({
61
- "../__mcpc__core_0.2.0-beta.10/node_modules/@mcpc/core/src/plugins/built-in/logging-plugin.js"() {
188
+ "../__mcpc__core_latest/node_modules/@mcpc/core/src/plugins/built-in/logging-plugin.js"() {
189
+ init_logger();
62
190
  createLoggingPlugin = (options = {}) => {
63
191
  const { enabled = true, verbose = false, compact: compact2 = true } = options;
64
192
  return {
65
193
  name: "built-in-logging",
66
- composeEnd: (context) => {
194
+ version: "1.0.0",
195
+ composeEnd: async (context2) => {
67
196
  if (!enabled) return;
197
+ const logger2 = createLogger("mcpc.plugin.logging", context2.server);
68
198
  if (compact2) {
69
- const pluginCount = context.pluginNames.length;
70
- const server = context.server;
71
- const externalList = server.getExternalToolNames();
72
- const internalList = server.getInternalToolNames();
73
- const hiddenList = server.getHiddenToolNames();
74
- const publicToolNames = server.getPublicToolNames();
75
- const externalCount = externalList.length;
76
- const internalCount = internalList.length;
77
- const hiddenCount = hiddenList.length;
78
- const globalCount = publicToolNames.length;
79
- console.log(`\u{1F9E9} [${context.toolName}] ${pluginCount} plugins \u2022 ${externalCount} external \u2022 ${internalCount} internal \u2022 ${hiddenCount} hidden \u2022 ${globalCount} global`);
199
+ const pluginCount = context2.pluginNames.length;
200
+ const { stats } = context2;
201
+ await logger2.info(`[${context2.toolName}] ${pluginCount} plugins \u2022 ${stats.publicTools} public \u2022 ${stats.hiddenTools} hidden`);
80
202
  } else if (verbose) {
81
- console.log(`\u{1F9E9} [${context.toolName}]`);
82
- console.log(` \u251C\u2500 Plugins: ${context.pluginNames.join(", ")}`);
83
- const server = context.server;
84
- const globalToolNames = Array.from(new Set(server.getPublicToolNames().map(String)));
85
- const external = Array.from(new Set(server.getExternalToolNames().map(String)));
86
- const internal = Array.from(new Set(server.getInternalToolNames().map(String)));
87
- const hidden = Array.from(new Set(server.getHiddenToolNames().map(String)));
88
- const globalNames = globalToolNames.map(String);
89
- const totalSet = /* @__PURE__ */ new Set([
90
- ...external,
91
- ...internal,
92
- ...globalNames
93
- ]);
94
- const totalList = Array.from(totalSet);
95
- if (external.length > 0) {
96
- console.log(` \u251C\u2500 External: ${external.join(", ")}`);
97
- }
98
- if (internal.length > 0) {
99
- console.log(` \u251C\u2500 Internal: ${internal.join(", ")}`);
100
- }
101
- if (globalNames.length > 0) {
102
- console.log(` \u251C\u2500 Global: ${globalNames.join(", ")}`);
103
- }
104
- if (hidden.length > 0) {
105
- console.log(` \u251C\u2500 Hidden: ${hidden.join(", ")}`);
203
+ await logger2.info(`[${context2.toolName}] Composition complete`);
204
+ await logger2.info(` \u251C\u2500 Plugins: ${context2.pluginNames.join(", ")}`);
205
+ const { stats } = context2;
206
+ const server = context2.server;
207
+ const publicTools = Array.from(new Set(server.getPublicToolNames().map(String)));
208
+ const hiddenTools = Array.from(new Set(server.getHiddenToolNames().map(String)));
209
+ if (publicTools.length > 0) {
210
+ await logger2.info(` \u251C\u2500 Public: ${publicTools.join(", ")}`);
106
211
  }
107
- if (totalList.length > 0) {
108
- console.log(` \u2514\u2500 Total: ${totalList.length} tools`);
212
+ if (hiddenTools.length > 0) {
213
+ await logger2.info(` \u251C\u2500 Hidden: ${hiddenTools.join(", ")}`);
109
214
  }
215
+ await logger2.info(` \u2514\u2500 Total: ${stats.totalTools} tools`);
110
216
  }
111
217
  }
112
218
  };
@@ -118,7 +224,7 @@ var init_logging_plugin = __esm({
118
224
  }
119
225
  });
120
226
 
121
- // ../__mcpc__core_0.2.0-beta.10/node_modules/@mcpc/core/src/plugins/built-in/index.js
227
+ // ../__mcpc__core_latest/node_modules/@mcpc/core/src/plugins/built-in/index.js
122
228
  var built_in_exports = {};
123
229
  __export(built_in_exports, {
124
230
  createConfigPlugin: () => createConfigPlugin,
@@ -134,7 +240,7 @@ function getBuiltInPlugins() {
134
240
  ];
135
241
  }
136
242
  var init_built_in = __esm({
137
- "../__mcpc__core_0.2.0-beta.10/node_modules/@mcpc/core/src/plugins/built-in/index.js"() {
243
+ "../__mcpc__core_latest/node_modules/@mcpc/core/src/plugins/built-in/index.js"() {
138
244
  init_config_plugin();
139
245
  init_tool_name_mapping_plugin();
140
246
  init_logging_plugin();
@@ -144,34 +250,389 @@ var init_built_in = __esm({
144
250
  }
145
251
  });
146
252
 
147
- // ../__mcpc__core_0.2.0-beta.10/node_modules/@mcpc/core/src/compose.js
148
- import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
149
- import { jsonSchema as jsonSchema3 } from "ai";
253
+ // ../__mcpc__core_latest/node_modules/@mcpc/core/src/plugin-utils.js
254
+ var plugin_utils_exports = {};
255
+ __export(plugin_utils_exports, {
256
+ checkCircularDependencies: () => checkCircularDependencies,
257
+ clearPluginCache: () => clearPluginCache,
258
+ getPluginsWithHook: () => getPluginsWithHook,
259
+ isValidPlugin: () => isValidPlugin,
260
+ loadPlugin: () => loadPlugin,
261
+ shouldApplyPlugin: () => shouldApplyPlugin,
262
+ sortPluginsByOrder: () => sortPluginsByOrder,
263
+ validatePlugins: () => validatePlugins
264
+ });
265
+ function shouldApplyPlugin(plugin, mode) {
266
+ if (!plugin.apply) return true;
267
+ if (typeof plugin.apply === "string") {
268
+ return mode.includes(plugin.apply);
269
+ }
270
+ if (typeof plugin.apply === "function") {
271
+ try {
272
+ return plugin.apply(mode);
273
+ } catch (error) {
274
+ console.warn(`Plugin "${plugin.name}" apply function failed: ${error}. Defaulting to true.`);
275
+ return true;
276
+ }
277
+ }
278
+ return true;
279
+ }
280
+ function sortPluginsByOrder(plugins) {
281
+ const pluginMap = /* @__PURE__ */ new Map();
282
+ for (const plugin of plugins) {
283
+ pluginMap.set(plugin.name, plugin);
284
+ }
285
+ const visited = /* @__PURE__ */ new Set();
286
+ const sorted = [];
287
+ function visit(plugin) {
288
+ if (visited.has(plugin.name)) return;
289
+ visited.add(plugin.name);
290
+ if (plugin.dependencies) {
291
+ for (const depName of plugin.dependencies) {
292
+ const dep = pluginMap.get(depName);
293
+ if (dep) {
294
+ visit(dep);
295
+ } else {
296
+ console.warn(`Plugin "${plugin.name}" depends on "${depName}" which is not loaded`);
297
+ }
298
+ }
299
+ }
300
+ sorted.push(plugin);
301
+ }
302
+ const prePlugins = plugins.filter((p2) => p2.enforce === "pre");
303
+ const normalPlugins = plugins.filter((p2) => !p2.enforce);
304
+ const postPlugins = plugins.filter((p2) => p2.enforce === "post");
305
+ [
306
+ ...prePlugins,
307
+ ...normalPlugins,
308
+ ...postPlugins
309
+ ].forEach(visit);
310
+ return sorted;
311
+ }
312
+ function getPluginsWithHook(plugins, hookName) {
313
+ return plugins.filter((p2) => typeof p2[hookName] === "function");
314
+ }
315
+ function isValidPlugin(plugin) {
316
+ if (!plugin || typeof plugin !== "object") return false;
317
+ const p2 = plugin;
318
+ if (!p2.name || typeof p2.name !== "string" || p2.name.trim() === "") {
319
+ return false;
320
+ }
321
+ const hasHook = typeof p2.configureServer === "function" || typeof p2.composeStart === "function" || typeof p2.transformTool === "function" || typeof p2.finalizeComposition === "function" || typeof p2.composeEnd === "function" || typeof p2.transformInput === "function" || typeof p2.transformOutput === "function" || typeof p2.dispose === "function";
322
+ if (!hasHook) return false;
323
+ if (p2.enforce && p2.enforce !== "pre" && p2.enforce !== "post") {
324
+ return false;
325
+ }
326
+ if (p2.apply && typeof p2.apply !== "string" && typeof p2.apply !== "function") {
327
+ return false;
328
+ }
329
+ if (p2.dependencies && !Array.isArray(p2.dependencies)) {
330
+ return false;
331
+ }
332
+ return true;
333
+ }
334
+ function parseQueryParams(params) {
335
+ const typedParams = {};
336
+ for (const [key, value] of Object.entries(params)) {
337
+ const numValue = Number(value);
338
+ if (!isNaN(numValue) && value.trim() !== "") {
339
+ typedParams[key] = numValue;
340
+ continue;
341
+ }
342
+ if (value === "true") {
343
+ typedParams[key] = true;
344
+ continue;
345
+ }
346
+ if (value === "false") {
347
+ typedParams[key] = false;
348
+ continue;
349
+ }
350
+ if (value.includes(",")) {
351
+ typedParams[key] = value.split(",").map((v) => v.trim());
352
+ continue;
353
+ }
354
+ typedParams[key] = value;
355
+ }
356
+ return typedParams;
357
+ }
358
+ async function loadPlugin(pluginPath, options = {
359
+ cache: true
360
+ }) {
361
+ if (options.cache && pluginCache.has(pluginPath)) {
362
+ return pluginCache.get(pluginPath);
363
+ }
364
+ try {
365
+ const [rawPath, queryString] = pluginPath.split("?", 2);
366
+ const searchParams = new URLSearchParams(queryString || "");
367
+ const params = Object.fromEntries(searchParams.entries());
368
+ const importPath = rawPath;
369
+ const pluginModule = await import(importPath);
370
+ const pluginFactory = pluginModule.createPlugin;
371
+ const defaultPlugin = pluginModule.default;
372
+ let plugin;
373
+ if (Object.keys(params).length > 0) {
374
+ if (typeof pluginFactory !== "function") {
375
+ throw new Error(`Plugin "${rawPath}" has parameters but no createPlugin export function`);
376
+ }
377
+ const typedParams = parseQueryParams(params);
378
+ plugin = pluginFactory(typedParams);
379
+ } else {
380
+ if (defaultPlugin) {
381
+ plugin = defaultPlugin;
382
+ } else if (typeof pluginFactory === "function") {
383
+ plugin = pluginFactory();
384
+ } else {
385
+ throw new Error(`Plugin "${rawPath}" has no default export or createPlugin function`);
386
+ }
387
+ }
388
+ if (!isValidPlugin(plugin)) {
389
+ throw new Error(`Invalid plugin format in "${rawPath}": must have a unique name and at least one lifecycle hook`);
390
+ }
391
+ if (options.cache) {
392
+ pluginCache.set(pluginPath, plugin);
393
+ }
394
+ return plugin;
395
+ } catch (error) {
396
+ const errorMsg = error instanceof Error ? error.message : String(error);
397
+ throw new Error(`Failed to load plugin from "${pluginPath}": ${errorMsg}`);
398
+ }
399
+ }
400
+ function clearPluginCache() {
401
+ pluginCache.clear();
402
+ }
403
+ function checkCircularDependencies(plugins) {
404
+ const errors = [];
405
+ const pluginMap = /* @__PURE__ */ new Map();
406
+ for (const plugin of plugins) {
407
+ pluginMap.set(plugin.name, plugin);
408
+ }
409
+ function checkCircular(pluginName, visited, path) {
410
+ if (visited.has(pluginName)) {
411
+ const cycle = [
412
+ ...path,
413
+ pluginName
414
+ ].join(" -> ");
415
+ errors.push(`Circular dependency detected: ${cycle}`);
416
+ return;
417
+ }
418
+ const plugin = pluginMap.get(pluginName);
419
+ if (!plugin || !plugin.dependencies) return;
420
+ visited.add(pluginName);
421
+ path.push(pluginName);
422
+ for (const dep of plugin.dependencies) {
423
+ checkCircular(dep, new Set(visited), [
424
+ ...path
425
+ ]);
426
+ }
427
+ }
428
+ for (const plugin of plugins) {
429
+ checkCircular(plugin.name, /* @__PURE__ */ new Set(), []);
430
+ }
431
+ return errors;
432
+ }
433
+ function validatePlugins(plugins) {
434
+ const errors = [];
435
+ const names = /* @__PURE__ */ new Map();
436
+ for (const plugin of plugins) {
437
+ const count = names.get(plugin.name) || 0;
438
+ names.set(plugin.name, count + 1);
439
+ }
440
+ for (const [name, count] of names.entries()) {
441
+ if (count > 1) {
442
+ errors.push(`Duplicate plugin name: "${name}" (${count} instances)`);
443
+ }
444
+ }
445
+ const circularErrors = checkCircularDependencies(plugins);
446
+ errors.push(...circularErrors);
447
+ for (const plugin of plugins) {
448
+ if (!isValidPlugin(plugin)) {
449
+ const name = plugin.name || "unknown";
450
+ errors.push(`Invalid plugin: "${name}"`);
451
+ }
452
+ }
453
+ return {
454
+ valid: errors.length === 0,
455
+ errors
456
+ };
457
+ }
458
+ var pluginCache;
459
+ var init_plugin_utils = __esm({
460
+ "../__mcpc__core_latest/node_modules/@mcpc/core/src/plugin-utils.js"() {
461
+ pluginCache = /* @__PURE__ */ new Map();
462
+ }
463
+ });
464
+
465
+ // ../__mcpc__core_latest/node_modules/@mcpc/core/src/utils/common/schema.js
466
+ import traverse from "json-schema-traverse";
467
+ function updateRefPaths(schema, wrapperPath) {
468
+ if (!schema || typeof schema !== "object") {
469
+ return schema;
470
+ }
471
+ if (!wrapperPath || typeof wrapperPath !== "string") {
472
+ throw new Error("wrapperPath must be a non-empty string");
473
+ }
474
+ const clonedSchema = JSON.parse(JSON.stringify(schema));
475
+ try {
476
+ traverse(clonedSchema, {
477
+ allKeys: true,
478
+ cb: function(schemaNode, _jsonPtr, _rootSchema, _parentJsonPtr, _parentKeyword, _parentSchema, _keyIndex) {
479
+ if (schemaNode && typeof schemaNode === "object" && schemaNode.$ref) {
480
+ const ref = schemaNode.$ref;
481
+ if (ref.startsWith("#/properties/")) {
482
+ const relativePath = ref.substring(13);
483
+ schemaNode.$ref = `#/properties/${wrapperPath}/properties/${relativePath}`;
484
+ } else if (ref === "#") {
485
+ schemaNode.$ref = `#/properties/${wrapperPath}`;
486
+ }
487
+ }
488
+ }
489
+ });
490
+ } catch (error) {
491
+ console.warn(`Failed to traverse schema for path "${wrapperPath}":`, error);
492
+ return clonedSchema;
493
+ }
494
+ return clonedSchema;
495
+ }
496
+ var init_schema2 = __esm({
497
+ "../__mcpc__core_latest/node_modules/@mcpc/core/src/utils/common/schema.js"() {
498
+ }
499
+ });
500
+
501
+ // ../__mcpc__core_latest/node_modules/@mcpc/core/src/utils/compose-helpers.js
502
+ var compose_helpers_exports = {};
503
+ __export(compose_helpers_exports, {
504
+ buildDependencyGroups: () => buildDependencyGroups,
505
+ processToolsWithPlugins: () => processToolsWithPlugins,
506
+ registerGlobalTools: () => registerGlobalTools
507
+ });
508
+ async function processToolsWithPlugins(server, externalTools, mode) {
509
+ const toolManager = server.toolManager;
510
+ const pluginManager = server.pluginManager;
511
+ for (const [toolId, toolData] of toolManager.getToolEntries()) {
512
+ const defaultSchema = {
513
+ type: "object",
514
+ properties: {},
515
+ additionalProperties: true
516
+ };
517
+ const tempTool = {
518
+ name: toolId,
519
+ description: toolData.description,
520
+ inputSchema: toolData.schema || defaultSchema,
521
+ execute: toolData.callback
522
+ };
523
+ const processedTool = await pluginManager.applyTransformToolHooks(tempTool, {
524
+ toolName: toolId,
525
+ server,
526
+ mode,
527
+ originalTool: {
528
+ ...tempTool
529
+ },
530
+ transformationIndex: 0
531
+ });
532
+ toolManager.registerTool(toolId, processedTool.description || toolData.description, processedTool.inputSchema, processedTool.execute);
533
+ if (externalTools[toolId]) {
534
+ try {
535
+ const builtIn = await Promise.resolve().then(() => (init_built_in(), built_in_exports));
536
+ if (builtIn && typeof builtIn.processToolVisibility === "function") {
537
+ builtIn.processToolVisibility(toolId, processedTool, server, externalTools);
538
+ }
539
+ } catch {
540
+ }
541
+ externalTools[toolId] = processedTool;
542
+ }
543
+ }
544
+ }
545
+ function buildDependencyGroups(toolNameToDetailList, hiddenToolNames, publicToolNames, server) {
546
+ const depGroups = {};
547
+ const toolManager = server.toolManager;
548
+ toolNameToDetailList.forEach(([toolName, tool]) => {
549
+ const resolvedName = toolManager.resolveToolName(toolName);
550
+ if (hiddenToolNames.includes(resolvedName ?? "") || publicToolNames.includes(resolvedName ?? "")) {
551
+ return;
552
+ }
553
+ if (!tool) {
554
+ const allToolNames = [
555
+ ...toolNameToDetailList.map(([n]) => n)
556
+ ];
557
+ throw new Error(`Action ${toolName} not found, available action list: ${allToolNames.join(", ")}`);
558
+ }
559
+ const baseSchema = tool.inputSchema.jsonSchema ?? tool.inputSchema ?? {
560
+ type: "object",
561
+ properties: {},
562
+ required: []
563
+ };
564
+ const baseProperties = baseSchema.type === "object" && baseSchema.properties ? baseSchema.properties : {};
565
+ const baseRequired = baseSchema.type === "object" && Array.isArray(baseSchema.required) ? baseSchema.required : [];
566
+ const updatedProperties = updateRefPaths(baseProperties, toolName);
567
+ depGroups[toolName] = {
568
+ type: "object",
569
+ description: tool.description,
570
+ properties: updatedProperties,
571
+ required: [
572
+ ...baseRequired
573
+ ],
574
+ additionalProperties: false
575
+ };
576
+ });
577
+ return depGroups;
578
+ }
579
+ function registerGlobalTools(globalToolNames, tools, server) {
580
+ globalToolNames.forEach((toolId) => {
581
+ const tool = tools[toolId];
582
+ if (!tool) {
583
+ throw new Error(`Global tool ${toolId} not found in registry, available: ${Object.keys(tools).join(", ")}`);
584
+ }
585
+ server.tool(toolId, tool.description || "No description available", jsonSchema(tool.inputSchema), tool.execute);
586
+ });
587
+ }
588
+ var init_compose_helpers = __esm({
589
+ "../__mcpc__core_latest/node_modules/@mcpc/core/src/utils/compose-helpers.js"() {
590
+ init_schema2();
591
+ init_schema();
592
+ }
593
+ });
594
+
595
+ // ../__mcpc__core_latest/node_modules/@mcpc/core/src/compose.js
596
+ init_schema();
597
+ import { CallToolRequestSchema, ListToolsRequestSchema, SetLevelRequestSchema } from "@modelcontextprotocol/sdk/types.js";
150
598
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
151
599
 
152
- // ../__mcpc__core_0.2.0-beta.10/node_modules/@jsr/mcpc__utils/src/json.js
600
+ // ../__mcpc__core_latest/node_modules/@jsr/mcpc__utils/src/json.js
153
601
  import { jsonrepair } from "jsonrepair";
602
+ function stripMarkdownAndText(text) {
603
+ text = text.trim();
604
+ text = text.replace(/^```(?:json)?\s*\n?/i, "");
605
+ text = text.replace(/\n?```\s*$/, "");
606
+ text = text.replace(/^(?:here is|here's|response|result|output|json):\s*/i, "");
607
+ const jsonMatch = text.match(/(\{[\s\S]*\}|\[[\s\S]*\])/);
608
+ if (jsonMatch) {
609
+ text = jsonMatch[1];
610
+ }
611
+ return text.trim();
612
+ }
154
613
  function parseJSON(text, throwError) {
155
614
  try {
156
615
  return JSON.parse(text);
157
616
  } catch (_error) {
158
617
  try {
159
- const repairedText = jsonrepair(text);
160
- console.warn(`Failed to parse JSON, attempting to repair, result: ${text}`);
161
- if (throwError) {
162
- throw _error;
618
+ const cleanedText = stripMarkdownAndText(text);
619
+ try {
620
+ return JSON.parse(cleanedText);
621
+ } catch {
622
+ const repairedText = jsonrepair(cleanedText);
623
+ console.warn(`Failed to parse JSON, cleaned and repaired. Original: ${text.slice(0, 100)}...`);
624
+ return JSON.parse(repairedText);
163
625
  }
164
- return JSON.parse(repairedText);
165
- } catch {
626
+ } catch (_repairError) {
166
627
  if (throwError) {
167
- throw new Error("Failed to parse repaired JSON");
628
+ throw new Error(`Failed to parse JSON after cleanup and repair. Original error: ${_error instanceof Error ? _error.message : String(_error)}`);
168
629
  }
169
630
  return null;
170
631
  }
171
632
  }
172
633
  }
173
634
 
174
- // ../__mcpc__core_0.2.0-beta.10/node_modules/@jsr/mcpc__utils/src/ai.js
635
+ // ../__mcpc__core_latest/node_modules/@jsr/mcpc__utils/src/ai.js
175
636
  var p = (template, options = {}) => {
176
637
  const { missingVariableHandling = "warn" } = options;
177
638
  const names = /* @__PURE__ */ new Set();
@@ -207,7 +668,7 @@ var p = (template, options = {}) => {
207
668
  };
208
669
  };
209
670
 
210
- // ../__mcpc__core_0.2.0-beta.10/node_modules/@jsr/mcpc__utils/src/tool-tags.js
671
+ // ../__mcpc__core_latest/node_modules/@jsr/mcpc__utils/src/tool-tags.js
211
672
  import { load } from "cheerio";
212
673
  function parseTags(htmlString, tags) {
213
674
  const $ = load(htmlString, {
@@ -226,10 +687,10 @@ function parseTags(htmlString, tags) {
226
687
  };
227
688
  }
228
689
 
229
- // ../__mcpc__core_0.2.0-beta.10/node_modules/@jsr/mcpc__utils/src/transport/sse.js
690
+ // ../__mcpc__core_latest/node_modules/@jsr/mcpc__utils/src/transport/sse.js
230
691
  import { JSONRPCMessageSchema } from "@modelcontextprotocol/sdk/types.js";
231
692
 
232
- // ../__mcpc__core_0.2.0-beta.10/node_modules/@jsr/std__http/server_sent_event_stream.js
693
+ // ../__mcpc__core_latest/node_modules/@jsr/std__http/server_sent_event_stream.js
233
694
  var NEWLINE_REGEXP = /\r\n|\r|\n/;
234
695
  var encoder = new TextEncoder();
235
696
  function assertHasNoNewline(value, varName, errPrefix) {
@@ -267,13 +728,13 @@ var ServerSentEventStream = class extends TransformStream {
267
728
  }
268
729
  };
269
730
 
270
- // ../__mcpc__core_0.2.0-beta.10/node_modules/@mcpc/core/src/utils/common/mcp.js
731
+ // ../__mcpc__core_latest/node_modules/@mcpc/core/src/utils/common/mcp.js
271
732
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
272
733
  import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
273
734
  import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
274
735
  import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
275
736
 
276
- // ../__mcpc__core_0.2.0-beta.10/node_modules/@mcpc/core/src/utils/common/registory.js
737
+ // ../__mcpc__core_latest/node_modules/@mcpc/core/src/utils/common/registory.js
277
738
  function connectToSmitheryServer(smitheryConfig) {
278
739
  const serverUrl = new URL(smitheryConfig.deploymentUrl);
279
740
  serverUrl.searchParams.set("config", btoa(JSON.stringify(smitheryConfig.config)));
@@ -298,7 +759,7 @@ function smitheryToolNameCompatibale(name, scope) {
298
759
  };
299
760
  }
300
761
 
301
- // ../__mcpc__core_0.2.0-beta.10/node_modules/@mcpc/core/src/utils/common/mcp.js
762
+ // ../__mcpc__core_latest/node_modules/@mcpc/core/src/utils/common/mcp.js
302
763
  import { cwd } from "node:process";
303
764
  import process2 from "node:process";
304
765
  import { createHash } from "node:crypto";
@@ -461,46 +922,14 @@ async function composeMcpDepTools(mcpConfig, filterIn) {
461
922
  };
462
923
  }
463
924
 
464
- // ../__mcpc__core_0.2.0-beta.10/node_modules/@mcpc/core/src/utils/common/schema.js
465
- import traverse from "json-schema-traverse";
466
- function updateRefPaths(schema, wrapperPath) {
467
- if (!schema || typeof schema !== "object") {
468
- return schema;
469
- }
470
- if (!wrapperPath || typeof wrapperPath !== "string") {
471
- throw new Error("wrapperPath must be a non-empty string");
472
- }
473
- const clonedSchema = JSON.parse(JSON.stringify(schema));
474
- try {
475
- traverse(clonedSchema, {
476
- allKeys: true,
477
- cb: function(schemaNode, _jsonPtr, _rootSchema, _parentJsonPtr, _parentKeyword, _parentSchema, _keyIndex) {
478
- if (schemaNode && typeof schemaNode === "object" && schemaNode.$ref) {
479
- const ref = schemaNode.$ref;
480
- if (ref.startsWith("#/properties/")) {
481
- const relativePath = ref.substring(13);
482
- schemaNode.$ref = `#/properties/${wrapperPath}/properties/${relativePath}`;
483
- } else if (ref === "#") {
484
- schemaNode.$ref = `#/properties/${wrapperPath}`;
485
- }
486
- }
487
- }
488
- });
489
- } catch (error) {
490
- console.warn(`Failed to traverse schema for path "${wrapperPath}":`, error);
491
- return clonedSchema;
492
- }
493
- return clonedSchema;
494
- }
495
-
496
- // ../__mcpc__core_0.2.0-beta.10/node_modules/@mcpc/core/src/executors/agentic/agentic-tool-registrar.js
497
- import { jsonSchema } from "ai";
925
+ // ../__mcpc__core_latest/node_modules/@mcpc/core/src/executors/agentic/agentic-tool-registrar.js
926
+ init_schema();
498
927
 
499
- // ../__mcpc__core_0.2.0-beta.10/node_modules/@mcpc/core/src/utils/common/config.js
928
+ // ../__mcpc__core_latest/node_modules/@mcpc/core/src/utils/common/config.js
500
929
  import process3 from "node:process";
501
930
  var GEMINI_PREFERRED_FORMAT = process3.env.GEMINI_PREFERRED_FORMAT === "0" ? false : true;
502
931
 
503
- // ../__mcpc__core_0.2.0-beta.10/node_modules/@mcpc/core/src/utils/common/json.js
932
+ // ../__mcpc__core_latest/node_modules/@mcpc/core/src/utils/common/json.js
504
933
  import { jsonrepair as jsonrepair2 } from "jsonrepair";
505
934
  import { inspect } from "node:util";
506
935
  function parseJSON2(text, throwError) {
@@ -536,7 +965,7 @@ function optionalObject(obj, condition) {
536
965
  return {};
537
966
  }
538
967
 
539
- // ../__mcpc__core_0.2.0-beta.10/node_modules/@mcpc/core/src/utils/common/provider.js
968
+ // ../__mcpc__core_latest/node_modules/@mcpc/core/src/utils/common/provider.js
540
969
  var createGoogleCompatibleJSONSchema = (schema) => {
541
970
  if (!GEMINI_PREFERRED_FORMAT) {
542
971
  return schema;
@@ -560,7 +989,7 @@ var createGoogleCompatibleJSONSchema = (schema) => {
560
989
  return removeAdditionalProperties(cleanSchema);
561
990
  };
562
991
 
563
- // ../__mcpc__core_0.2.0-beta.10/node_modules/@mcpc/core/src/prompts/index.js
992
+ // ../__mcpc__core_latest/node_modules/@mcpc/core/src/prompts/index.js
564
993
  var SystemPrompts = {
565
994
  /**
566
995
  * Base system prompt for autonomous MCP execution
@@ -902,10 +1331,81 @@ ${JSON.stringify(steps, null, 2)}`;
902
1331
  }
903
1332
  };
904
1333
 
905
- // ../__mcpc__core_0.2.0-beta.10/node_modules/@mcpc/core/src/executors/agentic/agentic-executor.js
1334
+ // ../__mcpc__core_latest/node_modules/@mcpc/core/src/executors/agentic/agentic-executor.js
906
1335
  import { Ajv } from "ajv";
907
1336
  import { AggregateAjvError } from "@segment/ajv-human-errors";
908
1337
  import addFormats from "ajv-formats";
1338
+ init_logger();
1339
+
1340
+ // ../__mcpc__core_latest/node_modules/@mcpc/core/src/utils/tracing.js
1341
+ import { context, SpanStatusCode, trace } from "@opentelemetry/api";
1342
+ import { NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
1343
+ import { BatchSpanProcessor, ConsoleSpanExporter, SimpleSpanProcessor } from "@opentelemetry/sdk-trace-base";
1344
+ import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
1345
+ import { Resource } from "@opentelemetry/resources";
1346
+ import { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION } from "@opentelemetry/semantic-conventions";
1347
+ var tracerProvider = null;
1348
+ var tracer = null;
1349
+ var isInitialized = false;
1350
+ function initializeTracing(config = {}) {
1351
+ if (isInitialized) {
1352
+ return;
1353
+ }
1354
+ const { enabled = true, serviceName = "mcpc-sampling", serviceVersion = "0.2.0", exportTo = "console", otlpEndpoint = "http://localhost:4318/v1/traces", otlpHeaders = {} } = config;
1355
+ if (!enabled) {
1356
+ isInitialized = true;
1357
+ return;
1358
+ }
1359
+ const resource = Resource.default().merge(new Resource({
1360
+ [ATTR_SERVICE_NAME]: serviceName,
1361
+ [ATTR_SERVICE_VERSION]: serviceVersion
1362
+ }));
1363
+ tracerProvider = new NodeTracerProvider({
1364
+ resource
1365
+ });
1366
+ if (exportTo === "console") {
1367
+ tracerProvider.addSpanProcessor(new SimpleSpanProcessor(new ConsoleSpanExporter()));
1368
+ } else if (exportTo === "otlp") {
1369
+ const otlpExporter = new OTLPTraceExporter({
1370
+ url: otlpEndpoint,
1371
+ headers: otlpHeaders
1372
+ });
1373
+ tracerProvider.addSpanProcessor(new BatchSpanProcessor(otlpExporter));
1374
+ }
1375
+ tracerProvider.register();
1376
+ tracer = trace.getTracer(serviceName, serviceVersion);
1377
+ isInitialized = true;
1378
+ }
1379
+ function getTracer() {
1380
+ if (!isInitialized) {
1381
+ initializeTracing();
1382
+ }
1383
+ return tracer;
1384
+ }
1385
+ function startSpan(name, attributes, parent) {
1386
+ const tracer2 = getTracer();
1387
+ const ctx = parent ? trace.setSpan(context.active(), parent) : void 0;
1388
+ return tracer2.startSpan(name, {
1389
+ attributes
1390
+ }, ctx);
1391
+ }
1392
+ function endSpan(span, error) {
1393
+ if (error) {
1394
+ span.setStatus({
1395
+ code: SpanStatusCode.ERROR,
1396
+ message: error.message
1397
+ });
1398
+ span.recordException(error);
1399
+ } else {
1400
+ span.setStatus({
1401
+ code: SpanStatusCode.OK
1402
+ });
1403
+ }
1404
+ span.end();
1405
+ }
1406
+
1407
+ // ../__mcpc__core_latest/node_modules/@mcpc/core/src/executors/agentic/agentic-executor.js
1408
+ import process4 from "node:process";
909
1409
  var ajv = new Ajv({
910
1410
  allErrors: true,
911
1411
  verbose: true
@@ -918,6 +1418,8 @@ var AgenticExecutor = class {
918
1418
  server;
919
1419
  ACTION_KEY;
920
1420
  NEXT_ACTION_KEY;
1421
+ logger;
1422
+ tracingEnabled;
921
1423
  constructor(name, allToolNames, toolNameToDetailList, server, ACTION_KEY = "action", NEXT_ACTION_KEY = "nextAction") {
922
1424
  this.name = name;
923
1425
  this.allToolNames = allToolNames;
@@ -925,93 +1427,216 @@ var AgenticExecutor = class {
925
1427
  this.server = server;
926
1428
  this.ACTION_KEY = ACTION_KEY;
927
1429
  this.NEXT_ACTION_KEY = NEXT_ACTION_KEY;
928
- }
929
- async execute(args, schema) {
930
- const validationResult = this.validate(args, schema);
931
- if (!validationResult.valid) {
932
- return {
933
- content: [
934
- {
935
- type: "text",
936
- text: CompiledPrompts.errorResponse({
937
- errorMessage: validationResult.error || "Validation failed"
938
- })
939
- }
940
- ],
941
- isError: true
942
- };
943
- }
944
- const actionName = args[this.ACTION_KEY];
945
- const currentTool = this.toolNameToDetailList.find(([name, _detail]) => name === actionName)?.[1];
946
- if (currentTool) {
947
- const nextAction = args[this.NEXT_ACTION_KEY];
948
- const currentResult = await currentTool.execute({
949
- ...args[actionName]
950
- });
951
- if (args[nextAction]) {
952
- currentResult?.content?.push({
953
- type: "text",
954
- text: CompiledPrompts.actionSuccess({
955
- toolName: this.name,
956
- nextAction,
957
- currentAction: actionName
958
- })
959
- });
960
- } else {
961
- currentResult?.content?.push({
962
- type: "text",
963
- text: CompiledPrompts.planningPrompt({
964
- currentAction: actionName
965
- })
1430
+ this.tracingEnabled = false;
1431
+ this.logger = createLogger(`mcpc.agentic.${name}`, server);
1432
+ try {
1433
+ this.tracingEnabled = process4.env.MCPC_TRACING_ENABLED === "true";
1434
+ if (this.tracingEnabled) {
1435
+ initializeTracing({
1436
+ enabled: true,
1437
+ serviceName: `mcpc-agentic-${name}`,
1438
+ exportTo: process4.env.MCPC_TRACING_EXPORT ?? "otlp",
1439
+ otlpEndpoint: process4.env.MCPC_TRACING_OTLP_ENDPOINT ?? "http://localhost:4318/v1/traces"
966
1440
  });
967
1441
  }
968
- return currentResult;
1442
+ } catch {
1443
+ this.tracingEnabled = false;
969
1444
  }
970
- if (this.allToolNames.includes(actionName)) {
971
- try {
972
- const result = await this.server.callTool(actionName, args[actionName]);
973
- const nextAction = args[this.NEXT_ACTION_KEY];
974
- const callToolResult = result ?? {
975
- content: []
976
- };
977
- if (nextAction && this.allToolNames.includes(nextAction)) {
978
- callToolResult.content.push({
979
- type: "text",
980
- text: CompiledPrompts.actionSuccess({
981
- toolName: this.name,
982
- nextAction,
983
- currentAction: actionName
984
- })
985
- });
986
- } else {
987
- callToolResult.content.push({
988
- type: "text",
989
- text: CompiledPrompts.planningPrompt({
990
- currentAction: actionName
991
- })
1445
+ }
1446
+ async execute(args, schema) {
1447
+ const executeSpan = this.tracingEnabled ? startSpan("mcpc.agentic_execute", {
1448
+ agent: this.name,
1449
+ action: String(args[this.ACTION_KEY] ?? "unknown"),
1450
+ nextAction: String(args[this.NEXT_ACTION_KEY] ?? "none"),
1451
+ args: JSON.stringify(args)
1452
+ }) : null;
1453
+ try {
1454
+ const validationResult = this.validate(args, schema);
1455
+ if (!validationResult.valid) {
1456
+ if (executeSpan) {
1457
+ executeSpan.setAttributes({
1458
+ validationError: true,
1459
+ errorMessage: validationResult.error || "Validation failed"
992
1460
  });
1461
+ endSpan(executeSpan);
993
1462
  }
994
- return callToolResult;
995
- } catch (error) {
1463
+ this.logger.warning({
1464
+ message: "Validation failed",
1465
+ action: args[this.ACTION_KEY],
1466
+ error: validationResult.error
1467
+ });
996
1468
  return {
997
1469
  content: [
998
1470
  {
999
1471
  type: "text",
1000
- text: `Error executing internal tool ${actionName}: ${error instanceof Error ? error.message : String(error)}`
1472
+ text: CompiledPrompts.errorResponse({
1473
+ errorMessage: validationResult.error || "Validation failed"
1474
+ })
1001
1475
  }
1002
1476
  ],
1003
1477
  isError: true
1004
1478
  };
1005
1479
  }
1006
- }
1007
- return {
1008
- content: [
1009
- {
1010
- type: "text",
1011
- text: CompiledPrompts.completionMessage()
1480
+ const actionName = args[this.ACTION_KEY];
1481
+ if (executeSpan && actionName) {
1482
+ try {
1483
+ const safeAction = String(actionName).replace(/\s+/g, "_");
1484
+ if (typeof executeSpan.updateName === "function") {
1485
+ executeSpan.updateName(`mcpc.agentic_execute.${safeAction}`);
1486
+ }
1487
+ } catch {
1012
1488
  }
1013
- ]
1014
- };
1489
+ }
1490
+ const currentTool = this.toolNameToDetailList.find(([name, _detail]) => name === actionName)?.[1];
1491
+ if (currentTool) {
1492
+ const nextAction = args[this.NEXT_ACTION_KEY];
1493
+ if (executeSpan) {
1494
+ executeSpan.setAttributes({
1495
+ toolType: "external",
1496
+ actionName,
1497
+ nextAction: nextAction || "none"
1498
+ });
1499
+ }
1500
+ this.logger.debug({
1501
+ message: "Executing external tool",
1502
+ action: actionName,
1503
+ nextAction
1504
+ });
1505
+ const currentResult = await currentTool.execute({
1506
+ ...args[actionName]
1507
+ });
1508
+ if (args[nextAction]) {
1509
+ currentResult?.content?.push({
1510
+ type: "text",
1511
+ text: CompiledPrompts.actionSuccess({
1512
+ toolName: this.name,
1513
+ nextAction,
1514
+ currentAction: actionName
1515
+ })
1516
+ });
1517
+ } else {
1518
+ currentResult?.content?.push({
1519
+ type: "text",
1520
+ text: CompiledPrompts.planningPrompt({
1521
+ currentAction: actionName
1522
+ })
1523
+ });
1524
+ }
1525
+ if (executeSpan) {
1526
+ executeSpan.setAttributes({
1527
+ success: true,
1528
+ isError: !!currentResult.isError,
1529
+ resultContentLength: currentResult.content?.length || 0,
1530
+ hasNextAction: !!args[nextAction],
1531
+ toolResult: JSON.stringify(currentResult)
1532
+ });
1533
+ endSpan(executeSpan);
1534
+ }
1535
+ return currentResult;
1536
+ }
1537
+ if (this.allToolNames.includes(actionName)) {
1538
+ if (executeSpan) {
1539
+ executeSpan.setAttributes({
1540
+ toolType: "internal",
1541
+ actionName
1542
+ });
1543
+ }
1544
+ this.logger.debug({
1545
+ message: "Executing internal tool",
1546
+ action: actionName
1547
+ });
1548
+ try {
1549
+ const result = await this.server.callTool(actionName, args[actionName]);
1550
+ const nextAction = args[this.NEXT_ACTION_KEY];
1551
+ const callToolResult = result ?? {
1552
+ content: []
1553
+ };
1554
+ if (nextAction && this.allToolNames.includes(nextAction)) {
1555
+ callToolResult.content.push({
1556
+ type: "text",
1557
+ text: CompiledPrompts.actionSuccess({
1558
+ toolName: this.name,
1559
+ nextAction,
1560
+ currentAction: actionName
1561
+ })
1562
+ });
1563
+ } else {
1564
+ callToolResult.content.push({
1565
+ type: "text",
1566
+ text: CompiledPrompts.planningPrompt({
1567
+ currentAction: actionName
1568
+ })
1569
+ });
1570
+ }
1571
+ if (executeSpan) {
1572
+ executeSpan.setAttributes({
1573
+ success: true,
1574
+ isError: !!callToolResult.isError,
1575
+ resultContentLength: callToolResult.content?.length || 0,
1576
+ hasNextAction: !!(nextAction && this.allToolNames.includes(nextAction)),
1577
+ toolResult: JSON.stringify(callToolResult)
1578
+ });
1579
+ endSpan(executeSpan);
1580
+ }
1581
+ return callToolResult;
1582
+ } catch (error) {
1583
+ if (executeSpan) {
1584
+ endSpan(executeSpan, error);
1585
+ }
1586
+ this.logger.error({
1587
+ message: "Error executing internal tool",
1588
+ action: actionName,
1589
+ error: String(error)
1590
+ });
1591
+ return {
1592
+ content: [
1593
+ {
1594
+ type: "text",
1595
+ text: `Error executing internal tool ${actionName}: ${error instanceof Error ? error.message : String(error)}`
1596
+ }
1597
+ ],
1598
+ isError: true
1599
+ };
1600
+ }
1601
+ }
1602
+ if (executeSpan) {
1603
+ executeSpan.setAttributes({
1604
+ toolType: "not_found",
1605
+ actionName: actionName || "unknown",
1606
+ completion: true
1607
+ });
1608
+ endSpan(executeSpan);
1609
+ }
1610
+ this.logger.debug({
1611
+ message: "Tool not found, returning completion message",
1612
+ action: actionName
1613
+ });
1614
+ return {
1615
+ content: [
1616
+ {
1617
+ type: "text",
1618
+ text: CompiledPrompts.completionMessage()
1619
+ }
1620
+ ]
1621
+ };
1622
+ } catch (error) {
1623
+ if (executeSpan) {
1624
+ endSpan(executeSpan, error);
1625
+ }
1626
+ this.logger.error({
1627
+ message: "Unexpected error in execute",
1628
+ error: String(error)
1629
+ });
1630
+ return {
1631
+ content: [
1632
+ {
1633
+ type: "text",
1634
+ text: `Unexpected error: ${error instanceof Error ? error.message : String(error)}`
1635
+ }
1636
+ ],
1637
+ isError: true
1638
+ };
1639
+ }
1015
1640
  }
1016
1641
  // Validate arguments using JSON schema
1017
1642
  validate(args, schema) {
@@ -1034,7 +1659,7 @@ var AgenticExecutor = class {
1034
1659
  }
1035
1660
  };
1036
1661
 
1037
- // ../__mcpc__core_0.2.0-beta.10/node_modules/@jsr/es-toolkit__es-toolkit/src/function/partial.js
1662
+ // ../__mcpc__core_latest/node_modules/@jsr/es-toolkit__es-toolkit/src/function/partial.js
1038
1663
  function partial(func, ...partialArgs) {
1039
1664
  return partialImpl(func, placeholderSymbol, ...partialArgs);
1040
1665
  }
@@ -1053,7 +1678,7 @@ function partialImpl(func, placeholder, ...partialArgs) {
1053
1678
  var placeholderSymbol = Symbol("partial.placeholder");
1054
1679
  partial.placeholder = placeholderSymbol;
1055
1680
 
1056
- // ../__mcpc__core_0.2.0-beta.10/node_modules/@jsr/es-toolkit__es-toolkit/src/function/partialRight.js
1681
+ // ../__mcpc__core_latest/node_modules/@jsr/es-toolkit__es-toolkit/src/function/partialRight.js
1057
1682
  function partialRight(func, ...partialArgs) {
1058
1683
  return partialRightImpl(func, placeholderSymbol2, ...partialArgs);
1059
1684
  }
@@ -1074,10 +1699,10 @@ function partialRightImpl(func, placeholder, ...partialArgs) {
1074
1699
  var placeholderSymbol2 = Symbol("partialRight.placeholder");
1075
1700
  partialRight.placeholder = placeholderSymbol2;
1076
1701
 
1077
- // ../__mcpc__core_0.2.0-beta.10/node_modules/@jsr/es-toolkit__es-toolkit/src/function/retry.js
1702
+ // ../__mcpc__core_latest/node_modules/@jsr/es-toolkit__es-toolkit/src/function/retry.js
1078
1703
  var DEFAULT_RETRIES = Number.POSITIVE_INFINITY;
1079
1704
 
1080
- // ../__mcpc__core_0.2.0-beta.10/node_modules/@jsr/es-toolkit__es-toolkit/src/object/pick.js
1705
+ // ../__mcpc__core_latest/node_modules/@jsr/es-toolkit__es-toolkit/src/object/pick.js
1081
1706
  function pick(obj, keys) {
1082
1707
  const result = {};
1083
1708
  for (let i = 0; i < keys.length; i++) {
@@ -1089,7 +1714,7 @@ function pick(obj, keys) {
1089
1714
  return result;
1090
1715
  }
1091
1716
 
1092
- // ../__mcpc__core_0.2.0-beta.10/node_modules/@jsr/es-toolkit__es-toolkit/src/string/deburr.js
1717
+ // ../__mcpc__core_latest/node_modules/@jsr/es-toolkit__es-toolkit/src/string/deburr.js
1093
1718
  var deburrMap = new Map(
1094
1719
  // eslint-disable-next-line no-restricted-syntax
1095
1720
  Object.entries({
@@ -1125,7 +1750,7 @@ var deburrMap = new Map(
1125
1750
  })
1126
1751
  );
1127
1752
 
1128
- // ../__mcpc__core_0.2.0-beta.10/node_modules/@mcpc/core/src/factories/args-def-factory.js
1753
+ // ../__mcpc__core_latest/node_modules/@mcpc/core/src/factories/args-def-factory.js
1129
1754
  var DECISION_OPTIONS = {
1130
1755
  RETRY: "retry",
1131
1756
  PROCEED: "proceed",
@@ -1252,10 +1877,16 @@ Workflow step definitions - provide ONLY on initial call.
1252
1877
  userRequest: {
1253
1878
  type: "string",
1254
1879
  description: "The task or request that should be completed autonomously by the agentic system using available tools"
1880
+ },
1881
+ context: {
1882
+ type: "object",
1883
+ 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.",
1884
+ additionalProperties: true
1255
1885
  }
1256
1886
  },
1257
1887
  required: [
1258
- "userRequest"
1888
+ "userRequest",
1889
+ "context"
1259
1890
  ]
1260
1891
  };
1261
1892
  },
@@ -1350,11 +1981,12 @@ NOTE: The \`steps\` has been predefined` : `**You MUST execute this tool with fo
1350
1981
  };
1351
1982
  }
1352
1983
 
1353
- // ../__mcpc__core_0.2.0-beta.10/node_modules/@mcpc/core/src/executors/sampling/base-sampling-executor.js
1984
+ // ../__mcpc__core_latest/node_modules/@mcpc/core/src/executors/sampling/base-sampling-executor.js
1354
1985
  import { Ajv as Ajv2 } from "ajv";
1355
1986
  import { AggregateAjvError as AggregateAjvError2 } from "@segment/ajv-human-errors";
1356
1987
  import addFormats2 from "ajv-formats";
1357
- import { inspect as inspect2 } from "node:util";
1988
+ init_logger();
1989
+ import process5 from "node:process";
1358
1990
  var ajv2 = new Ajv2({
1359
1991
  allErrors: true,
1360
1992
  verbose: true
@@ -1369,6 +2001,9 @@ var BaseSamplingExecutor = class {
1369
2001
  conversationHistory;
1370
2002
  maxIterations;
1371
2003
  currentIteration;
2004
+ logger;
2005
+ tracingEnabled;
2006
+ summarize;
1372
2007
  constructor(name, description, allToolNames, toolNameToDetailList, server, config) {
1373
2008
  this.name = name;
1374
2009
  this.description = description;
@@ -1376,57 +2011,158 @@ var BaseSamplingExecutor = class {
1376
2011
  this.toolNameToDetailList = toolNameToDetailList;
1377
2012
  this.server = server;
1378
2013
  this.conversationHistory = [];
1379
- this.maxIterations = 33;
2014
+ this.maxIterations = 55;
1380
2015
  this.currentIteration = 0;
2016
+ this.tracingEnabled = false;
2017
+ this.summarize = true;
1381
2018
  if (config?.maxIterations) {
1382
2019
  this.maxIterations = config.maxIterations;
1383
2020
  }
2021
+ if (config?.summarize !== void 0) {
2022
+ this.summarize = config.summarize;
2023
+ }
2024
+ this.logger = createLogger(`mcpc.sampling.${name}`, server);
2025
+ try {
2026
+ const tracingConfig = {
2027
+ enabled: process5.env.MCPC_TRACING_ENABLED === "true",
2028
+ serviceName: `mcpc-sampling-${name}`,
2029
+ exportTo: process5.env.MCPC_TRACING_EXPORT ?? "otlp",
2030
+ otlpEndpoint: process5.env.MCPC_TRACING_OTLP_ENDPOINT ?? "http://localhost:4318/v1/traces"
2031
+ };
2032
+ this.tracingEnabled = tracingConfig.enabled;
2033
+ if (this.tracingEnabled) {
2034
+ initializeTracing(tracingConfig);
2035
+ }
2036
+ } catch {
2037
+ this.tracingEnabled = false;
2038
+ }
1384
2039
  }
1385
2040
  async runSamplingLoop(systemPrompt, schema, state) {
1386
- this.conversationHistory = [];
2041
+ this.conversationHistory = [
2042
+ {
2043
+ role: "user",
2044
+ content: {
2045
+ type: "text",
2046
+ text: 'Return ONLY raw JSON (no code fences or explanations). The JSON MUST include action and decision. Example: {"action":"<tool>","decision":"proceed|complete","<tool>":{}}'
2047
+ }
2048
+ }
2049
+ ];
2050
+ const loopSpan = this.tracingEnabled ? startSpan("mcpc.sampling_loop", {
2051
+ agent: this.name,
2052
+ maxIterations: this.maxIterations,
2053
+ systemPrompt: systemPrompt()
2054
+ }) : null;
1387
2055
  try {
1388
2056
  for (this.currentIteration = 0; this.currentIteration < this.maxIterations; this.currentIteration++) {
1389
- const response = await this.server.createMessage({
1390
- systemPrompt: systemPrompt(),
1391
- messages: this.conversationHistory,
1392
- maxTokens: Number.MAX_SAFE_INTEGER
1393
- });
1394
- const responseContent = response.content.text || "{}";
1395
- let parsedData;
2057
+ let iterationSpan = null;
1396
2058
  try {
1397
- parsedData = parseJSON(responseContent.trim(), true);
1398
- } catch (parseError) {
1399
- this.addParsingErrorToHistory(responseContent, parseError);
1400
- continue;
1401
- }
1402
- if (parsedData) {
1403
- this.conversationHistory.push({
1404
- role: "assistant",
1405
- content: {
1406
- type: "text",
1407
- text: JSON.stringify(parsedData, null, 2)
1408
- }
2059
+ const response = await this.server.createMessage({
2060
+ systemPrompt: systemPrompt(),
2061
+ messages: this.conversationHistory,
2062
+ maxTokens: 55e3
1409
2063
  });
1410
- }
1411
- const result = await this.processAction(parsedData, schema, state);
1412
- this.logIterationProgress(parsedData, result);
1413
- if (result.isError) {
1414
- this.conversationHistory.push({
1415
- role: "user",
1416
- content: {
1417
- type: "text",
1418
- text: result.content[0].text
2064
+ const responseContent = response.content.text || "{}";
2065
+ const model = response.model;
2066
+ const stopReason = response.stopReason;
2067
+ const role = response.role;
2068
+ let parsedData;
2069
+ try {
2070
+ parsedData = parseJSON(responseContent.trim(), true);
2071
+ } catch (parseError) {
2072
+ iterationSpan = this.tracingEnabled ? startSpan("mcpc.sampling_iteration.parse_error", {
2073
+ iteration: this.currentIteration + 1,
2074
+ agent: this.name,
2075
+ error: String(parseError),
2076
+ maxIterations: this.maxIterations
2077
+ }, loopSpan ?? void 0) : null;
2078
+ this.addParsingErrorToHistory(responseContent, parseError);
2079
+ if (iterationSpan) endSpan(iterationSpan);
2080
+ continue;
2081
+ }
2082
+ if (parsedData) {
2083
+ this.conversationHistory.push({
2084
+ role: "assistant",
2085
+ content: {
2086
+ type: "text",
2087
+ text: JSON.stringify(parsedData, null, 2)
2088
+ }
2089
+ });
2090
+ }
2091
+ const action = parsedData["action"];
2092
+ const actionStr = action && typeof action === "string" ? String(action) : "unknown_action";
2093
+ const spanName = `mcpc.sampling_iteration.${actionStr}`;
2094
+ iterationSpan = this.tracingEnabled ? startSpan(spanName, {
2095
+ iteration: this.currentIteration + 1,
2096
+ agent: this.name,
2097
+ action: actionStr,
2098
+ systemPrompt: systemPrompt(),
2099
+ maxTokens: String(Number.MAX_SAFE_INTEGER),
2100
+ maxIterations: this.maxIterations,
2101
+ messages: JSON.stringify(this.conversationHistory)
2102
+ }, loopSpan ?? void 0) : null;
2103
+ if (!action || typeof parsedData["decision"] !== "string") {
2104
+ this.conversationHistory.push({
2105
+ role: "user",
2106
+ content: {
2107
+ type: "text",
2108
+ text: 'Required fields missing: action or decision. Return ONLY raw JSON, no code fences or explanations. Example: {"action":"<tool>","decision":"proceed|complete","<tool>":{}}'
2109
+ }
2110
+ });
2111
+ if (iterationSpan) endSpan(iterationSpan);
2112
+ continue;
2113
+ }
2114
+ const result = await this.processAction(parsedData, schema, state, loopSpan);
2115
+ this.logIterationProgress(parsedData, result, model, stopReason, role);
2116
+ if (iterationSpan) {
2117
+ let rawJson = "{}";
2118
+ try {
2119
+ rawJson = parsedData ? JSON.stringify(parsedData) : "{}";
2120
+ } catch {
1419
2121
  }
1420
- });
1421
- continue;
1422
- }
1423
- if (result.isComplete) {
1424
- return result;
2122
+ const attr = {
2123
+ isError: !!result.isError,
2124
+ isComplete: !!result.isComplete,
2125
+ iteration: this.currentIteration + 1,
2126
+ maxIterations: this.maxIterations,
2127
+ parsed: rawJson,
2128
+ action: typeof action === "string" ? action : String(action),
2129
+ samplingResponse: responseContent,
2130
+ toolResult: JSON.stringify(result),
2131
+ model,
2132
+ role
2133
+ };
2134
+ if (stopReason) {
2135
+ attr.stopReason = stopReason;
2136
+ }
2137
+ iterationSpan.setAttributes(attr);
2138
+ }
2139
+ if (result.isError) {
2140
+ this.conversationHistory.push({
2141
+ role: "user",
2142
+ content: {
2143
+ type: "text",
2144
+ text: result.content[0].text
2145
+ }
2146
+ });
2147
+ if (iterationSpan) endSpan(iterationSpan);
2148
+ continue;
2149
+ }
2150
+ if (result.isComplete) {
2151
+ if (iterationSpan) endSpan(iterationSpan);
2152
+ if (loopSpan) endSpan(loopSpan);
2153
+ return result;
2154
+ }
2155
+ if (iterationSpan) endSpan(iterationSpan);
2156
+ } catch (iterError) {
2157
+ if (iterationSpan) endSpan(iterationSpan, iterError);
2158
+ throw iterError;
1425
2159
  }
1426
2160
  }
1427
- return this.createMaxIterationsError();
2161
+ if (loopSpan) endSpan(loopSpan);
2162
+ return await this.createMaxIterationsError(loopSpan);
1428
2163
  } catch (error) {
1429
- return this.createExecutionError(error);
2164
+ if (loopSpan) endSpan(loopSpan, error);
2165
+ return await this.createExecutionError(error, loopSpan);
1430
2166
  }
1431
2167
  }
1432
2168
  addParsingErrorToHistory(responseText, parseError) {
@@ -1449,71 +2185,137 @@ Please respond with valid JSON.`
1449
2185
  }
1450
2186
  });
1451
2187
  }
1452
- createMaxIterationsError() {
1453
- const result = this.createCompletionResult(`Action argument validation failed: Execution reached maximum iterations (${this.maxIterations}). Please try with a more specific request or break down the task into smaller parts.`);
1454
- return {
1455
- ...result,
1456
- isError: true,
1457
- isComplete: false
1458
- };
2188
+ async createMaxIterationsError(parentSpan) {
2189
+ const result = await this.createCompletionResult(`Reached max iterations (${this.maxIterations}). Try a more specific request.`, parentSpan);
2190
+ result.isError = true;
2191
+ result.isComplete = false;
2192
+ return result;
1459
2193
  }
1460
- createExecutionError(error) {
1461
- const errorMessage = `Sampling execution error: ${error instanceof Error ? error.message : String(error)}`;
1462
- const result = this.createCompletionResult(errorMessage);
1463
- return {
1464
- ...result,
1465
- isError: true,
1466
- isComplete: false
1467
- };
2194
+ async createExecutionError(error, parentSpan) {
2195
+ const result = await this.createCompletionResult(`Execution error: ${error instanceof Error ? error.message : String(error)}`, parentSpan);
2196
+ result.isError = true;
2197
+ result.isComplete = false;
2198
+ return result;
1468
2199
  }
1469
- createCompletionResult(text) {
1470
- const conversationDetails = this.getConversationDetails();
2200
+ async createCompletionResult(text, parentSpan) {
2201
+ const summary = this.summarize ? await this.summarizeConversation(parentSpan) : this.formatConversation();
1471
2202
  return {
1472
2203
  content: [
1473
2204
  {
1474
2205
  type: "text",
1475
- text: `Task Completed
1476
- ${text}
2206
+ text: `${text}
2207
+
1477
2208
  **Execution Summary:**
1478
2209
  - Iterations used: ${this.currentIteration + 1}/${this.maxIterations}
1479
- - Agent: ${this.name}${conversationDetails}`
2210
+ - Agent: ${this.name}
2211
+ ${summary}`
1480
2212
  }
1481
2213
  ],
1482
2214
  isError: false,
1483
2215
  isComplete: true
1484
2216
  };
1485
2217
  }
1486
- getConversationDetails() {
2218
+ // Use LLM to create high-signal summary for parent agent
2219
+ async summarizeConversation(parentSpan) {
1487
2220
  if (this.conversationHistory.length === 0) {
1488
- return "\n\n**No conversation history available**";
2221
+ return "\n\n**No conversation history**";
1489
2222
  }
1490
- let details = "\n\n**Detailed Conversation History:**";
1491
- this.conversationHistory.forEach((message) => {
1492
- if (message.role === "assistant") {
1493
- try {
1494
- const parsed = JSON.parse(message.content.text);
1495
- details += "\n```json\n" + JSON.stringify(parsed, null, 2) + "\n```";
1496
- } catch {
1497
- details += "\n```\n" + message.content.text + "\n```";
2223
+ if (this.conversationHistory.length <= 3) {
2224
+ return this.formatConversation();
2225
+ }
2226
+ const summarizeSpan = this.tracingEnabled ? startSpan("mcpc.sampling_summarize", {
2227
+ agent: this.name,
2228
+ messageCount: this.conversationHistory.length
2229
+ }, parentSpan ?? void 0) : null;
2230
+ try {
2231
+ this.logger.debug({
2232
+ message: "Starting conversation summarization",
2233
+ messageCount: this.conversationHistory.length
2234
+ });
2235
+ const history = this.conversationHistory.map((msg, i) => {
2236
+ const prefix = `[${i + 1}] ${msg.role.toUpperCase()}`;
2237
+ return `${prefix}:
2238
+ ${msg.content.text}`;
2239
+ }).join("\n\n---\n\n");
2240
+ const response = await this.server.createMessage({
2241
+ systemPrompt: `Summarize this agent execution:
2242
+
2243
+ Final Decision: (include complete JSON if present)
2244
+ Key Findings: (most important)
2245
+ Actions Taken: (high-level flow)
2246
+ Errors/Warnings: (if any)
2247
+
2248
+ ${history}`,
2249
+ messages: [
2250
+ {
2251
+ role: "user",
2252
+ content: {
2253
+ type: "text",
2254
+ text: "Please provide a concise summary."
2255
+ }
2256
+ }
2257
+ ],
2258
+ maxTokens: 3e3
2259
+ });
2260
+ const summary = "\n\n" + response.content.text;
2261
+ this.logger.debug({
2262
+ message: "Summarization completed",
2263
+ summaryLength: summary.length
2264
+ });
2265
+ if (summarizeSpan) {
2266
+ summarizeSpan.setAttributes({
2267
+ summaryLength: summary.length,
2268
+ summary,
2269
+ success: true
2270
+ });
2271
+ endSpan(summarizeSpan);
2272
+ }
2273
+ return summary;
2274
+ } catch (error) {
2275
+ this.logger.warning({
2276
+ message: "Summarization failed, falling back to full history",
2277
+ error: String(error)
2278
+ });
2279
+ if (summarizeSpan) {
2280
+ endSpan(summarizeSpan, error);
2281
+ }
2282
+ return this.formatConversation();
2283
+ }
2284
+ }
2285
+ // Format full conversation history (for debugging)
2286
+ formatConversation() {
2287
+ if (this.conversationHistory.length === 0) {
2288
+ return "\n\n**No conversation history**";
2289
+ }
2290
+ const messages = this.conversationHistory.map((msg, i) => {
2291
+ const header = `### Message ${i + 1}: ${msg.role}`;
2292
+ try {
2293
+ const parsed = JSON.parse(msg.content.text);
2294
+ if (JSON.stringify(parsed).length < 100) {
2295
+ return `${header}
2296
+ ${JSON.stringify(parsed)}`;
1498
2297
  }
1499
- } else {
1500
- details += "\n```\n" + message.content.text + "\n```";
2298
+ return `${header}
2299
+ \`\`\`json
2300
+ ${JSON.stringify(parsed, null, 2)}
2301
+ \`\`\``;
2302
+ } catch {
2303
+ return `${header}
2304
+ ${msg.content.text}`;
1501
2305
  }
1502
2306
  });
1503
- return details;
2307
+ return "\n\n**Conversation History:**\n" + messages.join("\n\n");
1504
2308
  }
1505
- logIterationProgress(parsedData, result) {
1506
- console.log(`Iteration ${this.currentIteration + 1}/${this.maxIterations}:`, {
2309
+ logIterationProgress(parsedData, result, model, stopReason, role) {
2310
+ this.logger.debug({
2311
+ iteration: `${this.currentIteration + 1}/${this.maxIterations}`,
1507
2312
  parsedData,
1508
2313
  isError: result.isError,
1509
2314
  isComplete: result.isComplete,
1510
- result: inspect2(result, {
1511
- depth: 5,
1512
- maxArrayLength: 10,
1513
- breakLength: 120,
1514
- compact: true,
1515
- maxStringLength: 120
1516
- })
2315
+ model,
2316
+ stopReason,
2317
+ role,
2318
+ result
1517
2319
  });
1518
2320
  }
1519
2321
  injectJsonInstruction({ prompt, schema, schemaPrefix = "JSON schema:", schemaSuffix = `STRICT REQUIREMENTS:
@@ -1547,7 +2349,7 @@ VALID: {"key":"value"}` }) {
1547
2349
  }
1548
2350
  };
1549
2351
 
1550
- // ../__mcpc__core_0.2.0-beta.10/node_modules/@mcpc/core/src/executors/sampling/agentic-sampling-executor.js
2352
+ // ../__mcpc__core_latest/node_modules/@mcpc/core/src/executors/sampling/agentic-sampling-executor.js
1551
2353
  var SamplingExecutor = class extends BaseSamplingExecutor {
1552
2354
  agenticExecutor;
1553
2355
  constructor(name, description, allToolNames, toolNameToDetailList, server, config) {
@@ -1564,7 +2366,7 @@ var SamplingExecutor = class extends BaseSamplingExecutor {
1564
2366
  ...tool.inputSchema
1565
2367
  };
1566
2368
  } else {
1567
- const toolSchema = this.server.getInternalToolSchema(toolName);
2369
+ const toolSchema = this.server.getHiddenToolSchema(toolName);
1568
2370
  if (toolSchema) {
1569
2371
  depGroups[toolName] = {
1570
2372
  ...toolSchema.schema,
@@ -1592,13 +2394,13 @@ var SamplingExecutor = class extends BaseSamplingExecutor {
1592
2394
  }
1593
2395
  const createArgsDef = createArgsDefFactory(this.name, this.allToolNames, this.buildDepGroups(), void 0, void 0);
1594
2396
  const agenticSchema = createArgsDef.forAgentic(this.toolNameToDetailList, true);
1595
- const systemPrompt = this.buildSystemPrompt(args.userRequest, agenticSchema);
2397
+ const systemPrompt = this.buildSystemPrompt(args.userRequest, agenticSchema, args.context && typeof args.context === "object" ? args.context : void 0);
1596
2398
  return this.runSamplingLoop(() => systemPrompt, agenticSchema);
1597
2399
  }
1598
- async processAction(parsedData, schema) {
2400
+ async processAction(parsedData, schema, _state, parentSpan) {
1599
2401
  const toolCallData = parsedData;
1600
2402
  if (toolCallData.decision === "complete") {
1601
- return this.createCompletionResult("Task completed");
2403
+ return await this.createCompletionResult("Task completed", parentSpan);
1602
2404
  }
1603
2405
  try {
1604
2406
  const { action: _action, decision: _decision, ..._toolArgs } = toolCallData;
@@ -1613,13 +2415,13 @@ var SamplingExecutor = class extends BaseSamplingExecutor {
1613
2415
  });
1614
2416
  return toolResult;
1615
2417
  } catch (error) {
1616
- return this.createExecutionError(error);
2418
+ return this.createExecutionError(error, parentSpan);
1617
2419
  }
1618
2420
  }
1619
- buildSystemPrompt(userRequest, agenticSchema) {
2421
+ buildSystemPrompt(userRequest, agenticSchema, context2) {
1620
2422
  const toolList = this.allToolNames.map((name) => {
1621
2423
  const tool = this.toolNameToDetailList.find(([toolName]) => toolName === name);
1622
- const toolSchema = this.server.getInternalToolSchema(name);
2424
+ const toolSchema = this.server.getHiddenToolSchema(name);
1623
2425
  if (tool && tool[1]) {
1624
2426
  return `- ${name}: ${tool[1].description || `Tool: ${name}`}`;
1625
2427
  } else if (toolSchema) {
@@ -1627,6 +2429,13 @@ var SamplingExecutor = class extends BaseSamplingExecutor {
1627
2429
  }
1628
2430
  return `- ${name}`;
1629
2431
  }).join("\n");
2432
+ let contextInfo = "";
2433
+ if (context2 && typeof context2 === "object" && Object.keys(context2).length > 0) {
2434
+ contextInfo = `
2435
+
2436
+ Context:
2437
+ ${JSON.stringify(context2, null, 2)}`;
2438
+ }
1630
2439
  const basePrompt = CompiledPrompts.samplingExecution({
1631
2440
  toolName: this.name,
1632
2441
  description: this.description,
@@ -1635,7 +2444,7 @@ var SamplingExecutor = class extends BaseSamplingExecutor {
1635
2444
  const taskPrompt = `
1636
2445
 
1637
2446
  ## Current Task
1638
- I will now use agentic sampling to complete the following task: "${userRequest}"
2447
+ I will now use agentic sampling to complete the following task: "${userRequest}"${contextInfo}
1639
2448
 
1640
2449
  When I need to use a tool, I should specify the tool name in 'action' and provide tool-specific parameters as additional properties.
1641
2450
  When the task is complete, I should use "action": "complete".`;
@@ -1646,7 +2455,7 @@ When the task is complete, I should use "action": "complete".`;
1646
2455
  }
1647
2456
  };
1648
2457
 
1649
- // ../__mcpc__core_0.2.0-beta.10/node_modules/@mcpc/core/src/executors/agentic/agentic-tool-registrar.js
2458
+ // ../__mcpc__core_latest/node_modules/@mcpc/core/src/executors/agentic/agentic-tool-registrar.js
1650
2459
  function registerAgenticTool(server, { description, name, allToolNames, depGroups, toolNameToDetailList, sampling = false }) {
1651
2460
  const createArgsDef = createArgsDefFactory(name, allToolNames, depGroups, void 0, void 0);
1652
2461
  const isSamplingMode = sampling === true || typeof sampling === "object";
@@ -1676,10 +2485,10 @@ function registerAgenticTool(server, { description, name, allToolNames, depGroup
1676
2485
  });
1677
2486
  }
1678
2487
 
1679
- // ../__mcpc__core_0.2.0-beta.10/node_modules/@mcpc/core/src/executors/workflow/workflow-tool-registrar.js
1680
- import { jsonSchema as jsonSchema2 } from "ai";
2488
+ // ../__mcpc__core_latest/node_modules/@mcpc/core/src/executors/workflow/workflow-tool-registrar.js
2489
+ init_schema();
1681
2490
 
1682
- // ../__mcpc__core_0.2.0-beta.10/node_modules/@mcpc/core/src/utils/state.js
2491
+ // ../__mcpc__core_latest/node_modules/@mcpc/core/src/utils/state.js
1683
2492
  var WorkflowState = class {
1684
2493
  currentStepIndex = -1;
1685
2494
  steps = [];
@@ -1848,7 +2657,7 @@ var WorkflowState = class {
1848
2657
  }
1849
2658
  };
1850
2659
 
1851
- // ../__mcpc__core_0.2.0-beta.10/node_modules/@mcpc/core/src/executors/workflow/workflow-executor.js
2660
+ // ../__mcpc__core_latest/node_modules/@mcpc/core/src/executors/workflow/workflow-executor.js
1852
2661
  import { Ajv as Ajv3 } from "ajv";
1853
2662
  import { AggregateAjvError as AggregateAjvError3 } from "@segment/ajv-human-errors";
1854
2663
  import addFormats3 from "ajv-formats";
@@ -2175,7 +2984,7 @@ ${this.formatProgress(state)}`
2175
2984
  }
2176
2985
  };
2177
2986
 
2178
- // ../__mcpc__core_0.2.0-beta.10/node_modules/@mcpc/core/src/executors/sampling/workflow-sampling-executor.js
2987
+ // ../__mcpc__core_latest/node_modules/@mcpc/core/src/executors/sampling/workflow-sampling-executor.js
2179
2988
  var WorkflowSamplingExecutor = class extends BaseSamplingExecutor {
2180
2989
  createArgsDef;
2181
2990
  predefinedSteps;
@@ -2201,14 +3010,14 @@ var WorkflowSamplingExecutor = class extends BaseSamplingExecutor {
2201
3010
  }
2202
3011
  return await this.runSamplingLoop(() => this.buildWorkflowSystemPrompt(args, state), schema, state);
2203
3012
  }
2204
- async processAction(parsedData, _schema, state) {
3013
+ async processAction(parsedData, _schema, state, parentSpan) {
2205
3014
  const workflowState = state;
2206
3015
  if (!workflowState) {
2207
3016
  throw new Error("WorkflowState is required for workflow");
2208
3017
  }
2209
3018
  const toolCallData = parsedData;
2210
3019
  if (toolCallData.decision === "complete") {
2211
- return this.createCompletionResult("Task completed");
3020
+ return await this.createCompletionResult("Task completed", parentSpan);
2212
3021
  }
2213
3022
  try {
2214
3023
  const workflowResult = await this.workflowExecutor.execute(parsedData, workflowState);
@@ -2222,7 +3031,7 @@ var WorkflowSamplingExecutor = class extends BaseSamplingExecutor {
2222
3031
  });
2223
3032
  return workflowResult;
2224
3033
  } catch (error) {
2225
- return this.createExecutionError(error);
3034
+ return this.createExecutionError(error, parentSpan);
2226
3035
  }
2227
3036
  }
2228
3037
  buildWorkflowSystemPrompt(args, state) {
@@ -2232,9 +3041,16 @@ var WorkflowSamplingExecutor = class extends BaseSamplingExecutor {
2232
3041
  description: this.description,
2233
3042
  workflowSchema: `${JSON.stringify(workflowSchema, null, 2)}`
2234
3043
  });
3044
+ let contextInfo = "";
3045
+ if (args.context && typeof args.context === "object" && Object.keys(args.context).length > 0) {
3046
+ contextInfo = `
3047
+
3048
+ Context:
3049
+ ${JSON.stringify(args.context, null, 2)}`;
3050
+ }
2235
3051
  const workflowPrompt = `
2236
3052
 
2237
- Current Task: <user_request>${args.userRequest}</user_request>`;
3053
+ Current Task: <user_request>${args.userRequest}</user_request>${contextInfo}`;
2238
3054
  return this.injectJsonInstruction({
2239
3055
  prompt: basePrompt + workflowPrompt,
2240
3056
  schema: workflowSchema
@@ -2242,7 +3058,7 @@ Current Task: <user_request>${args.userRequest}</user_request>`;
2242
3058
  }
2243
3059
  };
2244
3060
 
2245
- // ../__mcpc__core_0.2.0-beta.10/node_modules/@mcpc/core/src/executors/workflow/workflow-tool-registrar.js
3061
+ // ../__mcpc__core_latest/node_modules/@mcpc/core/src/executors/workflow/workflow-tool-registrar.js
2246
3062
  function registerAgenticWorkflowTool(server, { description, name, allToolNames, depGroups, toolNameToDetailList, predefinedSteps, sampling = false, ensureStepActions, toolNameToIdMapping }) {
2247
3063
  const createArgsDef = createArgsDefFactory(name, allToolNames, depGroups, predefinedSteps, ensureStepActions);
2248
3064
  const isSamplingMode = sampling === true || typeof sampling === "object";
@@ -2262,7 +3078,7 @@ function registerAgenticWorkflowTool(server, { description, name, allToolNames,
2262
3078
  });
2263
3079
  const argsDef = isSamplingMode ? createArgsDef.forSampling() : createArgsDef.forTool();
2264
3080
  const toolDescription = isSamplingMode ? baseDescription : createArgsDef.forToolDescription(baseDescription, workflowState);
2265
- server.tool(name, toolDescription, jsonSchema2(createGoogleCompatibleJSONSchema(argsDef)), async (args) => {
3081
+ server.tool(name, toolDescription, jsonSchema(createGoogleCompatibleJSONSchema(argsDef)), async (args) => {
2266
3082
  try {
2267
3083
  if (isSamplingMode) {
2268
3084
  return await workflowSamplingExecutor.executeWorkflowSampling(args, argsDef, workflowState);
@@ -2284,7 +3100,7 @@ function registerAgenticWorkflowTool(server, { description, name, allToolNames,
2284
3100
  });
2285
3101
  }
2286
3102
 
2287
- // ../__mcpc__core_0.2.0-beta.10/node_modules/@mcpc/core/src/utils/common/tool-tag-processor.js
3103
+ // ../__mcpc__core_latest/node_modules/@mcpc/core/src/utils/common/tool-tag-processor.js
2288
3104
  var ALL_TOOLS_PLACEHOLDER = "__ALL__";
2289
3105
  function findToolId(toolName, tools, toolNameMapping) {
2290
3106
  const mappedId = toolNameMapping?.get(toolName);
@@ -2304,9 +3120,9 @@ function processToolTags({ description, tagToResults, $, tools, toolOverrides, t
2304
3120
  return;
2305
3121
  }
2306
3122
  const override = toolOverrides.get(toolName);
2307
- if (override?.visibility?.hide) {
3123
+ if (override?.visibility?.hidden) {
2308
3124
  $(toolEl).remove();
2309
- } else if (override?.visibility?.global) {
3125
+ } else if (override?.visibility?.public) {
2310
3126
  $(toolEl).replaceWith(`<tool name="${toolName}"/>`);
2311
3127
  } else {
2312
3128
  const toolId = findToolId(toolName, tools, toolNameMapping);
@@ -2318,168 +3134,308 @@ function processToolTags({ description, tagToResults, $, tools, toolOverrides, t
2318
3134
  return $.root().html() ?? description;
2319
3135
  }
2320
3136
 
2321
- // ../__mcpc__core_0.2.0-beta.10/node_modules/@mcpc/core/src/compose.js
3137
+ // ../__mcpc__core_latest/node_modules/@mcpc/core/src/compose.js
2322
3138
  init_built_in();
3139
+ init_logger();
3140
+ init_plugin_utils();
2323
3141
 
2324
- // ../__mcpc__core_0.2.0-beta.10/node_modules/@mcpc/core/src/plugin-utils.js
2325
- function shouldApplyPlugin(plugin, mode) {
2326
- if (!plugin.apply) return true;
2327
- if (typeof plugin.apply === "string") {
2328
- return mode.includes(plugin.apply);
2329
- }
2330
- if (typeof plugin.apply === "function") {
2331
- return plugin.apply(mode);
2332
- }
2333
- return plugin.apply;
2334
- }
2335
- function isValidPlugin(plugin) {
2336
- return plugin && plugin.name && (plugin.configureServer || plugin.composeStart || plugin.transformTool || plugin.finalizeComposition || plugin.composeEnd);
2337
- }
2338
- async function loadPlugin(pluginPath) {
2339
- try {
2340
- const [rawPath, queryString] = pluginPath.split("?", 2);
2341
- const searchParams = new URLSearchParams(queryString || "");
2342
- const params = Object.fromEntries(searchParams.entries());
2343
- const pluginModule = await import(rawPath);
2344
- const pluginFactory = pluginModule.createPlugin;
2345
- const defaultPlugin = pluginModule.default;
2346
- let plugin;
2347
- if (Object.keys(params).length > 0) {
2348
- if (typeof pluginFactory === "function") {
2349
- const typedParams = {};
2350
- for (const [key, value] of Object.entries(params)) {
2351
- const numValue = Number(value);
2352
- if (!isNaN(numValue)) {
2353
- typedParams[key] = numValue;
2354
- } else if (value === "true") {
2355
- typedParams[key] = true;
2356
- } else if (value === "false") {
2357
- typedParams[key] = false;
2358
- } else {
2359
- typedParams[key] = value;
2360
- }
2361
- }
2362
- plugin = pluginFactory(typedParams);
2363
- } else {
2364
- throw new Error(`Plugin ${rawPath} has parameters but no createPlugin export`);
2365
- }
2366
- } else {
2367
- plugin = defaultPlugin;
2368
- }
2369
- if (isValidPlugin(plugin)) {
2370
- return plugin;
2371
- } else {
2372
- throw new Error(`Invalid plugin format in ${rawPath} - plugin must have a name and at least one lifecycle hook`);
2373
- }
2374
- } catch (error) {
2375
- throw new Error(`Failed to load plugin from ${pluginPath}: ${error}`);
3142
+ // ../__mcpc__core_latest/node_modules/@mcpc/core/src/utils/plugin-manager.js
3143
+ init_plugin_utils();
3144
+ init_logger();
3145
+ var PluginManager = class {
3146
+ server;
3147
+ plugins;
3148
+ logger;
3149
+ constructor(server) {
3150
+ this.server = server;
3151
+ this.plugins = [];
3152
+ this.logger = createLogger("mcpc.plugin-manager");
3153
+ this.logger.setServer(server);
2376
3154
  }
2377
- }
2378
-
2379
- // ../__mcpc__core_0.2.0-beta.10/node_modules/@mcpc/core/src/compose.js
2380
- var ALL_TOOLS_PLACEHOLDER2 = "__ALL__";
2381
- var ComposableMCPServer = class extends Server {
2382
- tools = [];
2383
- toolRegistry = /* @__PURE__ */ new Map();
2384
- toolConfigs = /* @__PURE__ */ new Map();
2385
- globalPlugins = [];
2386
- toolNameMapping = /* @__PURE__ */ new Map();
2387
- constructor(_serverInfo, options) {
2388
- super(_serverInfo, options);
3155
+ /**
3156
+ * Get all registered plugins
3157
+ */
3158
+ getPlugins() {
3159
+ return [
3160
+ ...this.plugins
3161
+ ];
2389
3162
  }
2390
3163
  /**
2391
- * Initialize built-in plugins - called during setup
3164
+ * Get plugin names
2392
3165
  */
2393
- async initBuiltInPlugins() {
2394
- const builtInPlugins = getBuiltInPlugins();
2395
- for (const plugin of builtInPlugins) {
2396
- await this.addPlugin(plugin);
2397
- }
3166
+ getPluginNames() {
3167
+ return this.plugins.map((p2) => p2.name);
2398
3168
  }
2399
3169
  /**
2400
- * Apply plugin transformations to tool arguments/results
2401
- * TODO: Implement transformResult lifecycle hooks
3170
+ * Check if a plugin is registered
2402
3171
  */
2403
- applyPluginTransforms(_toolName, args, _mode, _originalArgs) {
2404
- return args;
3172
+ hasPlugin(name) {
3173
+ return this.plugins.some((p2) => p2.name === name);
2405
3174
  }
2406
3175
  /**
2407
- * Resolve a tool name to its internal format
3176
+ * Add a plugin with validation and error handling
2408
3177
  */
2409
- resolveToolName(name) {
2410
- if (this.toolRegistry.has(name)) {
2411
- return name;
3178
+ async addPlugin(plugin) {
3179
+ const validation = validatePlugins([
3180
+ plugin
3181
+ ]);
3182
+ if (!validation.valid) {
3183
+ const errorMsg = validation.errors.join(", ");
3184
+ throw new Error(`Invalid plugin "${plugin.name}": ${errorMsg}`);
2412
3185
  }
2413
- const mappedName = this.toolNameMapping.get(name);
2414
- if (mappedName && this.toolRegistry.has(mappedName)) {
2415
- return mappedName;
3186
+ if (this.plugins.some((p2) => p2.name === plugin.name)) {
3187
+ await this.logger.warning(`Plugin "${plugin.name}" already registered, skipping`);
3188
+ return;
2416
3189
  }
2417
- if (this.toolConfigs.has(name)) {
2418
- const cfgMapped = this.toolNameMapping.get(name);
2419
- if (cfgMapped && this.toolRegistry.has(cfgMapped)) {
2420
- return cfgMapped;
3190
+ if (plugin.dependencies) {
3191
+ const missingDeps = plugin.dependencies.filter((dep) => !this.plugins.some((p2) => p2.name === dep));
3192
+ if (missingDeps.length > 0) {
3193
+ throw new Error(`Plugin "${plugin.name}" has missing dependencies: ${missingDeps.join(", ")}`);
2421
3194
  }
2422
3195
  }
2423
- return void 0;
2424
- }
2425
- tool(name, description, paramsSchema, cb, options = {}) {
2426
- this.toolRegistry.set(name, {
2427
- callback: cb,
2428
- description,
2429
- schema: paramsSchema.jsonSchema
2430
- });
2431
- if (options.plugins) {
2432
- for (const plugin of options.plugins) {
2433
- this.globalPlugins.push(plugin);
3196
+ this.plugins.push(plugin);
3197
+ if (plugin.configureServer) {
3198
+ try {
3199
+ await plugin.configureServer(this.server);
3200
+ } catch (error) {
3201
+ this.plugins = this.plugins.filter((p2) => p2.name !== plugin.name);
3202
+ const errorMsg = error instanceof Error ? error.message : String(error);
3203
+ throw new Error(`Plugin "${plugin.name}" configuration failed: ${errorMsg}`);
2434
3204
  }
2435
3205
  }
2436
- if (options.internal) {
2437
- this.toolConfigs.set(name, {
2438
- visibility: {
2439
- internal: true
3206
+ }
3207
+ /**
3208
+ * Load and register a plugin from a file path
3209
+ */
3210
+ async loadPluginFromPath(pluginPath, options = {
3211
+ cache: true
3212
+ }) {
3213
+ const plugin = await loadPlugin(pluginPath, options);
3214
+ await this.addPlugin(plugin);
3215
+ }
3216
+ /**
3217
+ * Trigger composeStart hooks for all applicable plugins
3218
+ */
3219
+ async triggerComposeStart(context2) {
3220
+ const startPlugins = this.plugins.filter((p2) => p2.composeStart && shouldApplyPlugin(p2, context2.mode));
3221
+ const sortedPlugins = sortPluginsByOrder(startPlugins);
3222
+ for (const plugin of sortedPlugins) {
3223
+ if (plugin.composeStart) {
3224
+ try {
3225
+ await plugin.composeStart(context2);
3226
+ } catch (error) {
3227
+ const errorMsg = error instanceof Error ? error.message : String(error);
3228
+ await this.logger.error(`Plugin "${plugin.name}" composeStart failed: ${errorMsg}`);
2440
3229
  }
2441
- });
2442
- } else {
2443
- const existingTool = this.tools.find((t) => t.name === name);
2444
- if (!existingTool) {
2445
- const newTool = {
2446
- name,
2447
- description,
2448
- inputSchema: paramsSchema.jsonSchema
2449
- };
2450
- this.tools = [
2451
- ...this.tools,
2452
- newTool
2453
- ];
2454
3230
  }
2455
3231
  }
2456
- this.setRequestHandler(ListToolsRequestSchema, () => {
2457
- return {
2458
- tools: this.tools
2459
- };
2460
- });
2461
- this.setRequestHandler(CallToolRequestSchema, (request, extra) => {
2462
- const { name: toolName, arguments: args } = request.params;
2463
- const handler = this.getToolCallback(toolName);
2464
- if (!handler) {
2465
- throw new Error(`Tool ${toolName} not found`);
3232
+ }
3233
+ /**
3234
+ * Apply transformTool hooks to a tool during composition
3235
+ */
3236
+ async applyTransformToolHooks(tool, context2) {
3237
+ const transformPlugins = this.plugins.filter((p2) => p2.transformTool && shouldApplyPlugin(p2, context2.mode));
3238
+ if (transformPlugins.length === 0) {
3239
+ return tool;
3240
+ }
3241
+ const sortedPlugins = sortPluginsByOrder(transformPlugins);
3242
+ let currentTool = tool;
3243
+ for (const plugin of sortedPlugins) {
3244
+ if (plugin.transformTool) {
3245
+ try {
3246
+ const result = await plugin.transformTool(currentTool, context2);
3247
+ if (result) {
3248
+ currentTool = result;
3249
+ }
3250
+ } catch (error) {
3251
+ const errorMsg = error instanceof Error ? error.message : String(error);
3252
+ await this.logger.error(`Plugin "${plugin.name}" transformTool failed for "${context2.toolName}": ${errorMsg}`);
3253
+ }
2466
3254
  }
2467
- const processedArgs = this.applyPluginTransforms(toolName, args, "input");
2468
- const result = handler(processedArgs, extra);
2469
- return this.applyPluginTransforms(toolName, result, "output", args);
3255
+ }
3256
+ return currentTool;
3257
+ }
3258
+ /**
3259
+ * Trigger finalizeComposition hooks for all applicable plugins
3260
+ */
3261
+ async triggerFinalizeComposition(tools, context2) {
3262
+ const finalizePlugins = this.plugins.filter((p2) => p2.finalizeComposition && shouldApplyPlugin(p2, context2.mode));
3263
+ const sortedPlugins = sortPluginsByOrder(finalizePlugins);
3264
+ for (const plugin of sortedPlugins) {
3265
+ if (plugin.finalizeComposition) {
3266
+ try {
3267
+ await plugin.finalizeComposition(tools, context2);
3268
+ } catch (error) {
3269
+ const errorMsg = error instanceof Error ? error.message : String(error);
3270
+ await this.logger.error(`Plugin "${plugin.name}" finalizeComposition failed: ${errorMsg}`);
3271
+ }
3272
+ }
3273
+ }
3274
+ }
3275
+ /**
3276
+ * Trigger composeEnd hooks for all applicable plugins
3277
+ */
3278
+ async triggerComposeEnd(context2) {
3279
+ const endPlugins = this.plugins.filter((p2) => p2.composeEnd && shouldApplyPlugin(p2, context2.mode));
3280
+ const sortedPlugins = sortPluginsByOrder(endPlugins);
3281
+ for (const plugin of sortedPlugins) {
3282
+ if (plugin.composeEnd) {
3283
+ try {
3284
+ await plugin.composeEnd(context2);
3285
+ } catch (error) {
3286
+ const errorMsg = error instanceof Error ? error.message : String(error);
3287
+ await this.logger.error(`Plugin "${plugin.name}" composeEnd failed: ${errorMsg}`);
3288
+ }
3289
+ }
3290
+ }
3291
+ }
3292
+ /**
3293
+ * Dispose all plugins and cleanup resources
3294
+ */
3295
+ async dispose() {
3296
+ for (const plugin of this.plugins) {
3297
+ if (plugin.dispose) {
3298
+ try {
3299
+ await plugin.dispose();
3300
+ } catch (error) {
3301
+ const errorMsg = error instanceof Error ? error.message : String(error);
3302
+ await this.logger.error(`Plugin "${plugin.name}" dispose failed: ${errorMsg}`);
3303
+ }
3304
+ }
3305
+ }
3306
+ this.plugins = [];
3307
+ }
3308
+ };
3309
+
3310
+ // ../__mcpc__core_latest/node_modules/@mcpc/core/src/utils/tool-manager.js
3311
+ var ToolManager = class {
3312
+ toolRegistry = /* @__PURE__ */ new Map();
3313
+ toolConfigs = /* @__PURE__ */ new Map();
3314
+ toolNameMapping = /* @__PURE__ */ new Map();
3315
+ publicTools = [];
3316
+ /**
3317
+ * Get tool name mapping (for external access)
3318
+ */
3319
+ getToolNameMapping() {
3320
+ return this.toolNameMapping;
3321
+ }
3322
+ /**
3323
+ * Register a tool in the registry
3324
+ */
3325
+ registerTool(name, description, schema, callback, options = {}) {
3326
+ this.toolRegistry.set(name, {
3327
+ callback,
3328
+ description,
3329
+ schema
2470
3330
  });
3331
+ if (options.internal) {
3332
+ this.toolConfigs.set(name, {
3333
+ visibility: {
3334
+ hidden: true
3335
+ }
3336
+ });
3337
+ }
3338
+ }
3339
+ /**
3340
+ * Explicitly mark a tool as public (exposed to MCP clients)
3341
+ */
3342
+ addPublicTool(name, description, schema) {
3343
+ const existingTool = this.publicTools.find((t) => t.name === name);
3344
+ if (!existingTool) {
3345
+ this.publicTools.push({
3346
+ name,
3347
+ description,
3348
+ inputSchema: schema
3349
+ });
3350
+ }
3351
+ }
3352
+ /**
3353
+ * Check if a tool is public (exposed to MCP clients)
3354
+ */
3355
+ isPublic(name) {
3356
+ const config = this.toolConfigs.get(name);
3357
+ return config?.visibility?.public === true;
3358
+ }
3359
+ /**
3360
+ * Check if a tool is hidden from agent context
3361
+ */
3362
+ isHidden(name) {
3363
+ const config = this.toolConfigs.get(name);
3364
+ return config?.visibility?.hidden === true;
3365
+ }
3366
+ /**
3367
+ * Get all public tool names (exposed to MCP clients)
3368
+ */
3369
+ getPublicToolNames() {
3370
+ return Array.from(this.toolConfigs.entries()).filter(([_name, config]) => config.visibility?.public === true).map(([name]) => this.resolveToolName(name) ?? name);
3371
+ }
3372
+ /**
3373
+ * Get all hidden tool names
3374
+ */
3375
+ getHiddenToolNames() {
3376
+ return Array.from(this.toolConfigs.entries()).filter(([_name, config]) => config.visibility?.hidden === true).map(([name]) => this.resolveToolName(name) ?? name);
2471
3377
  }
2472
3378
  /**
2473
- * Register a tool override with description, hide, args transformation, and/or custom handler
3379
+ * Get all public tools
2474
3380
  */
3381
+ getPublicTools() {
3382
+ return [
3383
+ ...this.publicTools
3384
+ ];
3385
+ }
3386
+ /**
3387
+ * Set public tools list
3388
+ */
3389
+ setPublicTools(tools) {
3390
+ this.publicTools = [
3391
+ ...tools
3392
+ ];
3393
+ }
2475
3394
  /**
2476
- * Get tool callback from registry
2477
- */
3395
+ * Get tool callback by name
3396
+ */
2478
3397
  getToolCallback(name) {
2479
3398
  return this.toolRegistry.get(name)?.callback;
2480
3399
  }
2481
3400
  /**
2482
- * Find tool configuration (simplified - dot/underscore mapping now handled by plugin)
3401
+ * Check if tool exists in registry
3402
+ */
3403
+ hasToolNamed(name) {
3404
+ return this.toolRegistry.has(name) || this.toolNameMapping.has(name) && this.toolRegistry.has(this.toolNameMapping.get(name));
3405
+ }
3406
+ /**
3407
+ * Resolve a tool name to its internal format
3408
+ */
3409
+ resolveToolName(name) {
3410
+ if (this.toolRegistry.has(name)) {
3411
+ return name;
3412
+ }
3413
+ const mappedName = this.toolNameMapping.get(name);
3414
+ if (mappedName && this.toolRegistry.has(mappedName)) {
3415
+ return mappedName;
3416
+ }
3417
+ if (this.toolConfigs.has(name)) {
3418
+ const cfgMapped = this.toolNameMapping.get(name);
3419
+ if (cfgMapped && this.toolRegistry.has(cfgMapped)) {
3420
+ return cfgMapped;
3421
+ }
3422
+ }
3423
+ return void 0;
3424
+ }
3425
+ /**
3426
+ * Configure tool behavior
3427
+ */
3428
+ configTool(toolName, config) {
3429
+ this.toolConfigs.set(toolName, config);
3430
+ }
3431
+ /**
3432
+ * Get tool configuration
3433
+ */
3434
+ getToolConfig(toolName) {
3435
+ return this.toolConfigs.get(toolName);
3436
+ }
3437
+ /**
3438
+ * Find tool configuration (with mapping fallback)
2483
3439
  */
2484
3440
  findToolConfig(toolId) {
2485
3441
  const directConfig = this.toolConfigs.get(toolId);
@@ -2492,6 +3448,179 @@ var ComposableMCPServer = class extends Server {
2492
3448
  }
2493
3449
  return void 0;
2494
3450
  }
3451
+ /**
3452
+ * Remove tool configuration
3453
+ */
3454
+ removeToolConfig(toolName) {
3455
+ return this.toolConfigs.delete(toolName);
3456
+ }
3457
+ /**
3458
+ * Set tool name mapping
3459
+ */
3460
+ setToolNameMapping(from, to) {
3461
+ this.toolNameMapping.set(from, to);
3462
+ }
3463
+ /**
3464
+ * Get tool schema if it's hidden (for internal access)
3465
+ */
3466
+ getHiddenToolSchema(name) {
3467
+ const tool = this.toolRegistry.get(name);
3468
+ const config = this.toolConfigs.get(name);
3469
+ if (tool && config?.visibility?.hidden && tool.schema) {
3470
+ return {
3471
+ description: tool.description,
3472
+ schema: tool.schema
3473
+ };
3474
+ }
3475
+ return void 0;
3476
+ }
3477
+ /**
3478
+ * Get total tool count
3479
+ */
3480
+ getTotalToolCount() {
3481
+ return this.toolRegistry.size;
3482
+ }
3483
+ /**
3484
+ * Get all tool entries
3485
+ */
3486
+ getToolEntries() {
3487
+ return Array.from(this.toolRegistry.entries());
3488
+ }
3489
+ /**
3490
+ * Get tool registry (for external access)
3491
+ */
3492
+ getToolRegistry() {
3493
+ return this.toolRegistry;
3494
+ }
3495
+ };
3496
+
3497
+ // ../__mcpc__core_latest/node_modules/@mcpc/core/src/compose.js
3498
+ init_compose_helpers();
3499
+ var ALL_TOOLS_PLACEHOLDER2 = "__ALL__";
3500
+ var ComposableMCPServer = class extends Server {
3501
+ pluginManager;
3502
+ toolManager;
3503
+ logger = createLogger("mcpc.compose");
3504
+ // Legacy property for backward compatibility
3505
+ get toolNameMapping() {
3506
+ return this.toolManager.getToolNameMapping();
3507
+ }
3508
+ constructor(_serverInfo, options) {
3509
+ const enhancedOptions = {
3510
+ ...options,
3511
+ capabilities: {
3512
+ logging: {},
3513
+ tools: {},
3514
+ sampling: {},
3515
+ ...options?.capabilities ?? {}
3516
+ }
3517
+ };
3518
+ super(_serverInfo, enhancedOptions);
3519
+ this.logger.setServer(this);
3520
+ this.pluginManager = new PluginManager(this);
3521
+ this.toolManager = new ToolManager();
3522
+ }
3523
+ /**
3524
+ * Initialize built-in plugins - called during setup
3525
+ */
3526
+ async initBuiltInPlugins() {
3527
+ const builtInPlugins = getBuiltInPlugins();
3528
+ const validation = validatePlugins(builtInPlugins);
3529
+ if (!validation.valid) {
3530
+ await this.logger.warning("Built-in plugin validation issues:");
3531
+ for (const error of validation.errors) {
3532
+ await this.logger.warning(` - ${error}`);
3533
+ }
3534
+ }
3535
+ for (const plugin of builtInPlugins) {
3536
+ await this.pluginManager.addPlugin(plugin);
3537
+ }
3538
+ }
3539
+ /**
3540
+ * Apply plugin transformations to tool arguments/results
3541
+ * Supports runtime transformation hooks for input/output processing
3542
+ */
3543
+ async applyPluginTransforms(toolName, data, direction, originalArgs) {
3544
+ const hookName = direction === "input" ? "transformInput" : "transformOutput";
3545
+ const plugins = this.pluginManager.getPlugins().filter((p2) => p2[hookName]);
3546
+ if (plugins.length === 0) {
3547
+ return data;
3548
+ }
3549
+ const { sortPluginsByOrder: sortPluginsByOrder2 } = await Promise.resolve().then(() => (init_plugin_utils(), plugin_utils_exports));
3550
+ const sortedPlugins = sortPluginsByOrder2(plugins);
3551
+ let currentData = data;
3552
+ const context2 = {
3553
+ toolName,
3554
+ server: this,
3555
+ direction,
3556
+ originalArgs
3557
+ };
3558
+ for (const plugin of sortedPlugins) {
3559
+ const hook = plugin[hookName];
3560
+ if (hook) {
3561
+ try {
3562
+ const result = await hook(currentData, context2);
3563
+ if (result !== void 0) {
3564
+ currentData = result;
3565
+ }
3566
+ } catch (error) {
3567
+ const errorMsg = error instanceof Error ? error.message : String(error);
3568
+ await this.logger.error(`Plugin "${plugin.name}" ${hookName} failed for "${toolName}": ${errorMsg}`);
3569
+ }
3570
+ }
3571
+ }
3572
+ return currentData;
3573
+ }
3574
+ /**
3575
+ * Resolve a tool name to its internal format
3576
+ */
3577
+ resolveToolName(name) {
3578
+ return this.toolManager.resolveToolName(name);
3579
+ }
3580
+ tool(name, description, paramsSchema, cb, options = {}) {
3581
+ const jsonSchemaObj = extractJsonSchema(paramsSchema);
3582
+ this.toolManager.registerTool(name, description, jsonSchemaObj, cb, options);
3583
+ if (!options.internal) {
3584
+ this.toolManager.addPublicTool(name, description, jsonSchemaObj);
3585
+ }
3586
+ if (options.plugins) {
3587
+ for (const plugin of options.plugins) {
3588
+ this.pluginManager.addPlugin(plugin);
3589
+ }
3590
+ }
3591
+ this.setRequestHandler(ListToolsRequestSchema, () => {
3592
+ return {
3593
+ tools: this.toolManager.getPublicTools()
3594
+ };
3595
+ });
3596
+ this.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
3597
+ const { name: toolName, arguments: args } = request.params;
3598
+ const handler = this.getToolCallback(toolName);
3599
+ if (!handler) {
3600
+ throw new Error(`Tool ${toolName} not found`);
3601
+ }
3602
+ const processedArgs = await this.applyPluginTransforms(toolName, args, "input");
3603
+ const result = await handler(processedArgs, extra);
3604
+ return await this.applyPluginTransforms(toolName, result, "output", args);
3605
+ });
3606
+ this.setRequestHandler(SetLevelRequestSchema, (request) => {
3607
+ const { level } = request.params;
3608
+ this.logger.setLevel(level);
3609
+ return {};
3610
+ });
3611
+ }
3612
+ /**
3613
+ * Get tool callback from registry
3614
+ */
3615
+ getToolCallback(name) {
3616
+ return this.toolManager.getToolCallback(name);
3617
+ }
3618
+ /**
3619
+ * Find tool configuration
3620
+ */
3621
+ findToolConfig(toolId) {
3622
+ return this.toolManager.findToolConfig(toolId);
3623
+ }
2495
3624
  /**
2496
3625
  * Call any registered tool directly, whether it's public or internal
2497
3626
  */
@@ -2504,207 +3633,84 @@ var ComposableMCPServer = class extends Server {
2504
3633
  if (!callback) {
2505
3634
  throw new Error(`Tool ${name} not found`);
2506
3635
  }
2507
- const processedArgs = this.applyPluginTransforms(resolvedName, args, "input");
3636
+ const processedArgs = await this.applyPluginTransforms(resolvedName, args, "input");
2508
3637
  const result = await callback(processedArgs);
2509
- return this.applyPluginTransforms(resolvedName, result, "output", args);
3638
+ return await this.applyPluginTransforms(resolvedName, result, "output", args);
2510
3639
  }
2511
3640
  /**
2512
- * Get all internal tool names
2513
- */
2514
- getInternalToolNames() {
2515
- return Array.from(this.toolConfigs.entries()).filter(([_name, config]) => config.visibility?.internal).map(([name]) => this.resolveToolName(name) ?? name);
2516
- }
2517
- /**
2518
- * Get all public tool names
3641
+ * Get all public tool names (exposed to MCP clients)
2519
3642
  */
2520
3643
  getPublicToolNames() {
2521
- return Array.from(this.toolConfigs.entries()).filter(([_name, config]) => config.visibility?.global).map(([name]) => this.resolveToolName(name) ?? name);
3644
+ return this.toolManager.getPublicToolNames();
2522
3645
  }
2523
3646
  /**
2524
- * Get all external (non-global, non-internal, non-hidden) tool names
3647
+ * Get all public tools (for AI SDK integration)
2525
3648
  */
2526
- getExternalToolNames() {
2527
- const allRegistered = Array.from(this.toolRegistry.keys());
2528
- const publicSet = new Set(this.getPublicToolNames());
2529
- const internalSet = new Set(this.getInternalToolNames());
2530
- const hiddenSet = new Set(this.getHiddenToolNames());
2531
- return allRegistered.filter((n) => !publicSet.has(n) && !internalSet.has(n) && !hiddenSet.has(n));
3649
+ getPublicTools() {
3650
+ return this.toolManager.getPublicTools();
2532
3651
  }
2533
3652
  /**
2534
3653
  * Get all hidden tool names
2535
3654
  */
2536
3655
  getHiddenToolNames() {
2537
- return Array.from(this.toolConfigs.entries()).filter(([_name, config]) => config.visibility?.hide).map(([name]) => this.resolveToolName(name) ?? name);
3656
+ return this.toolManager.getHiddenToolNames();
2538
3657
  }
2539
3658
  /**
2540
- * Get internal tool schema by name
3659
+ * Get hidden tool schema by name (for internal access)
2541
3660
  */
2542
- getInternalToolSchema(name) {
2543
- const tool = this.toolRegistry.get(name);
2544
- const config = this.toolConfigs.get(name);
2545
- if (tool && config?.visibility?.internal && tool.schema) {
2546
- return {
2547
- description: tool.description,
2548
- schema: tool.schema
2549
- };
2550
- }
2551
- return void 0;
3661
+ getHiddenToolSchema(name) {
3662
+ return this.toolManager.getHiddenToolSchema(name);
2552
3663
  }
2553
3664
  /**
2554
- * Check if a tool exists (visible or internal)
3665
+ * Check if a tool exists (visible or hidden)
2555
3666
  */
2556
3667
  hasToolNamed(name) {
2557
- return this.toolRegistry.has(name) || this.toolNameMapping.has(name) && this.toolRegistry.has(this.toolNameMapping.get(name));
3668
+ return this.toolManager.hasToolNamed(name);
2558
3669
  }
2559
3670
  /**
2560
- * Configure tool behavior (simplified replacement for middleware)
2561
- * @example
2562
- * ```typescript
2563
- * // Override description
2564
- * server.configTool('myTool', {
2565
- * callback: originalCallback,
2566
- * description: 'Enhanced tool description'
2567
- * });
2568
- *
2569
- * // Hide tool from agentic execution
2570
- * server.configTool('myTool', {
2571
- * callback: originalCallback,
2572
- * description: 'Hidden tool',
2573
- * visibility: { hide: true }
2574
- * });
2575
- *
2576
- * // Make tool globally available
2577
- * server.configTool('myTool', {
2578
- * callback: originalCallback,
2579
- * description: 'Global tool',
2580
- * visibility: { global: true }
2581
- * });
2582
- * ```
3671
+ * Configure tool behavior
2583
3672
  */
2584
3673
  configTool(toolName, config) {
2585
- this.toolConfigs.set(toolName, config);
3674
+ this.toolManager.configTool(toolName, config);
2586
3675
  }
2587
3676
  /**
2588
3677
  * Get tool configuration
2589
3678
  */
2590
3679
  getToolConfig(toolName) {
2591
- return this.toolConfigs.get(toolName);
3680
+ return this.toolManager.getToolConfig(toolName);
2592
3681
  }
2593
3682
  /**
2594
3683
  * Remove tool configuration
2595
3684
  */
2596
3685
  removeToolConfig(toolName) {
2597
- return this.toolConfigs.delete(toolName);
3686
+ return this.toolManager.removeToolConfig(toolName);
2598
3687
  }
2599
3688
  /**
2600
- * Register a tool plugin
2601
- * @example
2602
- * ```typescript
2603
- * // Global plugin for all tools
2604
- * server.addPlugin({
2605
- * name: 'logger',
2606
- * transformTool: (tool, context) => {
2607
- * const originalExecute = tool.execute;
2608
- * tool.execute = async (args, extra) => {
2609
- * console.log(`Calling ${tool.name} with:`, args);
2610
- * const result = await originalExecute(args, extra);
2611
- * console.log(`Result:`, result);
2612
- * return result;
2613
- * };
2614
- * return tool;
2615
- * }
2616
- * });
2617
- * ```
3689
+ * Register a tool plugin with validation and error handling
2618
3690
  */
2619
3691
  async addPlugin(plugin) {
2620
- if (plugin.configureServer) {
2621
- await plugin.configureServer(this);
2622
- }
2623
- this.globalPlugins.push(plugin);
3692
+ await this.pluginManager.addPlugin(plugin);
2624
3693
  }
2625
3694
  /**
2626
3695
  * Load and register a plugin from a file path with optional parameters
2627
- *
2628
- * Supports parameter passing via query string syntax:
2629
- * loadPluginFromPath("path/to/plugin.ts?param1=value1&param2=value2")
2630
- */
2631
- async loadPluginFromPath(pluginPath) {
2632
- const plugin = await loadPlugin(pluginPath);
2633
- this.addPlugin(plugin);
2634
- }
2635
- /**
2636
- * Apply transformTool hook to a tool during composition
2637
3696
  */
2638
- async applyTransformToolHooks(tool, toolName, mode) {
2639
- const transformPlugins = this.globalPlugins.filter((p2) => p2.transformTool && shouldApplyPlugin(p2, mode));
2640
- if (transformPlugins.length === 0) {
2641
- return tool;
2642
- }
2643
- const sortedPlugins = [
2644
- ...transformPlugins.filter((p2) => p2.enforce === "pre"),
2645
- ...transformPlugins.filter((p2) => !p2.enforce),
2646
- ...transformPlugins.filter((p2) => p2.enforce === "post")
2647
- ];
2648
- const context = {
2649
- toolName,
2650
- server: this,
2651
- mode
2652
- };
2653
- let currentTool = tool;
2654
- for (const plugin of sortedPlugins) {
2655
- if (plugin.transformTool) {
2656
- const result = await plugin.transformTool(currentTool, context);
2657
- if (result) {
2658
- currentTool = result;
2659
- }
2660
- }
2661
- }
2662
- return currentTool;
3697
+ async loadPluginFromPath(pluginPath, options = {
3698
+ cache: true
3699
+ }) {
3700
+ await this.pluginManager.loadPluginFromPath(pluginPath, options);
2663
3701
  }
2664
3702
  /**
2665
3703
  * Apply plugins to all tools in registry and handle visibility configurations
2666
3704
  */
2667
3705
  async processToolsWithPlugins(externalTools, mode) {
2668
- for (const [toolId, toolData] of this.toolRegistry.entries()) {
2669
- const defaultSchema = {
2670
- type: "object",
2671
- properties: {},
2672
- additionalProperties: true
2673
- };
2674
- const tempTool = {
2675
- name: toolId,
2676
- description: toolData.description,
2677
- inputSchema: toolData.schema || defaultSchema,
2678
- execute: toolData.callback
2679
- };
2680
- const processedTool = await this.applyTransformToolHooks(tempTool, toolId, mode);
2681
- this.toolRegistry.set(toolId, {
2682
- callback: processedTool.execute,
2683
- description: processedTool.description || toolData.description,
2684
- schema: processedTool.inputSchema
2685
- });
2686
- if (externalTools[toolId]) {
2687
- try {
2688
- const builtIn = await Promise.resolve().then(() => (init_built_in(), built_in_exports));
2689
- if (builtIn && typeof builtIn.processToolVisibility === "function") {
2690
- builtIn.processToolVisibility(toolId, processedTool, this, externalTools);
2691
- }
2692
- } catch {
2693
- }
2694
- externalTools[toolId] = processedTool;
2695
- }
2696
- }
3706
+ const { processToolsWithPlugins: processTools } = await Promise.resolve().then(() => (init_compose_helpers(), compose_helpers_exports));
3707
+ await processTools(this, externalTools, mode);
2697
3708
  }
2698
3709
  /**
2699
- * Trigger composeEnd hooks for all plugins
3710
+ * Dispose all plugins and cleanup resources
2700
3711
  */
2701
- async triggerComposeEndHooks(context) {
2702
- const endPlugins = this.globalPlugins.filter((p2) => p2.composeEnd && shouldApplyPlugin(p2, context.mode));
2703
- for (const plugin of endPlugins) {
2704
- if (plugin.composeEnd) {
2705
- await plugin.composeEnd(context);
2706
- }
2707
- }
3712
+ async disposePlugins() {
3713
+ await this.pluginManager.dispose();
2708
3714
  }
2709
3715
  async compose(name, description, depsConfig = {
2710
3716
  mcpServers: {}
@@ -2716,17 +3722,24 @@ var ComposableMCPServer = class extends Server {
2716
3722
  "tool",
2717
3723
  "fn"
2718
3724
  ]);
3725
+ await this.pluginManager.triggerComposeStart({
3726
+ serverName: name ?? "anonymous",
3727
+ description,
3728
+ mode: options.mode ?? "agentic",
3729
+ server: this,
3730
+ availableTools: []
3731
+ });
2719
3732
  tagToResults.tool.forEach((toolEl) => {
2720
3733
  const toolName = toolEl.attribs.name;
2721
3734
  const toolDescription = toolEl.attribs.description;
2722
3735
  const isHidden = toolEl.attribs.hide !== void 0;
2723
- const isGlobal = toolEl.attribs.global !== void 0;
3736
+ const isPublic = toolEl.attribs.global !== void 0;
2724
3737
  if (toolName) {
2725
- this.toolConfigs.set(toolName, {
3738
+ this.toolManager.configTool(toolName, {
2726
3739
  description: toolDescription,
2727
3740
  visibility: {
2728
- hide: isHidden,
2729
- global: isGlobal
3741
+ hidden: isHidden,
3742
+ public: isPublic
2730
3743
  }
2731
3744
  });
2732
3745
  }
@@ -2745,10 +3758,10 @@ var ComposableMCPServer = class extends Server {
2745
3758
  availableToolNames.add(toolId);
2746
3759
  availableToolNames.add(`${mcpName}.${ALL_TOOLS_PLACEHOLDER2}`);
2747
3760
  availableToolNames.add(mcpName);
2748
- this.toolNameMapping.set(toolNameWithScope, toolId);
3761
+ this.toolManager.setToolNameMapping(toolNameWithScope, toolId);
2749
3762
  const internalName = toolNameWithScope.includes(".") ? toolNameWithScope.split(".").slice(1).join(".") : toolNameWithScope;
2750
3763
  if (!this.toolNameMapping.has(internalName)) {
2751
- this.toolNameMapping.set(internalName, toolId);
3764
+ this.toolManager.setToolNameMapping(internalName, toolId);
2752
3765
  }
2753
3766
  const matchingStep = options.steps?.find((step) => step.actions.includes(toolNameWithScope));
2754
3767
  if (matchingStep) {
@@ -2768,53 +3781,56 @@ var ComposableMCPServer = class extends Server {
2768
3781
  });
2769
3782
  const unmatchedTools = Array.from(requestedToolNames).filter((toolName) => !availableToolNames.has(toolName));
2770
3783
  if (unmatchedTools.length > 0) {
2771
- console.warn(`\u26A0\uFE0F Tool matching warnings for agent "${name}":`);
2772
- unmatchedTools.forEach((toolName) => {
2773
- console.warn(` \u2022 Tool not found: "${toolName}"`);
2774
- });
2775
- console.warn(` Available tools: ${Array.from(availableToolNames).sort().join(", ")}`);
3784
+ await this.logger.warning(`Tool matching warnings for agent "${name}":`);
3785
+ for (const toolName of unmatchedTools) {
3786
+ await this.logger.warning(` \u2022 Tool not found: "${toolName}"`);
3787
+ }
3788
+ await this.logger.warning(` Available tools: ${Array.from(availableToolNames).sort().join(", ")}`);
2776
3789
  }
2777
3790
  Object.entries(tools).forEach(([toolId, tool]) => {
2778
- this.toolRegistry.set(toolId, {
2779
- callback: tool.execute,
2780
- description: tool.description || "No description available",
2781
- schema: tool.inputSchema
2782
- });
3791
+ this.toolManager.registerTool(toolId, tool.description || "No description available", tool.inputSchema, tool.execute);
2783
3792
  });
2784
3793
  await this.processToolsWithPlugins(tools, options.mode ?? "agentic");
3794
+ await this.pluginManager.triggerFinalizeComposition(tools, {
3795
+ serverName: name ?? "anonymous",
3796
+ mode: options.mode ?? "agentic",
3797
+ server: this,
3798
+ toolNames: Object.keys(tools)
3799
+ });
2785
3800
  this.onclose = async () => {
2786
3801
  await cleanupClients();
2787
- console.log(`\u{1F9E9} [${name}]`);
2788
- console.log(` \u251C\u2500 Event: closed`);
2789
- console.log(` \u2514\u2500 Action: cleaned up dependent clients`);
3802
+ await this.disposePlugins();
3803
+ await this.logger.info(`[${name}] Event: closed - cleaned up dependent clients and plugins`);
2790
3804
  };
2791
3805
  this.onerror = async (error) => {
2792
- console.log(`\u{1F9E9} [${name}]`);
2793
- console.log(` \u251C\u2500 Event: error, ${error?.stack ?? String(error)}`);
3806
+ await this.logger.error(`[${name}] Event: error - ${error?.stack ?? String(error)}`);
2794
3807
  await cleanupClients();
2795
- console.log(` \u2514\u2500 Action: cleaned up dependent clients`);
3808
+ await this.disposePlugins();
3809
+ await this.logger.info(`[${name}] Action: cleaned up dependent clients and plugins`);
2796
3810
  };
2797
3811
  const toolNameToDetailList = Object.entries(tools);
2798
- const globalToolNames = this.getPublicToolNames();
2799
- const hideToolNames = this.getHiddenToolNames();
2800
- const internalToolNames = this.getInternalToolNames();
2801
- const contextToolNames = toolNameToDetailList.map(([name2]) => name2).filter((n) => !globalToolNames.includes(n) && !hideToolNames.includes(n));
2802
- const allToolNames = [
2803
- ...contextToolNames,
2804
- ...internalToolNames
2805
- ];
2806
- globalToolNames.forEach((toolId) => {
3812
+ const publicToolNames = this.getPublicToolNames();
3813
+ const hiddenToolNames = this.getHiddenToolNames();
3814
+ const contextToolNames = toolNameToDetailList.map(([name2]) => name2).filter((n) => !hiddenToolNames.includes(n));
3815
+ publicToolNames.forEach((toolId) => {
2807
3816
  const tool = tools[toolId];
2808
3817
  if (!tool) {
2809
- throw new Error(`Global tool ${toolId} not found in registry, available: ${Object.keys(tools).join(", ")}`);
3818
+ throw new Error(`Public tool ${toolId} not found in registry, available: ${Object.keys(tools).join(", ")}`);
2810
3819
  }
2811
- this.tool(toolId, tool.description || "No description available", jsonSchema3(tool.inputSchema), tool.execute);
3820
+ this.tool(toolId, tool.description || "No description available", jsonSchema(tool.inputSchema), tool.execute, {
3821
+ internal: false
3822
+ });
2812
3823
  });
2813
- await this.triggerComposeEndHooks({
3824
+ await this.pluginManager.triggerComposeEnd({
2814
3825
  toolName: name,
2815
- pluginNames: this.globalPlugins.map((p2) => p2.name),
3826
+ pluginNames: this.pluginManager.getPluginNames(),
2816
3827
  mode: options.mode ?? "agentic",
2817
- server: this
3828
+ server: this,
3829
+ stats: {
3830
+ totalTools: this.toolManager.getTotalToolCount(),
3831
+ publicTools: publicToolNames.length,
3832
+ hiddenTools: hiddenToolNames.length
3833
+ }
2818
3834
  });
2819
3835
  if (!name) {
2820
3836
  return;
@@ -2827,50 +3843,11 @@ var ComposableMCPServer = class extends Server {
2827
3843
  ...desTags,
2828
3844
  description,
2829
3845
  tools,
2830
- toolOverrides: this.toolConfigs,
3846
+ toolOverrides: /* @__PURE__ */ new Map(),
2831
3847
  toolNameMapping: toolNameToIdMapping
2832
3848
  });
2833
- const depGroups = {};
2834
- toolNameToDetailList.forEach(([toolName, tool]) => {
2835
- if (hideToolNames.includes(this.resolveToolName(toolName) ?? "") || globalToolNames.includes(this.resolveToolName(toolName) ?? "")) {
2836
- return;
2837
- }
2838
- if (!tool) {
2839
- throw new Error(`Action ${toolName} not found, available action list: ${allToolNames.join(", ")}`);
2840
- }
2841
- const baseSchema = (
2842
- // Compatiable with ComposiableleMCPServer.tool() definition
2843
- tool.inputSchema.jsonSchema ?? // Standard definition
2844
- tool.inputSchema ?? {
2845
- type: "object",
2846
- properties: {},
2847
- required: []
2848
- }
2849
- );
2850
- const baseProperties = baseSchema.type === "object" && baseSchema.properties ? baseSchema.properties : {};
2851
- const baseRequired = baseSchema.type === "object" && Array.isArray(baseSchema.required) ? baseSchema.required : [];
2852
- const updatedProperties = updateRefPaths(baseProperties, toolName);
2853
- depGroups[toolName] = {
2854
- type: "object",
2855
- description: tool.description,
2856
- properties: updatedProperties,
2857
- required: [
2858
- ...baseRequired
2859
- ],
2860
- additionalProperties: false
2861
- };
2862
- });
2863
- internalToolNames.forEach((toolName) => {
2864
- const toolSchema = this.getInternalToolSchema(toolName);
2865
- if (toolSchema) {
2866
- depGroups[toolName] = {
2867
- ...toolSchema.schema,
2868
- description: toolSchema.description
2869
- };
2870
- } else {
2871
- throw new Error(`Internal tool schema not found for: ${toolName}`);
2872
- }
2873
- });
3849
+ const allToolNames = contextToolNames;
3850
+ const depGroups = buildDependencyGroups(toolNameToDetailList, hiddenToolNames, publicToolNames, this);
2874
3851
  switch (options.mode ?? "agentic") {
2875
3852
  case "agentic":
2876
3853
  registerAgenticTool(this, {
@@ -2899,18 +3876,36 @@ var ComposableMCPServer = class extends Server {
2899
3876
  }
2900
3877
  };
2901
3878
 
2902
- // ../__mcpc__core_0.2.0-beta.10/node_modules/@mcpc/core/src/utils/common/env.js
2903
- import process4 from "node:process";
2904
- var isProdEnv = () => process4.env.NODE_ENV === "production";
2905
- var isSCF = () => Boolean(process4.env.SCF_RUNTIME || process4.env.PROD_SCF);
3879
+ // ../__mcpc__core_latest/node_modules/@mcpc/core/src/utils/common/env.js
3880
+ import process6 from "node:process";
3881
+ var isProdEnv = () => process6.env.NODE_ENV === "production";
3882
+ var isSCF = () => Boolean(process6.env.SCF_RUNTIME || process6.env.PROD_SCF);
2906
3883
  if (isSCF()) {
2907
3884
  console.log({
2908
3885
  isSCF: isSCF(),
2909
- SCF_RUNTIME: process4.env.SCF_RUNTIME
3886
+ SCF_RUNTIME: process6.env.SCF_RUNTIME
2910
3887
  });
2911
3888
  }
2912
3889
 
2913
- // ../__mcpc__core_0.2.0-beta.10/node_modules/@mcpc/core/src/set-up-mcp-compose.js
3890
+ // ../__mcpc__core_latest/node_modules/@mcpc/core/mod.js
3891
+ init_schema();
3892
+
3893
+ // ../__mcpc__core_latest/node_modules/@mcpc/core/src/ai-sdk-adapter.js
3894
+ function convertToAISDKTools(server, tool, jsonSchema2) {
3895
+ const mcpcTools = server.getPublicTools();
3896
+ return Object.fromEntries(mcpcTools.map((mcpcTool) => [
3897
+ mcpcTool.name,
3898
+ tool({
3899
+ description: mcpcTool.description || "No description",
3900
+ parameters: jsonSchema2(mcpcTool.inputSchema),
3901
+ execute: async (input) => {
3902
+ return await server.callTool(mcpcTool.name, input);
3903
+ }
3904
+ })
3905
+ ]));
3906
+ }
3907
+
3908
+ // ../__mcpc__core_latest/node_modules/@mcpc/core/src/set-up-mcp-compose.js
2914
3909
  function parseMcpcConfigs(conf) {
2915
3910
  const mcpcConfigs = conf ?? [];
2916
3911
  const newMcpcConfigs = [];
@@ -2950,11 +3945,18 @@ async function mcpc(serverConf, composeConf, setupCallback) {
2950
3945
  }
2951
3946
  return server;
2952
3947
  }
3948
+
3949
+ // ../__mcpc__core_latest/node_modules/@mcpc/core/mod.ts
3950
+ init_schema();
2953
3951
  export {
2954
3952
  ComposableMCPServer,
2955
3953
  composeMcpDepTools,
3954
+ convertToAISDKTools,
3955
+ extractJsonSchema,
2956
3956
  isProdEnv,
2957
3957
  isSCF,
3958
+ isWrappedSchema,
3959
+ jsonSchema,
2958
3960
  mcpc,
2959
3961
  optionalObject,
2960
3962
  parseJSON2 as parseJSON,