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

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