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