mcponce 0.2.3 → 0.3.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.
- package/dist/cli/installer.d.ts +1 -1
- package/dist/cli/installer.d.ts.map +1 -1
- package/dist/cli/installer.js +21 -1
- package/dist/cli/installer.js.map +1 -1
- package/dist/cli/tool-caller.d.ts.map +1 -1
- package/dist/cli/tool-caller.js +1 -0
- package/dist/cli/tool-caller.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/logging/file-logger.d.ts.map +1 -1
- package/dist/logging/file-logger.js +1 -4
- package/dist/logging/file-logger.js.map +1 -1
- package/dist/registry/central.d.ts.map +1 -1
- package/dist/registry/central.js +2 -10
- package/dist/registry/central.js.map +1 -1
- package/dist/registry/tools.d.ts +1 -1
- package/dist/registry/tools.d.ts.map +1 -1
- package/dist/registry/tools.js +85 -18
- package/dist/registry/tools.js.map +1 -1
- package/dist/runtime/instance.js +1 -1
- package/dist/runtime/lock.d.ts.map +1 -1
- package/dist/runtime/lock.js +10 -46
- package/dist/runtime/lock.js.map +1 -1
- package/dist/runtime/paths.d.ts.map +1 -1
- package/dist/runtime/paths.js +8 -1
- package/dist/runtime/paths.js.map +1 -1
- package/dist/runtime/state.d.ts.map +1 -1
- package/dist/runtime/state.js +4 -11
- package/dist/runtime/state.js.map +1 -1
- package/dist/server/app.d.ts +15 -1
- package/dist/server/app.d.ts.map +1 -1
- package/dist/server/app.js +156 -38
- package/dist/server/app.js.map +1 -1
- package/dist/server/hono.d.ts.map +1 -1
- package/dist/server/hono.js +10 -0
- package/dist/server/hono.js.map +1 -1
- package/dist/server/mcp.d.ts +19 -5
- package/dist/server/mcp.d.ts.map +1 -1
- package/dist/server/mcp.js +348 -285
- package/dist/server/mcp.js.map +1 -1
- package/dist/transport/proxy.d.ts.map +1 -1
- package/dist/transport/proxy.js +18 -16
- package/dist/transport/proxy.js.map +1 -1
- package/dist/types.d.ts +85 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/utils/cache.d.ts.map +1 -1
- package/dist/utils/cache.js +3 -2
- package/dist/utils/cache.js.map +1 -1
- package/dist/utils/coercion.d.ts +3 -3
- package/dist/utils/coercion.d.ts.map +1 -1
- package/dist/utils/coercion.js +101 -12
- package/dist/utils/coercion.js.map +1 -1
- package/dist/utils/media.d.ts +3 -3
- package/dist/utils/media.d.ts.map +1 -1
- package/dist/utils/media.js +11 -4
- package/dist/utils/media.js.map +1 -1
- package/dist/utils/retry.d.ts +20 -1
- package/dist/utils/retry.d.ts.map +1 -1
- package/dist/utils/retry.js +103 -7
- package/dist/utils/retry.js.map +1 -1
- package/package.json +4 -3
package/dist/server/mcp.js
CHANGED
|
@@ -3,6 +3,7 @@ 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';
|
|
7
8
|
import { composeMiddleware } from '../utils/middleware.js';
|
|
8
9
|
import { verifyToolScopes } from '../utils/security.js';
|
|
@@ -32,9 +33,10 @@ export function normalizeToolResult(rawResult) {
|
|
|
32
33
|
text: `[Image: ${rawResult.mimeType}]`
|
|
33
34
|
};
|
|
34
35
|
}
|
|
35
|
-
// Direct Buffer or
|
|
36
|
-
if (Buffer.isBuffer(rawResult) || rawResult instanceof Uint8Array) {
|
|
37
|
-
const
|
|
36
|
+
// Direct Buffer, Uint8Array, or ArrayBuffer returned by tool
|
|
37
|
+
if (Buffer.isBuffer(rawResult) || rawResult instanceof Uint8Array || rawResult instanceof ArrayBuffer) {
|
|
38
|
+
const raw = rawResult instanceof ArrayBuffer ? new Uint8Array(rawResult) : rawResult;
|
|
39
|
+
const img = normalizeContentItem(raw);
|
|
38
40
|
const mime = img.mimeType || 'application/octet-stream';
|
|
39
41
|
return {
|
|
40
42
|
content: [img],
|
|
@@ -110,16 +112,352 @@ export function normalizeToolResult(rawResult) {
|
|
|
110
112
|
};
|
|
111
113
|
}
|
|
112
114
|
import { executeWithRetry, raceWithSignal } from '../utils/retry.js';
|
|
115
|
+
export function normalizeOutputSchema(schema) {
|
|
116
|
+
if (!schema) {
|
|
117
|
+
return undefined;
|
|
118
|
+
}
|
|
119
|
+
if (typeof schema === 'object' && '_def' in schema) {
|
|
120
|
+
return schema;
|
|
121
|
+
}
|
|
122
|
+
if (typeof schema === 'object') {
|
|
123
|
+
return normalizeInputSchema(schema);
|
|
124
|
+
}
|
|
125
|
+
return schema;
|
|
126
|
+
}
|
|
127
|
+
export function createToolCallback(server, tool, options, ctx) {
|
|
128
|
+
return async (args, extraFromMcp) => {
|
|
129
|
+
const start = Date.now();
|
|
130
|
+
options.logger?.info('tool:start', { name: tool.name });
|
|
131
|
+
options.onToolCalled?.(tool.name);
|
|
132
|
+
if (tool.requireAuth && !options.auth) {
|
|
133
|
+
throw new Error(`Authentication required for tool "${tool.name}"`);
|
|
134
|
+
}
|
|
135
|
+
if (tool.scopes && tool.scopes.length > 0) {
|
|
136
|
+
if (!verifyToolScopes(tool.scopes, options.auth?.scopes)) {
|
|
137
|
+
throw new Error(`Forbidden: Tool "${tool.name}" requires scopes: ${tool.scopes.join(', ')}`);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
const cacheConfig = typeof tool.cache === 'object' ? tool.cache : (tool.cache ? {} : undefined);
|
|
141
|
+
if (cacheConfig && options.cacheManager) {
|
|
142
|
+
const cached = options.cacheManager.get(tool.name, args, cacheConfig);
|
|
143
|
+
if (cached) {
|
|
144
|
+
const durationMs = Date.now() - start;
|
|
145
|
+
options.analytics?.recordInvocation({
|
|
146
|
+
tool: tool.name,
|
|
147
|
+
durationMs,
|
|
148
|
+
status: 'success',
|
|
149
|
+
isCacheHit: true
|
|
150
|
+
});
|
|
151
|
+
if (options.metrics) {
|
|
152
|
+
options.metrics.lastToolInvocation = {
|
|
153
|
+
name: tool.name,
|
|
154
|
+
timestamp: new Date().toISOString()
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
options.logger?.info('tool:cache_hit', { name: tool.name, durationMs });
|
|
158
|
+
return normalizeToolResult(cached);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
const effectiveTimeout = tool.timeoutMs !== undefined
|
|
162
|
+
? tool.timeoutMs
|
|
163
|
+
: (options.defaultTimeoutMs !== undefined ? options.defaultTimeoutMs : 60000);
|
|
164
|
+
const timeoutController = effectiveTimeout > 0 ? new AbortController() : null;
|
|
165
|
+
let timeoutTimer;
|
|
166
|
+
if (effectiveTimeout > 0 && timeoutController) {
|
|
167
|
+
timeoutTimer = setTimeout(() => {
|
|
168
|
+
timeoutController.abort(new Error(`Tool "${tool.name}" execution timed out after ${effectiveTimeout}ms`));
|
|
169
|
+
}, effectiveTimeout);
|
|
170
|
+
}
|
|
171
|
+
const signals = [];
|
|
172
|
+
if (extraFromMcp?.signal) {
|
|
173
|
+
signals.push(extraFromMcp.signal);
|
|
174
|
+
}
|
|
175
|
+
if (timeoutController) {
|
|
176
|
+
signals.push(timeoutController.signal);
|
|
177
|
+
}
|
|
178
|
+
const mergedSignal = signals.length > 1
|
|
179
|
+
? (typeof AbortSignal.any === 'function' ? AbortSignal.any(signals) : signals[0])
|
|
180
|
+
: signals[0];
|
|
181
|
+
const queueConfig = options.resolveQueueConfig?.(tool);
|
|
182
|
+
let release;
|
|
183
|
+
let retriesCount = 0;
|
|
184
|
+
try {
|
|
185
|
+
if (queueConfig && options.queueManager) {
|
|
186
|
+
release = await options.queueManager.getQueue(queueConfig.key, queueConfig.maxConcurrency).acquire(mergedSignal);
|
|
187
|
+
}
|
|
188
|
+
const callToolHelper = options.callTool
|
|
189
|
+
? (targetName, targetArgs = {}, targetOptions) => {
|
|
190
|
+
const mergedTargetOptions = {
|
|
191
|
+
...targetOptions,
|
|
192
|
+
auth: targetOptions?.auth || options.auth
|
|
193
|
+
};
|
|
194
|
+
return options.callTool(targetName, targetArgs, mergedTargetOptions, [tool.name]);
|
|
195
|
+
}
|
|
196
|
+
: undefined;
|
|
197
|
+
const clearCacheHelper = (targetToolName) => {
|
|
198
|
+
return options.cacheManager ? options.cacheManager.clear(targetToolName) : 0;
|
|
199
|
+
};
|
|
200
|
+
const progressToken = extraFromMcp?._meta?.progressToken;
|
|
201
|
+
const reportProgress = createProgressReporter({
|
|
202
|
+
toolName: tool.name,
|
|
203
|
+
progressToken,
|
|
204
|
+
sendMcpNotification: extraFromMcp?.sendNotification
|
|
205
|
+
? (notif) => extraFromMcp.sendNotification(notif)
|
|
206
|
+
: undefined,
|
|
207
|
+
logger: options.logger
|
|
208
|
+
});
|
|
209
|
+
const sampleHelper = (input, opts) => {
|
|
210
|
+
return executeSample(input, opts, server, options.onSample, mergedSignal);
|
|
211
|
+
};
|
|
212
|
+
const listRootsHelper = () => {
|
|
213
|
+
return executeListRoots(server, options.onListRoots, mergedSignal);
|
|
214
|
+
};
|
|
215
|
+
const handlerCtx = ctx && typeof ctx === 'object'
|
|
216
|
+
? (callToolHelper
|
|
217
|
+
? Object.assign(Object.create(Object.getPrototypeOf(ctx)), ctx, {
|
|
218
|
+
callTool: callToolHelper,
|
|
219
|
+
signal: mergedSignal,
|
|
220
|
+
clearCache: clearCacheHelper,
|
|
221
|
+
reportProgress,
|
|
222
|
+
sample: sampleHelper,
|
|
223
|
+
listRoots: listRootsHelper,
|
|
224
|
+
auth: options.auth
|
|
225
|
+
})
|
|
226
|
+
: Object.assign(Object.create(Object.getPrototypeOf(ctx)), ctx, {
|
|
227
|
+
signal: mergedSignal,
|
|
228
|
+
clearCache: clearCacheHelper,
|
|
229
|
+
reportProgress,
|
|
230
|
+
sample: sampleHelper,
|
|
231
|
+
listRoots: listRootsHelper,
|
|
232
|
+
auth: options.auth
|
|
233
|
+
}))
|
|
234
|
+
: {
|
|
235
|
+
callTool: callToolHelper,
|
|
236
|
+
signal: mergedSignal,
|
|
237
|
+
clearCache: clearCacheHelper,
|
|
238
|
+
reportProgress,
|
|
239
|
+
sample: sampleHelper,
|
|
240
|
+
listRoots: listRootsHelper,
|
|
241
|
+
auth: options.auth
|
|
242
|
+
};
|
|
243
|
+
const extra = {
|
|
244
|
+
signal: mergedSignal,
|
|
245
|
+
callTool: (callToolHelper || (() => Promise.reject(new Error('callTool is not available in this context')))),
|
|
246
|
+
clearCache: clearCacheHelper,
|
|
247
|
+
reportProgress,
|
|
248
|
+
progressToken,
|
|
249
|
+
sample: sampleHelper,
|
|
250
|
+
listRoots: listRootsHelper,
|
|
251
|
+
auth: options.auth
|
|
252
|
+
};
|
|
253
|
+
const middlewarePipeline = options.middlewareManager
|
|
254
|
+
? options.middlewareManager.composeForTool(tool.name, (pCtx) => Promise.resolve(tool.handler(pCtx.args, pCtx.context, pCtx.extra)), tool.middleware)
|
|
255
|
+
: tool.middleware && tool.middleware.length > 0
|
|
256
|
+
? composeMiddleware(tool.middleware, (pCtx) => Promise.resolve(tool.handler(pCtx.args, pCtx.context, pCtx.extra)))
|
|
257
|
+
: null;
|
|
258
|
+
const runAttempt = () => {
|
|
259
|
+
if (middlewarePipeline) {
|
|
260
|
+
const middlewareCtx = {
|
|
261
|
+
tool: tool.name,
|
|
262
|
+
args: args || {},
|
|
263
|
+
context: handlerCtx,
|
|
264
|
+
extra,
|
|
265
|
+
callStack: []
|
|
266
|
+
};
|
|
267
|
+
const executionPromise = middlewarePipeline(middlewareCtx);
|
|
268
|
+
return raceWithSignal(executionPromise, mergedSignal, () => new Error(`Tool "${tool.name}" execution was cancelled`));
|
|
269
|
+
}
|
|
270
|
+
const executionPromise = Promise.resolve(tool.handler(args, handlerCtx, extra));
|
|
271
|
+
return raceWithSignal(executionPromise, mergedSignal, () => new Error(`Tool "${tool.name}" execution was cancelled`));
|
|
272
|
+
};
|
|
273
|
+
const { result: rawResult, retries } = await executeWithRetry(runAttempt, {
|
|
274
|
+
name: tool.name,
|
|
275
|
+
config: tool.retry,
|
|
276
|
+
signal: mergedSignal,
|
|
277
|
+
onRetry: (err, attempt, delayMs) => {
|
|
278
|
+
options.logger?.warn('tool:retry', {
|
|
279
|
+
name: tool.name,
|
|
280
|
+
attempt,
|
|
281
|
+
delayMs,
|
|
282
|
+
error: err?.message || String(err)
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
});
|
|
286
|
+
retriesCount = retries;
|
|
287
|
+
const durationMs = Date.now() - start;
|
|
288
|
+
options.analytics?.recordInvocation({
|
|
289
|
+
tool: tool.name,
|
|
290
|
+
durationMs,
|
|
291
|
+
status: 'success',
|
|
292
|
+
retries: retriesCount
|
|
293
|
+
});
|
|
294
|
+
if (options.metrics) {
|
|
295
|
+
options.metrics.lastToolInvocation = {
|
|
296
|
+
name: tool.name,
|
|
297
|
+
timestamp: new Date().toISOString()
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
options.logger?.info('tool:end', { name: tool.name, durationMs });
|
|
301
|
+
const normalized = normalizeToolResult(rawResult);
|
|
302
|
+
if (tool.outputSchema && !normalized.structuredContent) {
|
|
303
|
+
if (rawResult && typeof rawResult === 'object') {
|
|
304
|
+
if ('structuredContent' in rawResult) {
|
|
305
|
+
normalized.structuredContent = rawResult.structuredContent;
|
|
306
|
+
}
|
|
307
|
+
else if ('data' in rawResult && typeof rawResult.data === 'object' && rawResult.data !== null) {
|
|
308
|
+
normalized.structuredContent = rawResult.data;
|
|
309
|
+
}
|
|
310
|
+
else if (!('content' in rawResult)) {
|
|
311
|
+
normalized.structuredContent = rawResult;
|
|
312
|
+
}
|
|
313
|
+
else if (rawResult.data !== undefined) {
|
|
314
|
+
normalized.structuredContent = rawResult.data;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
if (cacheConfig && options.cacheManager && !normalized.isError) {
|
|
319
|
+
options.cacheManager.set(tool.name, args, normalized, cacheConfig);
|
|
320
|
+
}
|
|
321
|
+
return normalized;
|
|
322
|
+
}
|
|
323
|
+
catch (error) {
|
|
324
|
+
const durationMs = Date.now() - start;
|
|
325
|
+
const isTimeout = String(error?.message || error).includes('timed out');
|
|
326
|
+
const isCancelled = Boolean(mergedSignal?.aborted && !isTimeout);
|
|
327
|
+
const status = isTimeout ? 'timeout' : (isCancelled ? 'cancelled' : 'error');
|
|
328
|
+
options.analytics?.recordInvocation({
|
|
329
|
+
tool: tool.name,
|
|
330
|
+
durationMs,
|
|
331
|
+
status,
|
|
332
|
+
errorMessage: error.message || String(error),
|
|
333
|
+
retries: retriesCount || (error?.retries ?? 0)
|
|
334
|
+
});
|
|
335
|
+
if (options.metrics) {
|
|
336
|
+
options.metrics.lastToolInvocation = {
|
|
337
|
+
name: tool.name,
|
|
338
|
+
timestamp: new Date().toISOString()
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
options.logger?.error('tool:error', {
|
|
342
|
+
name: tool.name,
|
|
343
|
+
durationMs,
|
|
344
|
+
isTimeout,
|
|
345
|
+
isCancelled,
|
|
346
|
+
error: error.message || String(error),
|
|
347
|
+
stack: error.stack
|
|
348
|
+
});
|
|
349
|
+
return {
|
|
350
|
+
isError: true,
|
|
351
|
+
content: [
|
|
352
|
+
{
|
|
353
|
+
type: 'text',
|
|
354
|
+
text: `Error in tool "${tool.name}": ${error.message || String(error)}`
|
|
355
|
+
}
|
|
356
|
+
]
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
finally {
|
|
360
|
+
if (timeoutTimer) {
|
|
361
|
+
clearTimeout(timeoutTimer);
|
|
362
|
+
}
|
|
363
|
+
release?.();
|
|
364
|
+
}
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
export function registerSingleTool(server, tool, options, ctx) {
|
|
368
|
+
if (server._registeredTools?.[tool.name]) {
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
371
|
+
const callback = createToolCallback(server, tool, options, ctx);
|
|
372
|
+
server.registerTool(tool.name, {
|
|
373
|
+
title: tool.title,
|
|
374
|
+
description: tool.description,
|
|
375
|
+
inputSchema: tool.normalizedSchema,
|
|
376
|
+
outputSchema: normalizeOutputSchema(tool.outputSchema),
|
|
377
|
+
annotations: tool.annotations
|
|
378
|
+
}, callback);
|
|
379
|
+
}
|
|
380
|
+
export function registerSingleResource(server, res, ctx) {
|
|
381
|
+
if (server._registeredResources?.[res.uri]) {
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
server.registerResource(res.name || res.uri, res.uri, {
|
|
385
|
+
description: res.description,
|
|
386
|
+
mimeType: res.mimeType
|
|
387
|
+
}, async (uri) => {
|
|
388
|
+
const raw = await res.handler(uri, ctx);
|
|
389
|
+
return normalizeResourceResult(raw, uri, res.mimeType);
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
export function registerSingleTemplate(server, tpl, ctx) {
|
|
393
|
+
const resourceTemplate = new ResourceTemplate(tpl.uriTemplate, {
|
|
394
|
+
list: tpl.list
|
|
395
|
+
? async () => {
|
|
396
|
+
const result = await tpl.list(ctx);
|
|
397
|
+
if (Array.isArray(result)) {
|
|
398
|
+
return { resources: result };
|
|
399
|
+
}
|
|
400
|
+
return result;
|
|
401
|
+
}
|
|
402
|
+
: undefined,
|
|
403
|
+
complete: tpl.complete
|
|
404
|
+
});
|
|
405
|
+
server.registerResource(tpl.name || tpl.uriTemplate, resourceTemplate, {
|
|
406
|
+
description: tpl.description,
|
|
407
|
+
mimeType: tpl.mimeType
|
|
408
|
+
}, async (uri, variables) => {
|
|
409
|
+
const params = {};
|
|
410
|
+
for (const [k, v] of Object.entries(variables || {})) {
|
|
411
|
+
params[k] = Array.isArray(v) ? v.join(',') : String(v);
|
|
412
|
+
}
|
|
413
|
+
const raw = await tpl.handler(uri, params, ctx);
|
|
414
|
+
return normalizeResourceResult(raw, uri, tpl.mimeType);
|
|
415
|
+
});
|
|
416
|
+
}
|
|
417
|
+
export function registerSinglePrompt(server, prompt, ctx) {
|
|
418
|
+
if (server._registeredPrompts?.[prompt.name]) {
|
|
419
|
+
return;
|
|
420
|
+
}
|
|
421
|
+
let argsSchema = prompt.argsSchema;
|
|
422
|
+
if (argsSchema && prompt.complete) {
|
|
423
|
+
const wrappedSchema = {};
|
|
424
|
+
for (const [key, field] of Object.entries(argsSchema)) {
|
|
425
|
+
const zodField = typeof field === 'string' ? z.string() : field;
|
|
426
|
+
if (prompt.complete[key]) {
|
|
427
|
+
wrappedSchema[key] = completable(zodField, async (val, context) => {
|
|
428
|
+
const list = await prompt.complete[key](val, context);
|
|
429
|
+
return Array.isArray(list) ? list : [];
|
|
430
|
+
});
|
|
431
|
+
}
|
|
432
|
+
else {
|
|
433
|
+
wrappedSchema[key] = zodField;
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
argsSchema = wrappedSchema;
|
|
437
|
+
}
|
|
438
|
+
server.registerPrompt(prompt.name, {
|
|
439
|
+
description: prompt.description,
|
|
440
|
+
argsSchema: argsSchema
|
|
441
|
+
}, async (args) => {
|
|
442
|
+
return await prompt.handler(args, ctx);
|
|
443
|
+
});
|
|
444
|
+
}
|
|
113
445
|
export function createSessionMcpServer(options) {
|
|
114
446
|
const server = new McpServer({
|
|
115
447
|
name: options.name,
|
|
116
448
|
version: options.version
|
|
117
449
|
});
|
|
118
|
-
// Register capabilities for
|
|
450
|
+
// Register capabilities for tools, resources subscriptions/list updates, and prompts list updates
|
|
119
451
|
server.server.registerCapabilities({
|
|
452
|
+
tools: {
|
|
453
|
+
listChanged: true
|
|
454
|
+
},
|
|
120
455
|
resources: {
|
|
121
456
|
subscribe: true,
|
|
122
457
|
listChanged: true
|
|
458
|
+
},
|
|
459
|
+
prompts: {
|
|
460
|
+
listChanged: true
|
|
123
461
|
}
|
|
124
462
|
});
|
|
125
463
|
// Handle client resource subscriptions
|
|
@@ -154,296 +492,19 @@ export function createSessionMcpServer(options) {
|
|
|
154
492
|
const ctx = options.contextManager.getContext();
|
|
155
493
|
// Register all tools
|
|
156
494
|
for (const tool of options.toolRegistry.getAll()) {
|
|
157
|
-
server
|
|
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
|
-
});
|
|
495
|
+
registerSingleTool(server, tool, options, ctx);
|
|
385
496
|
}
|
|
386
497
|
// Register all static resources
|
|
387
498
|
for (const res of options.resourceRegistry.getAll()) {
|
|
388
|
-
server
|
|
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
|
-
});
|
|
499
|
+
registerSingleResource(server, res, ctx);
|
|
395
500
|
}
|
|
396
501
|
// Register all dynamic resource templates
|
|
397
502
|
for (const tpl of options.resourceRegistry.getAllTemplates()) {
|
|
398
|
-
|
|
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
|
-
});
|
|
503
|
+
registerSingleTemplate(server, tpl, ctx);
|
|
421
504
|
}
|
|
422
505
|
// Register all prompts
|
|
423
506
|
for (const prompt of options.promptRegistry.getAll()) {
|
|
424
|
-
|
|
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
|
-
});
|
|
507
|
+
registerSinglePrompt(server, prompt, ctx);
|
|
447
508
|
}
|
|
448
509
|
// Register completion capability and fallback request handler if not yet registered
|
|
449
510
|
try {
|
|
@@ -471,6 +532,8 @@ export function createSessionMcpServer(options) {
|
|
|
471
532
|
catch {
|
|
472
533
|
// Handler already configured by McpServer
|
|
473
534
|
}
|
|
535
|
+
server._sessionOptions = options;
|
|
536
|
+
server._sessionCtx = ctx;
|
|
474
537
|
return server;
|
|
475
538
|
}
|
|
476
539
|
//# sourceMappingURL=mcp.js.map
|