mcponce 0.2.3 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/README.md +8 -8
  2. package/dist/cli/bin.d.ts.map +1 -1
  3. package/dist/cli/bin.js +6 -1
  4. package/dist/cli/bin.js.map +1 -1
  5. package/dist/cli/index.d.ts.map +1 -1
  6. package/dist/cli/index.js +6 -1
  7. package/dist/cli/index.js.map +1 -1
  8. package/dist/cli/installer.d.ts +15 -4
  9. package/dist/cli/installer.d.ts.map +1 -1
  10. package/dist/cli/installer.js +162 -25
  11. package/dist/cli/installer.js.map +1 -1
  12. package/dist/cli/tool-caller.d.ts.map +1 -1
  13. package/dist/cli/tool-caller.js +1 -0
  14. package/dist/cli/tool-caller.js.map +1 -1
  15. package/dist/index.d.ts +7 -6
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +4 -3
  18. package/dist/index.js.map +1 -1
  19. package/dist/logging/file-logger.d.ts.map +1 -1
  20. package/dist/logging/file-logger.js +1 -4
  21. package/dist/logging/file-logger.js.map +1 -1
  22. package/dist/logging/mcp-logger.d.ts +15 -0
  23. package/dist/logging/mcp-logger.d.ts.map +1 -0
  24. package/dist/logging/mcp-logger.js +46 -0
  25. package/dist/logging/mcp-logger.js.map +1 -0
  26. package/dist/registry/central.d.ts.map +1 -1
  27. package/dist/registry/central.js +2 -10
  28. package/dist/registry/central.js.map +1 -1
  29. package/dist/registry/tools.d.ts +1 -1
  30. package/dist/registry/tools.d.ts.map +1 -1
  31. package/dist/registry/tools.js +85 -18
  32. package/dist/registry/tools.js.map +1 -1
  33. package/dist/runtime/config.d.ts +7 -1
  34. package/dist/runtime/config.d.ts.map +1 -1
  35. package/dist/runtime/config.js +8 -0
  36. package/dist/runtime/config.js.map +1 -1
  37. package/dist/runtime/instance.d.ts.map +1 -1
  38. package/dist/runtime/instance.js +7 -2
  39. package/dist/runtime/instance.js.map +1 -1
  40. package/dist/runtime/lock.d.ts +4 -2
  41. package/dist/runtime/lock.d.ts.map +1 -1
  42. package/dist/runtime/lock.js +26 -37
  43. package/dist/runtime/lock.js.map +1 -1
  44. package/dist/runtime/paths.d.ts.map +1 -1
  45. package/dist/runtime/paths.js +8 -1
  46. package/dist/runtime/paths.js.map +1 -1
  47. package/dist/runtime/state.d.ts.map +1 -1
  48. package/dist/runtime/state.js +4 -11
  49. package/dist/runtime/state.js.map +1 -1
  50. package/dist/runtime/unitup.d.ts +10 -2
  51. package/dist/runtime/unitup.d.ts.map +1 -1
  52. package/dist/runtime/unitup.js +96 -3
  53. package/dist/runtime/unitup.js.map +1 -1
  54. package/dist/server/app.d.ts +34 -1
  55. package/dist/server/app.d.ts.map +1 -1
  56. package/dist/server/app.js +406 -199
  57. package/dist/server/app.js.map +1 -1
  58. package/dist/server/hono.d.ts +3 -0
  59. package/dist/server/hono.d.ts.map +1 -1
  60. package/dist/server/hono.js +176 -50
  61. package/dist/server/hono.js.map +1 -1
  62. package/dist/server/inspector.d.ts.map +1 -1
  63. package/dist/server/inspector.js +12 -2
  64. package/dist/server/inspector.js.map +1 -1
  65. package/dist/server/mcp.d.ts +25 -5
  66. package/dist/server/mcp.d.ts.map +1 -1
  67. package/dist/server/mcp.js +422 -295
  68. package/dist/server/mcp.js.map +1 -1
  69. package/dist/transport/proxy.d.ts.map +1 -1
  70. package/dist/transport/proxy.js +18 -16
  71. package/dist/transport/proxy.js.map +1 -1
  72. package/dist/types.d.ts +177 -4
  73. package/dist/types.d.ts.map +1 -1
  74. package/dist/utils/cache.d.ts.map +1 -1
  75. package/dist/utils/cache.js +3 -2
  76. package/dist/utils/cache.js.map +1 -1
  77. package/dist/utils/coercion.d.ts +3 -3
  78. package/dist/utils/coercion.d.ts.map +1 -1
  79. package/dist/utils/coercion.js +101 -12
  80. package/dist/utils/coercion.js.map +1 -1
  81. package/dist/utils/elicitation.d.ts +34 -0
  82. package/dist/utils/elicitation.d.ts.map +1 -0
  83. package/dist/utils/elicitation.js +136 -0
  84. package/dist/utils/elicitation.js.map +1 -0
  85. package/dist/utils/media.d.ts +41 -6
  86. package/dist/utils/media.d.ts.map +1 -1
  87. package/dist/utils/media.js +162 -7
  88. package/dist/utils/media.js.map +1 -1
  89. package/dist/utils/retry.d.ts +20 -1
  90. package/dist/utils/retry.d.ts.map +1 -1
  91. package/dist/utils/retry.js +103 -7
  92. package/dist/utils/retry.js.map +1 -1
  93. package/dist/utils/security.d.ts +12 -0
  94. package/dist/utils/security.d.ts.map +1 -1
  95. package/dist/utils/security.js +47 -0
  96. package/dist/utils/security.js.map +1 -1
  97. package/package.json +14 -5
@@ -3,11 +3,23 @@ import { z } from 'zod';
3
3
  import { SubscribeRequestSchema, UnsubscribeRequestSchema, RootsListChangedNotificationSchema, CompleteRequestSchema } from '@modelcontextprotocol/sdk/types.js';
4
4
  import { completable } from '@modelcontextprotocol/sdk/server/completable.js';
5
5
  import { resolveCompletion } from '../utils/completion.js';
6
+ import { normalizeInputSchema } from '../registry/tools.js';
6
7
  import { createProgressReporter } from '../utils/progress.js';
8
+ import { createToolLogger } from '../logging/mcp-logger.js';
7
9
  import { composeMiddleware } from '../utils/middleware.js';
8
10
  import { verifyToolScopes } from '../utils/security.js';
9
11
  import { executeSample, executeListRoots } from '../utils/sampling.js';
10
- import { normalizeContentItem, normalizeResourceResult, ImageContentHelper, isImageContent } from '../utils/media.js';
12
+ import { executeElicit } from '../utils/elicitation.js';
13
+ import { normalizeContentItem, normalizeResourceResult, ImageContentHelper, AudioContentHelper, isImageContent, isAudioContent, isResourceLink } from '../utils/media.js';
14
+ function summarizeNonTextContent(c) {
15
+ if (c.type === 'image')
16
+ return `[Image: ${c.mimeType}]`;
17
+ if (c.type === 'audio')
18
+ return `[Audio: ${c.mimeType}]`;
19
+ if (c.type === 'resource_link')
20
+ return `[ResourceLink: ${c.uri}]`;
21
+ return `[${c.type}]`;
22
+ }
11
23
  export function normalizeToolResult(rawResult) {
12
24
  if (rawResult === undefined || rawResult === null) {
13
25
  return {
@@ -32,14 +44,38 @@ export function normalizeToolResult(rawResult) {
32
44
  text: `[Image: ${rawResult.mimeType}]`
33
45
  };
34
46
  }
35
- // Direct Buffer or Uint8Array returned by tool
36
- if (Buffer.isBuffer(rawResult) || rawResult instanceof Uint8Array) {
37
- const img = normalizeContentItem(rawResult);
38
- const mime = img.mimeType || 'application/octet-stream';
47
+ // Direct AudioContentHelper or isAudioContent
48
+ if (rawResult instanceof AudioContentHelper) {
49
+ const item = rawResult.toJSON();
50
+ return {
51
+ content: [item],
52
+ data: rawResult,
53
+ text: `[Audio: ${item.mimeType}]`
54
+ };
55
+ }
56
+ if (isAudioContent(rawResult)) {
57
+ return {
58
+ content: [rawResult],
59
+ data: rawResult,
60
+ text: `[Audio: ${rawResult.mimeType}]`
61
+ };
62
+ }
63
+ // Direct ResourceLink
64
+ if (isResourceLink(rawResult)) {
65
+ return {
66
+ content: [rawResult],
67
+ data: rawResult,
68
+ text: `[ResourceLink: ${rawResult.uri}]`
69
+ };
70
+ }
71
+ // Direct Buffer, Uint8Array, or ArrayBuffer returned by tool
72
+ if (Buffer.isBuffer(rawResult) || rawResult instanceof Uint8Array || rawResult instanceof ArrayBuffer) {
73
+ const raw = rawResult instanceof ArrayBuffer ? new Uint8Array(rawResult) : rawResult;
74
+ const item = normalizeContentItem(raw);
39
75
  return {
40
- content: [img],
76
+ content: [item],
41
77
  data: rawResult,
42
- text: `[Image: ${mime}]`
78
+ text: summarizeNonTextContent(item)
43
79
  };
44
80
  }
45
81
  // Standard MCP result with content array
@@ -50,7 +86,7 @@ export function normalizeToolResult(rawResult) {
50
86
  .map((c) => c.text);
51
87
  const fallbackText = textPieces.length > 0
52
88
  ? textPieces.join('\n')
53
- : normalizedContent.map((c) => (c.type === 'image' ? `[Image: ${c.mimeType}]` : `[${c.type}]`)).join(' ');
89
+ : normalizedContent.map(summarizeNonTextContent).join(' ');
54
90
  return {
55
91
  ...rawResult,
56
92
  content: normalizedContent,
@@ -66,23 +102,23 @@ export function normalizeToolResult(rawResult) {
66
102
  .map((c) => c.text);
67
103
  const fallbackText = textPieces.length > 0
68
104
  ? textPieces.join('\n')
69
- : normalizedContent.map((c) => (c.type === 'image' ? `[Image: ${c.mimeType}]` : `[${c.type}]`)).join(' ');
105
+ : normalizedContent.map(summarizeNonTextContent).join(' ');
70
106
  return {
71
107
  content: normalizedContent,
72
108
  data: rawResult,
73
109
  text: fallbackText
74
110
  };
75
111
  }
76
- // Shorthand object with image / resource
112
+ // Shorthand object with image / audio / resourceLink / resource
77
113
  if (rawResult &&
78
114
  typeof rawResult === 'object' &&
79
- ('image' in rawResult || 'resource' in rawResult)) {
115
+ ('image' in rawResult || 'audio' in rawResult || 'resourceLink' in rawResult || 'resource' in rawResult)) {
80
116
  const item = normalizeContentItem(rawResult);
81
117
  const content = [item];
82
118
  if ('text' in rawResult && typeof rawResult.text === 'string' && rawResult.text.trim()) {
83
119
  content.unshift({ type: 'text', text: rawResult.text });
84
120
  }
85
- const textDesc = rawResult.text || (item.type === 'image' ? `[Image: ${item.mimeType}]` : `[${item.type}]`);
121
+ const textDesc = rawResult.text || summarizeNonTextContent(item);
86
122
  return {
87
123
  content,
88
124
  data: rawResult,
@@ -110,16 +146,382 @@ export function normalizeToolResult(rawResult) {
110
146
  };
111
147
  }
112
148
  import { executeWithRetry, raceWithSignal } from '../utils/retry.js';
149
+ export function normalizeOutputSchema(schema) {
150
+ if (!schema) {
151
+ return undefined;
152
+ }
153
+ if (typeof schema === 'object' && '_def' in schema) {
154
+ return schema;
155
+ }
156
+ if (typeof schema === 'object') {
157
+ return normalizeInputSchema(schema);
158
+ }
159
+ return schema;
160
+ }
161
+ export function createToolCallback(server, tool, options, ctx) {
162
+ return async (args, extraFromMcp) => {
163
+ const start = Date.now();
164
+ options.logger?.info('tool:start', { name: tool.name });
165
+ options.onToolCalled?.(tool.name);
166
+ if (tool.requireAuth && !options.auth) {
167
+ throw new Error(`Authentication required for tool "${tool.name}"`);
168
+ }
169
+ if (tool.scopes && tool.scopes.length > 0) {
170
+ if (!verifyToolScopes(tool.scopes, options.auth?.scopes)) {
171
+ throw new Error(`Forbidden: Tool "${tool.name}" requires scopes: ${tool.scopes.join(', ')}`);
172
+ }
173
+ }
174
+ const cacheConfig = typeof tool.cache === 'object' ? tool.cache : (tool.cache ? {} : undefined);
175
+ if (cacheConfig && options.cacheManager) {
176
+ const cached = options.cacheManager.get(tool.name, args, cacheConfig);
177
+ if (cached) {
178
+ const durationMs = Date.now() - start;
179
+ options.analytics?.recordInvocation({
180
+ tool: tool.name,
181
+ durationMs,
182
+ status: 'success',
183
+ isCacheHit: true
184
+ });
185
+ if (options.metrics) {
186
+ options.metrics.lastToolInvocation = {
187
+ name: tool.name,
188
+ timestamp: new Date().toISOString()
189
+ };
190
+ }
191
+ options.logger?.info('tool:cache_hit', { name: tool.name, durationMs });
192
+ return normalizeToolResult(cached);
193
+ }
194
+ }
195
+ const effectiveTimeout = tool.timeoutMs !== undefined
196
+ ? tool.timeoutMs
197
+ : (options.defaultTimeoutMs !== undefined ? options.defaultTimeoutMs : 60000);
198
+ const timeoutController = effectiveTimeout > 0 ? new AbortController() : null;
199
+ let timeoutTimer;
200
+ if (effectiveTimeout > 0 && timeoutController) {
201
+ timeoutTimer = setTimeout(() => {
202
+ timeoutController.abort(new Error(`Tool "${tool.name}" execution timed out after ${effectiveTimeout}ms`));
203
+ }, effectiveTimeout);
204
+ }
205
+ const signals = [];
206
+ if (extraFromMcp?.signal) {
207
+ signals.push(extraFromMcp.signal);
208
+ }
209
+ if (timeoutController) {
210
+ signals.push(timeoutController.signal);
211
+ }
212
+ const mergedSignal = signals.length > 1
213
+ ? (typeof AbortSignal.any === 'function' ? AbortSignal.any(signals) : signals[0])
214
+ : signals[0];
215
+ const queueConfig = options.resolveQueueConfig?.(tool);
216
+ let release;
217
+ let retriesCount = 0;
218
+ try {
219
+ if (queueConfig && options.queueManager) {
220
+ release = await options.queueManager.getQueue(queueConfig.key, queueConfig.maxConcurrency).acquire(mergedSignal);
221
+ }
222
+ const callToolHelper = options.callTool
223
+ ? (targetName, targetArgs = {}, targetOptions) => {
224
+ const mergedTargetOptions = {
225
+ ...targetOptions,
226
+ auth: targetOptions?.auth || options.auth
227
+ };
228
+ return options.callTool(targetName, targetArgs, mergedTargetOptions, [tool.name]);
229
+ }
230
+ : undefined;
231
+ const clearCacheHelper = (targetToolName) => {
232
+ return options.cacheManager ? options.cacheManager.clear(targetToolName) : 0;
233
+ };
234
+ const progressToken = extraFromMcp?._meta?.progressToken;
235
+ const reportProgress = createProgressReporter({
236
+ toolName: tool.name,
237
+ progressToken,
238
+ sendMcpNotification: extraFromMcp?.sendNotification
239
+ ? (notif) => extraFromMcp.sendNotification(notif)
240
+ : undefined,
241
+ logger: options.logger
242
+ });
243
+ const sampleHelper = (input, opts) => {
244
+ return executeSample(input, opts, server, options.onSample, mergedSignal);
245
+ };
246
+ const listRootsHelper = () => {
247
+ return executeListRoots(server, options.onListRoots, mergedSignal);
248
+ };
249
+ const elicitHelper = (elicitOpts) => {
250
+ return executeElicit(elicitOpts, server, options.onElicit, mergedSignal);
251
+ };
252
+ const logHelper = createToolLogger({
253
+ toolName: tool.name,
254
+ server,
255
+ sessionId: options.sessionId,
256
+ localLogger: options.logger
257
+ });
258
+ const handlerCtx = ctx && typeof ctx === 'object'
259
+ ? (callToolHelper
260
+ ? Object.assign(Object.create(Object.getPrototypeOf(ctx)), ctx, {
261
+ callTool: callToolHelper,
262
+ signal: mergedSignal,
263
+ clearCache: clearCacheHelper,
264
+ reportProgress,
265
+ sample: sampleHelper,
266
+ listRoots: listRootsHelper,
267
+ elicit: elicitHelper,
268
+ auth: options.auth,
269
+ log: logHelper
270
+ })
271
+ : Object.assign(Object.create(Object.getPrototypeOf(ctx)), ctx, {
272
+ signal: mergedSignal,
273
+ clearCache: clearCacheHelper,
274
+ reportProgress,
275
+ sample: sampleHelper,
276
+ listRoots: listRootsHelper,
277
+ elicit: elicitHelper,
278
+ auth: options.auth,
279
+ log: logHelper
280
+ }))
281
+ : {
282
+ callTool: callToolHelper,
283
+ signal: mergedSignal,
284
+ clearCache: clearCacheHelper,
285
+ reportProgress,
286
+ sample: sampleHelper,
287
+ listRoots: listRootsHelper,
288
+ elicit: elicitHelper,
289
+ auth: options.auth,
290
+ log: logHelper
291
+ };
292
+ const extra = {
293
+ signal: mergedSignal,
294
+ callTool: (callToolHelper || (() => Promise.reject(new Error('callTool is not available in this context')))),
295
+ clearCache: clearCacheHelper,
296
+ reportProgress,
297
+ progressToken,
298
+ sample: sampleHelper,
299
+ listRoots: listRootsHelper,
300
+ elicit: elicitHelper,
301
+ auth: options.auth,
302
+ log: logHelper
303
+ };
304
+ const middlewarePipeline = options.middlewareManager
305
+ ? options.middlewareManager.composeForTool(tool.name, (pCtx) => Promise.resolve(tool.handler(pCtx.args, pCtx.context, pCtx.extra)), tool.middleware)
306
+ : tool.middleware && tool.middleware.length > 0
307
+ ? composeMiddleware(tool.middleware, (pCtx) => Promise.resolve(tool.handler(pCtx.args, pCtx.context, pCtx.extra)))
308
+ : null;
309
+ const runAttempt = () => {
310
+ if (middlewarePipeline) {
311
+ const middlewareCtx = {
312
+ tool: tool.name,
313
+ args: args || {},
314
+ context: handlerCtx,
315
+ extra,
316
+ callStack: []
317
+ };
318
+ const executionPromise = middlewarePipeline(middlewareCtx);
319
+ return raceWithSignal(executionPromise, mergedSignal, () => new Error(`Tool "${tool.name}" execution was cancelled`));
320
+ }
321
+ const executionPromise = Promise.resolve(tool.handler(args, handlerCtx, extra));
322
+ return raceWithSignal(executionPromise, mergedSignal, () => new Error(`Tool "${tool.name}" execution was cancelled`));
323
+ };
324
+ const { result: rawResult, retries } = await executeWithRetry(runAttempt, {
325
+ name: tool.name,
326
+ config: tool.retry,
327
+ signal: mergedSignal,
328
+ onRetry: (err, attempt, delayMs) => {
329
+ options.logger?.warn('tool:retry', {
330
+ name: tool.name,
331
+ attempt,
332
+ delayMs,
333
+ error: err?.message || String(err)
334
+ });
335
+ }
336
+ });
337
+ retriesCount = retries;
338
+ const durationMs = Date.now() - start;
339
+ options.analytics?.recordInvocation({
340
+ tool: tool.name,
341
+ durationMs,
342
+ status: 'success',
343
+ retries: retriesCount
344
+ });
345
+ if (options.metrics) {
346
+ options.metrics.lastToolInvocation = {
347
+ name: tool.name,
348
+ timestamp: new Date().toISOString()
349
+ };
350
+ }
351
+ options.logger?.info('tool:end', { name: tool.name, durationMs });
352
+ const normalized = normalizeToolResult(rawResult);
353
+ if (tool.outputSchema && !normalized.structuredContent) {
354
+ if (rawResult && typeof rawResult === 'object') {
355
+ if ('structuredContent' in rawResult) {
356
+ normalized.structuredContent = rawResult.structuredContent;
357
+ }
358
+ else if ('data' in rawResult && typeof rawResult.data === 'object' && rawResult.data !== null) {
359
+ normalized.structuredContent = rawResult.data;
360
+ }
361
+ else if (!('content' in rawResult)) {
362
+ normalized.structuredContent = rawResult;
363
+ }
364
+ else if (rawResult.data !== undefined) {
365
+ normalized.structuredContent = rawResult.data;
366
+ }
367
+ }
368
+ }
369
+ if (cacheConfig && options.cacheManager && !normalized.isError) {
370
+ options.cacheManager.set(tool.name, args, normalized, cacheConfig);
371
+ }
372
+ return normalized;
373
+ }
374
+ catch (error) {
375
+ const durationMs = Date.now() - start;
376
+ const isTimeout = String(error?.message || error).includes('timed out');
377
+ const isCancelled = Boolean(mergedSignal?.aborted && !isTimeout);
378
+ const status = isTimeout ? 'timeout' : (isCancelled ? 'cancelled' : 'error');
379
+ options.analytics?.recordInvocation({
380
+ tool: tool.name,
381
+ durationMs,
382
+ status,
383
+ errorMessage: error.message || String(error),
384
+ retries: retriesCount || (error?.retries ?? 0)
385
+ });
386
+ if (options.metrics) {
387
+ options.metrics.lastToolInvocation = {
388
+ name: tool.name,
389
+ timestamp: new Date().toISOString()
390
+ };
391
+ }
392
+ options.logger?.error('tool:error', {
393
+ name: tool.name,
394
+ durationMs,
395
+ isTimeout,
396
+ isCancelled,
397
+ error: error.message || String(error),
398
+ stack: error.stack
399
+ });
400
+ return {
401
+ isError: true,
402
+ content: [
403
+ {
404
+ type: 'text',
405
+ text: `Error in tool "${tool.name}": ${error.message || String(error)}`
406
+ }
407
+ ]
408
+ };
409
+ }
410
+ finally {
411
+ if (timeoutTimer) {
412
+ clearTimeout(timeoutTimer);
413
+ }
414
+ release?.();
415
+ }
416
+ };
417
+ }
418
+ export function registerSingleTool(server, tool, options, ctx) {
419
+ if (server._registeredTools?.[tool.name]) {
420
+ return;
421
+ }
422
+ const callback = createToolCallback(server, tool, options, ctx);
423
+ server.registerTool(tool.name, {
424
+ title: tool.title,
425
+ description: tool.description,
426
+ inputSchema: tool.normalizedSchema,
427
+ outputSchema: normalizeOutputSchema(tool.outputSchema),
428
+ annotations: tool.annotations
429
+ }, callback);
430
+ }
431
+ export function registerSingleResource(server, res, ctx) {
432
+ if (server._registeredResources?.[res.uri]) {
433
+ return;
434
+ }
435
+ server.registerResource(res.name || res.uri, res.uri, {
436
+ title: res.title,
437
+ description: res.description,
438
+ mimeType: res.mimeType,
439
+ icons: res.icons
440
+ }, async (uri) => {
441
+ const raw = await res.handler(uri, ctx);
442
+ return normalizeResourceResult(raw, uri, res.mimeType);
443
+ });
444
+ }
445
+ export function registerSingleTemplate(server, tpl, ctx) {
446
+ const resourceTemplate = new ResourceTemplate(tpl.uriTemplate, {
447
+ list: tpl.list
448
+ ? async () => {
449
+ const result = await tpl.list(ctx);
450
+ if (Array.isArray(result)) {
451
+ return { resources: result };
452
+ }
453
+ return result;
454
+ }
455
+ : undefined,
456
+ complete: tpl.complete
457
+ });
458
+ server.registerResource(tpl.name || tpl.uriTemplate, resourceTemplate, {
459
+ title: tpl.title,
460
+ description: tpl.description,
461
+ mimeType: tpl.mimeType,
462
+ icons: tpl.icons
463
+ }, async (uri, variables) => {
464
+ const params = {};
465
+ for (const [k, v] of Object.entries(variables || {})) {
466
+ params[k] = Array.isArray(v) ? v.join(',') : String(v);
467
+ }
468
+ const raw = await tpl.handler(uri, params, ctx);
469
+ return normalizeResourceResult(raw, uri, tpl.mimeType);
470
+ });
471
+ }
472
+ export function registerSinglePrompt(server, prompt, ctx) {
473
+ if (server._registeredPrompts?.[prompt.name]) {
474
+ return;
475
+ }
476
+ let argsSchema = prompt.argsSchema;
477
+ if (argsSchema && prompt.complete) {
478
+ const wrappedSchema = {};
479
+ for (const [key, field] of Object.entries(argsSchema)) {
480
+ const zodField = typeof field === 'string' ? z.string() : field;
481
+ if (prompt.complete[key]) {
482
+ wrappedSchema[key] = completable(zodField, async (val, context) => {
483
+ const list = await prompt.complete[key](val, context);
484
+ return Array.isArray(list) ? list : [];
485
+ });
486
+ }
487
+ else {
488
+ wrappedSchema[key] = zodField;
489
+ }
490
+ }
491
+ argsSchema = wrappedSchema;
492
+ }
493
+ server.registerPrompt(prompt.name, {
494
+ title: prompt.title,
495
+ description: prompt.description,
496
+ argsSchema: argsSchema
497
+ }, async (args) => {
498
+ return await prompt.handler(args, ctx);
499
+ });
500
+ }
113
501
  export function createSessionMcpServer(options) {
114
502
  const server = new McpServer({
115
503
  name: options.name,
116
- version: options.version
504
+ version: options.version,
505
+ ...(options.title ? { title: options.title } : {}),
506
+ ...(options.description ? { description: options.description } : {}),
507
+ ...(options.websiteUrl ? { websiteUrl: options.websiteUrl } : {}),
508
+ ...(options.icons ? { icons: options.icons } : {})
509
+ }, {
510
+ capabilities: {
511
+ logging: {}
512
+ }
117
513
  });
118
- // Register capabilities for resource subscriptions and list updates
514
+ // Register capabilities for tools, resources subscriptions/list updates, and prompts list updates
119
515
  server.server.registerCapabilities({
516
+ tools: {
517
+ listChanged: true
518
+ },
120
519
  resources: {
121
520
  subscribe: true,
122
521
  listChanged: true
522
+ },
523
+ prompts: {
524
+ listChanged: true
123
525
  }
124
526
  });
125
527
  // Handle client resource subscriptions
@@ -154,296 +556,19 @@ export function createSessionMcpServer(options) {
154
556
  const ctx = options.contextManager.getContext();
155
557
  // Register all tools
156
558
  for (const tool of options.toolRegistry.getAll()) {
157
- server.registerTool(tool.name, {
158
- description: tool.description,
159
- inputSchema: tool.normalizedSchema
160
- }, async (args, extraFromMcp) => {
161
- const start = Date.now();
162
- options.logger?.info('tool:start', { name: tool.name });
163
- options.onToolCalled?.(tool.name);
164
- if (tool.requireAuth && !options.auth) {
165
- throw new Error(`Authentication required for tool "${tool.name}"`);
166
- }
167
- if (tool.scopes && tool.scopes.length > 0) {
168
- if (!verifyToolScopes(tool.scopes, options.auth?.scopes)) {
169
- throw new Error(`Forbidden: Tool "${tool.name}" requires scopes: ${tool.scopes.join(', ')}`);
170
- }
171
- }
172
- const cacheConfig = typeof tool.cache === 'object' ? tool.cache : (tool.cache ? {} : undefined);
173
- if (cacheConfig && options.cacheManager) {
174
- const cached = options.cacheManager.get(tool.name, args, cacheConfig);
175
- if (cached) {
176
- const durationMs = Date.now() - start;
177
- options.analytics?.recordInvocation({
178
- tool: tool.name,
179
- durationMs,
180
- status: 'success',
181
- isCacheHit: true
182
- });
183
- if (options.metrics) {
184
- options.metrics.lastToolInvocation = {
185
- name: tool.name,
186
- timestamp: new Date().toISOString()
187
- };
188
- }
189
- options.logger?.info('tool:cache_hit', { name: tool.name, durationMs });
190
- return normalizeToolResult(cached);
191
- }
192
- }
193
- const effectiveTimeout = tool.timeoutMs !== undefined
194
- ? tool.timeoutMs
195
- : (options.defaultTimeoutMs !== undefined ? options.defaultTimeoutMs : 60000);
196
- const timeoutController = effectiveTimeout > 0 ? new AbortController() : null;
197
- let timeoutTimer;
198
- if (effectiveTimeout > 0 && timeoutController) {
199
- timeoutTimer = setTimeout(() => {
200
- timeoutController.abort(new Error(`Tool "${tool.name}" execution timed out after ${effectiveTimeout}ms`));
201
- }, effectiveTimeout);
202
- }
203
- const signals = [];
204
- if (extraFromMcp?.signal) {
205
- signals.push(extraFromMcp.signal);
206
- }
207
- if (timeoutController) {
208
- signals.push(timeoutController.signal);
209
- }
210
- const mergedSignal = signals.length > 1
211
- ? (typeof AbortSignal.any === 'function' ? AbortSignal.any(signals) : signals[0])
212
- : signals[0];
213
- const queueConfig = options.resolveQueueConfig?.(tool);
214
- let release;
215
- let retriesCount = 0;
216
- try {
217
- if (queueConfig && options.queueManager) {
218
- release = await options.queueManager.getQueue(queueConfig.key, queueConfig.maxConcurrency).acquire(mergedSignal);
219
- }
220
- const callToolHelper = options.callTool
221
- ? (targetName, targetArgs = {}, targetOptions) => {
222
- const mergedTargetOptions = {
223
- ...targetOptions,
224
- auth: targetOptions?.auth || options.auth
225
- };
226
- return options.callTool(targetName, targetArgs, mergedTargetOptions, [tool.name]);
227
- }
228
- : undefined;
229
- const clearCacheHelper = (targetToolName) => {
230
- return options.cacheManager ? options.cacheManager.clear(targetToolName) : 0;
231
- };
232
- const progressToken = extraFromMcp?._meta?.progressToken;
233
- const reportProgress = createProgressReporter({
234
- toolName: tool.name,
235
- progressToken,
236
- sendMcpNotification: extraFromMcp?.sendNotification
237
- ? (notif) => extraFromMcp.sendNotification(notif)
238
- : undefined,
239
- logger: options.logger
240
- });
241
- const sampleHelper = (input, opts) => {
242
- return executeSample(input, opts, server, options.onSample, mergedSignal);
243
- };
244
- const listRootsHelper = () => {
245
- return executeListRoots(server, options.onListRoots, mergedSignal);
246
- };
247
- const handlerCtx = ctx && typeof ctx === 'object'
248
- ? (callToolHelper
249
- ? Object.assign(Object.create(Object.getPrototypeOf(ctx)), ctx, {
250
- callTool: callToolHelper,
251
- signal: mergedSignal,
252
- clearCache: clearCacheHelper,
253
- reportProgress,
254
- sample: sampleHelper,
255
- listRoots: listRootsHelper,
256
- auth: options.auth
257
- })
258
- : Object.assign(Object.create(Object.getPrototypeOf(ctx)), ctx, {
259
- signal: mergedSignal,
260
- clearCache: clearCacheHelper,
261
- reportProgress,
262
- sample: sampleHelper,
263
- listRoots: listRootsHelper,
264
- auth: options.auth
265
- }))
266
- : {
267
- callTool: callToolHelper,
268
- signal: mergedSignal,
269
- clearCache: clearCacheHelper,
270
- reportProgress,
271
- sample: sampleHelper,
272
- listRoots: listRootsHelper,
273
- auth: options.auth
274
- };
275
- const extra = {
276
- signal: mergedSignal,
277
- callTool: (callToolHelper || (() => Promise.reject(new Error('callTool is not available in this context')))),
278
- clearCache: clearCacheHelper,
279
- reportProgress,
280
- progressToken,
281
- sample: sampleHelper,
282
- listRoots: listRootsHelper,
283
- auth: options.auth
284
- };
285
- const middlewarePipeline = options.middlewareManager
286
- ? options.middlewareManager.composeForTool(tool.name, (pCtx) => Promise.resolve(tool.handler(pCtx.args, pCtx.context, pCtx.extra)), tool.middleware)
287
- : tool.middleware && tool.middleware.length > 0
288
- ? composeMiddleware(tool.middleware, (pCtx) => Promise.resolve(tool.handler(pCtx.args, pCtx.context, pCtx.extra)))
289
- : null;
290
- const runAttempt = () => {
291
- if (middlewarePipeline) {
292
- const middlewareCtx = {
293
- tool: tool.name,
294
- args: args || {},
295
- context: handlerCtx,
296
- extra,
297
- callStack: []
298
- };
299
- const executionPromise = middlewarePipeline(middlewareCtx);
300
- return raceWithSignal(executionPromise, mergedSignal, () => new Error(`Tool "${tool.name}" execution was cancelled`));
301
- }
302
- const executionPromise = Promise.resolve(tool.handler(args, handlerCtx, extra));
303
- return raceWithSignal(executionPromise, mergedSignal, () => new Error(`Tool "${tool.name}" execution was cancelled`));
304
- };
305
- const { result: rawResult, retries } = await executeWithRetry(runAttempt, {
306
- name: tool.name,
307
- config: tool.retry,
308
- signal: mergedSignal,
309
- onRetry: (err, attempt, delayMs) => {
310
- options.logger?.warn('tool:retry', {
311
- name: tool.name,
312
- attempt,
313
- delayMs,
314
- error: err?.message || String(err)
315
- });
316
- }
317
- });
318
- retriesCount = retries;
319
- const durationMs = Date.now() - start;
320
- const normalized = normalizeToolResult(rawResult);
321
- const status = normalized.isError ? 'error' : 'success';
322
- const errorMsg = normalized.isError ? normalized.content?.[0]?.text : undefined;
323
- options.analytics?.recordInvocation({
324
- tool: tool.name,
325
- durationMs,
326
- status,
327
- errorMessage: errorMsg,
328
- retries: retriesCount
329
- });
330
- if (options.metrics) {
331
- options.metrics.lastToolInvocation = {
332
- name: tool.name,
333
- timestamp: new Date().toISOString()
334
- };
335
- }
336
- options.logger?.info('tool:end', { name: tool.name, durationMs });
337
- if (cacheConfig && options.cacheManager && !normalized.isError) {
338
- options.cacheManager.set(tool.name, args, normalized, cacheConfig);
339
- }
340
- return normalized;
341
- }
342
- catch (error) {
343
- const durationMs = Date.now() - start;
344
- const isTimeout = String(error?.message || error).includes('timed out');
345
- const isCancelled = Boolean(mergedSignal?.aborted && !isTimeout);
346
- const status = isTimeout ? 'timeout' : (isCancelled ? 'cancelled' : 'error');
347
- options.analytics?.recordInvocation({
348
- tool: tool.name,
349
- durationMs,
350
- status,
351
- errorMessage: error.message || String(error),
352
- retries: retriesCount || (error?.retries ?? 0)
353
- });
354
- if (options.metrics) {
355
- options.metrics.lastToolInvocation = {
356
- name: tool.name,
357
- timestamp: new Date().toISOString()
358
- };
359
- }
360
- options.logger?.error('tool:error', {
361
- name: tool.name,
362
- durationMs,
363
- isTimeout,
364
- isCancelled,
365
- error: error.message || String(error),
366
- stack: error.stack
367
- });
368
- return {
369
- isError: true,
370
- content: [
371
- {
372
- type: 'text',
373
- text: `Error in tool "${tool.name}": ${error.message || String(error)}`
374
- }
375
- ]
376
- };
377
- }
378
- finally {
379
- if (timeoutTimer) {
380
- clearTimeout(timeoutTimer);
381
- }
382
- release?.();
383
- }
384
- });
559
+ registerSingleTool(server, tool, options, ctx);
385
560
  }
386
561
  // Register all static resources
387
562
  for (const res of options.resourceRegistry.getAll()) {
388
- server.registerResource(res.name || res.uri, res.uri, {
389
- description: res.description,
390
- mimeType: res.mimeType
391
- }, async (uri) => {
392
- const raw = await res.handler(uri, ctx);
393
- return normalizeResourceResult(raw, uri, res.mimeType);
394
- });
563
+ registerSingleResource(server, res, ctx);
395
564
  }
396
565
  // Register all dynamic resource templates
397
566
  for (const tpl of options.resourceRegistry.getAllTemplates()) {
398
- const resourceTemplate = new ResourceTemplate(tpl.uriTemplate, {
399
- list: tpl.list
400
- ? async () => {
401
- const result = await tpl.list(ctx);
402
- if (Array.isArray(result)) {
403
- return { resources: result };
404
- }
405
- return result;
406
- }
407
- : undefined,
408
- complete: tpl.complete
409
- });
410
- server.registerResource(tpl.name || tpl.uriTemplate, resourceTemplate, {
411
- description: tpl.description,
412
- mimeType: tpl.mimeType
413
- }, async (uri, variables) => {
414
- const params = {};
415
- for (const [k, v] of Object.entries(variables || {})) {
416
- params[k] = Array.isArray(v) ? v.join(',') : String(v);
417
- }
418
- const raw = await tpl.handler(uri, params, ctx);
419
- return normalizeResourceResult(raw, uri, tpl.mimeType);
420
- });
567
+ registerSingleTemplate(server, tpl, ctx);
421
568
  }
422
569
  // Register all prompts
423
570
  for (const prompt of options.promptRegistry.getAll()) {
424
- let argsSchema = prompt.argsSchema;
425
- if (argsSchema && prompt.complete) {
426
- const wrappedSchema = {};
427
- for (const [key, field] of Object.entries(argsSchema)) {
428
- const zodField = typeof field === 'string' ? z.string() : field;
429
- if (prompt.complete[key]) {
430
- wrappedSchema[key] = completable(zodField, async (val, context) => {
431
- const list = await prompt.complete[key](val, context);
432
- return Array.isArray(list) ? list : [];
433
- });
434
- }
435
- else {
436
- wrappedSchema[key] = zodField;
437
- }
438
- }
439
- argsSchema = wrappedSchema;
440
- }
441
- server.registerPrompt(prompt.name, {
442
- description: prompt.description,
443
- argsSchema: argsSchema
444
- }, async (args) => {
445
- return await prompt.handler(args, ctx);
446
- });
571
+ registerSinglePrompt(server, prompt, ctx);
447
572
  }
448
573
  // Register completion capability and fallback request handler if not yet registered
449
574
  try {
@@ -471,6 +596,8 @@ export function createSessionMcpServer(options) {
471
596
  catch {
472
597
  // Handler already configured by McpServer
473
598
  }
599
+ server._sessionOptions = options;
600
+ server._sessionCtx = ctx;
474
601
  return server;
475
602
  }
476
603
  //# sourceMappingURL=mcp.js.map