@whook/mcp 26.0.5

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.
@@ -0,0 +1,551 @@
1
+ import {
2
+ type WhookAuthenticationData,
3
+ type WhookAuthenticationScope,
4
+ } from '@whook/authorization';
5
+ import {
6
+ type WhookDefinitions,
7
+ type WhookOpenAPI,
8
+ type WhookOpenAPIOperation,
9
+ type WhookRouteConfig,
10
+ type WhookRouteHandlerParameters,
11
+ type WhookRoutesHandlersService,
12
+ type WhookSchemaValidatorsService,
13
+ } from '@whook/whook';
14
+
15
+ import {
16
+ Server,
17
+ type Tool,
18
+ createMcpHandler,
19
+ } from '@modelcontextprotocol/server';
20
+ import { type LogService } from 'common-services';
21
+ import { type Provider, autoProvider, name } from 'knifecycle';
22
+ import { Readable } from 'node:stream';
23
+ import {
24
+ type ObjectJSONSchema,
25
+ type ExpressiveJSONSchema,
26
+ type JSONSchema,
27
+ } from 'ya-json-schema-types';
28
+ import {
29
+ OpenAPIExtension,
30
+ type OpenAPIMethod,
31
+ OpenAPIParameter,
32
+ type OpenAPISecurityRequirement,
33
+ ensureResolvedObject,
34
+ } from 'ya-open-api-types';
35
+ import { YError, printStackTrace } from 'yerror';
36
+
37
+ const PARAMETERS_LOCATION: Record<
38
+ OpenAPIParameter<unknown, OpenAPIExtension>['in'],
39
+ keyof WhookRouteHandlerParameters
40
+ > = {
41
+ cookie: 'cookies',
42
+ header: 'headers',
43
+ path: 'path',
44
+ query: 'query',
45
+ querystring: 'query',
46
+ };
47
+
48
+ export type WhookMCPHandlerService = ReturnType<typeof createMcpHandler>;
49
+
50
+ export interface WhookMCPRouteConfig {
51
+ allowMCP?: boolean;
52
+ }
53
+ export interface WhookMCPOptions {
54
+ /** MCP server advertised metadata */
55
+ metadata: {
56
+ name: string;
57
+ version: `${string}.${string}.${string}`;
58
+ websiteUrl?: string;
59
+ title?: string;
60
+ description?: string;
61
+ icons?: {
62
+ src: string;
63
+ mimeType?: string;
64
+ sizes?: string[];
65
+ theme?: 'light' | 'dark';
66
+ }[];
67
+ };
68
+ /** The MCP server path */
69
+ path: `/${string}`;
70
+ /** Allows to prebuild definitions at startup (default: false) */
71
+ prebuildTools: boolean;
72
+ /** Security requirements keys to check
73
+ * (leave the array empty to provide anonymous routes only)
74
+ */
75
+ securityKeys: string[];
76
+ /** Rules to choose operation to provide
77
+ * (all routes are provided per default)
78
+ */
79
+ rules?:
80
+ | {
81
+ /** Use a static list of operations to allow/block */
82
+ mode: 'allowlist' | 'blocklist';
83
+ operationsIds: string[];
84
+ }
85
+ /** Use routes configuration */
86
+ | {
87
+ mode: 'config';
88
+ default: 'allow' | 'block';
89
+ }
90
+ | {
91
+ /** Use a function to filter operations to allow */
92
+ mode: 'filter';
93
+ operationIsAllowed: (operationId: string) => boolean;
94
+ };
95
+ }
96
+ export interface WhookMCPHandlerConfig {
97
+ MCP_OPTIONS: WhookMCPOptions;
98
+ }
99
+ export type WhookMCPHandlerDependencies = WhookMCPHandlerConfig & {
100
+ API: WhookOpenAPI;
101
+ ROUTES_HANDLERS: WhookRoutesHandlersService;
102
+ DEFINITIONS: WhookDefinitions;
103
+ schemaValidators: WhookSchemaValidatorsService;
104
+ log: LogService;
105
+ };
106
+
107
+ async function initWhookMCPHandler({
108
+ API,
109
+ ROUTES_HANDLERS,
110
+ DEFINITIONS,
111
+ schemaValidators,
112
+ MCP_OPTIONS,
113
+ log,
114
+ }: WhookMCPHandlerDependencies): Promise<Provider<WhookMCPHandlerService>> {
115
+ log('warning', `💻 - Starting the MCPServer service.`);
116
+
117
+ const toolsCache: Record<string, Tool | 'skipped'> = {};
118
+
119
+ if (MCP_OPTIONS.prebuildTools) {
120
+ log('debug', `🔧 - Pre-building tools!`);
121
+ for (const [operationId, config] of Object.entries(DEFINITIONS.configs)) {
122
+ if (config.type !== 'route' || config.method === 'options') {
123
+ continue;
124
+ }
125
+
126
+ const operation = config.operation;
127
+
128
+ if (!operation) {
129
+ log('debug', `🤷 - Filtering undefined "${operationId}" operation!`);
130
+ continue;
131
+ }
132
+
133
+ await buildTool(operation, config.method, config.config);
134
+ }
135
+ }
136
+
137
+ async function buildTool(
138
+ operation: WhookOpenAPIOperation,
139
+ method: OpenAPIMethod,
140
+ config?: WhookRouteConfig,
141
+ ) {
142
+ const operationId = operation.operationId;
143
+
144
+ if (toolsCache[operationId]) {
145
+ return toolsCache[operationId];
146
+ }
147
+
148
+ log('debug', `🔧 - Building tool for ${operationId}!`);
149
+
150
+ if (
151
+ MCP_OPTIONS.rules &&
152
+ ((MCP_OPTIONS.rules.mode === 'allowlist' &&
153
+ !MCP_OPTIONS.rules.operationsIds.includes(operationId)) ||
154
+ (MCP_OPTIONS.rules.mode === 'blocklist' &&
155
+ MCP_OPTIONS.rules.operationsIds.includes(operationId)) ||
156
+ (MCP_OPTIONS.rules.mode === 'config' &&
157
+ (config?.allowMCP === false ||
158
+ (config?.allowMCP !== true &&
159
+ MCP_OPTIONS.rules.default === 'block'))) ||
160
+ (MCP_OPTIONS.rules.mode === 'filter' &&
161
+ !MCP_OPTIONS.rules.operationIsAllowed(operationId)))
162
+ ) {
163
+ log(
164
+ 'debug',
165
+ `🤷 - Filtering "${operationId}" operation (mode: "${MCP_OPTIONS.rules?.mode}")!`,
166
+ );
167
+ toolsCache[operationId] = 'skipped';
168
+ return toolsCache[operationId];
169
+ }
170
+
171
+ const responsesSchemas: JSONSchema[] = [];
172
+
173
+ for (const statusCode of Object.keys(operation.responses || {})) {
174
+ const maybeResponse = operation.responses?.[statusCode];
175
+ const response = await ensureResolvedObject(API, maybeResponse);
176
+
177
+ if (!response || !('content' in response) || !response.content) {
178
+ continue;
179
+ }
180
+
181
+ const schema = response.content?.['application/json']?.schema || {
182
+ type: 'string',
183
+ format: 'binary',
184
+ };
185
+
186
+ responsesSchemas.push({
187
+ type: 'object',
188
+ required: ['status', 'body'],
189
+ properties: {
190
+ status:
191
+ statusCode === 'default'
192
+ ? { type: 'number' }
193
+ : { const: parseInt(statusCode, 10) },
194
+ body: schema,
195
+ },
196
+ });
197
+ }
198
+
199
+ const parameters = await Promise.all(
200
+ (operation.parameters || []).map((parameter) =>
201
+ ensureResolvedObject(API, parameter),
202
+ ),
203
+ );
204
+ const requestBody = operation.requestBody
205
+ ? await ensureResolvedObject(API, operation.requestBody)
206
+ : undefined;
207
+ const bodySchema = requestBody
208
+ ? requestBody.content?.['application/json']?.schema || {
209
+ type: 'string',
210
+ format: 'binary',
211
+ }
212
+ : undefined;
213
+
214
+ const tool: Tool = {
215
+ name: operationId,
216
+ description: operation.summary || '',
217
+ annotations: {
218
+ readOnlyHint: !['put', 'post', 'patch', 'delete'].includes(method),
219
+ idempotentHint: [
220
+ 'options',
221
+ 'head',
222
+ 'get',
223
+ 'query',
224
+ 'put',
225
+ 'delete',
226
+ ].includes(method),
227
+ destructiveHint: ['put', 'post', 'patch', 'delete'].includes(method),
228
+ openWorldHint: true,
229
+ },
230
+ inputSchema: {
231
+ type: 'object',
232
+ required: [
233
+ ...new Set(
234
+ parameters
235
+ .filter((parameter) => parameter.required)
236
+ .map((parameter) => PARAMETERS_LOCATION[parameter.in]),
237
+ ),
238
+ ...(requestBody?.required ? ['body'] : []),
239
+ ],
240
+ properties: parameters.reduce(
241
+ (properties, parameter) => ({
242
+ ...properties,
243
+ [PARAMETERS_LOCATION[parameter.in]]:
244
+ parameter.in === 'querystring'
245
+ ? 'schema' in parameter
246
+ ? (parameter.schema as ExpressiveJSONSchema)
247
+ : true
248
+ : ({
249
+ type: 'object',
250
+ required: [
251
+ ...new Set(
252
+ (
253
+ (properties[parameter.in] as ObjectJSONSchema)
254
+ ?.required || []
255
+ ).concat(parameter.required ? [parameter.name] : []),
256
+ ),
257
+ ],
258
+ properties: {
259
+ ...((properties[parameter.in] as ObjectJSONSchema)
260
+ ?.properties || {}),
261
+ [parameter.name]:
262
+ 'schema' in parameter
263
+ ? {
264
+ description: parameter.description,
265
+ ...parameter.schema,
266
+ }
267
+ : true,
268
+ },
269
+ } as ExpressiveJSONSchema),
270
+ }),
271
+ (bodySchema
272
+ ? {
273
+ body: bodySchema,
274
+ }
275
+ : {}) as NonNullable<ObjectJSONSchema['properties']>,
276
+ ),
277
+ } as unknown as Tool['inputSchema'],
278
+ outputSchema:
279
+ responsesSchemas.length === 1
280
+ ? (responsesSchemas[0] as ExpressiveJSONSchema)
281
+ : responsesSchemas.length
282
+ ? { oneOf: responsesSchemas }
283
+ : undefined,
284
+ };
285
+
286
+ toolsCache[operation.operationId] = tool;
287
+
288
+ return tool;
289
+ }
290
+
291
+ function checkSecurityScopes(
292
+ scopes: WhookAuthenticationScope[],
293
+ security?: OpenAPISecurityRequirement[],
294
+ ): boolean {
295
+ if (!security || Object.keys(security).length === 0) {
296
+ return true;
297
+ }
298
+
299
+ for (const securityKey of MCP_OPTIONS.securityKeys || []) {
300
+ for (const requirement of security) {
301
+ if (
302
+ Object.keys(requirement).length === 1 &&
303
+ requirement[securityKey] &&
304
+ requirement[securityKey].every((scope) =>
305
+ scopes.includes(scope as WhookAuthenticationScope),
306
+ )
307
+ ) {
308
+ return true;
309
+ }
310
+ }
311
+ }
312
+ return false;
313
+ }
314
+
315
+ const handler = createMcpHandler(({ requestInfo, authInfo }) => {
316
+ const server = new Server(MCP_OPTIONS.metadata, {
317
+ capabilities: { tools: {} },
318
+ });
319
+ const authenticationData = authInfo as unknown as WhookAuthenticationData;
320
+
321
+ log(
322
+ 'debug',
323
+ `🙋 - MCP authentication: `,
324
+ JSON.stringify(authenticationData) || 'anonymous',
325
+ );
326
+
327
+ server.setRequestHandler('tools/list', async () => {
328
+ try {
329
+ log('debug', '➕ - Listing tools!');
330
+
331
+ const scopes = authenticationData?.scopes || [];
332
+ const tools: Tool[] = [];
333
+
334
+ for (const [operationId, config] of Object.entries(
335
+ DEFINITIONS.configs,
336
+ )) {
337
+ if (config.type !== 'route' || config.method === 'options') {
338
+ continue;
339
+ }
340
+
341
+ const operation = config.operation;
342
+
343
+ if (!operation) {
344
+ log(
345
+ 'debug',
346
+ `🤷 - Filtering undefined "${operationId}" operation!`,
347
+ );
348
+ continue;
349
+ }
350
+
351
+ if (
352
+ !checkSecurityScopes(scopes, operation.security ?? API.security)
353
+ ) {
354
+ log(
355
+ 'debug',
356
+ `🤷 - Not supposed to run "${operationId}" with scopes "${scopes.join(' ')}"!`,
357
+ );
358
+ continue;
359
+ }
360
+
361
+ const tool = await buildTool(operation, config.method, config.config);
362
+
363
+ if (tool !== 'skipped') {
364
+ tools.push(tool);
365
+ }
366
+ }
367
+
368
+ log('debug', `➕ - Found ${tools.length} tools!`);
369
+
370
+ return {
371
+ tools,
372
+ };
373
+ } catch (err) {
374
+ log('error', `❌ - Failed to list MCP tools!`);
375
+ log('error-stack', printStackTrace(err));
376
+
377
+ return {
378
+ tools: [],
379
+ isError: true,
380
+ };
381
+ }
382
+ });
383
+
384
+ server.setRequestHandler('tools/call', async (request) => {
385
+ log('debug', `➕ - Running call ${request.params.name}!`);
386
+
387
+ const handler = ROUTES_HANDLERS[request.params.name];
388
+ const definition = DEFINITIONS.configs[request.params.name];
389
+ const tool =
390
+ definition?.type === 'route' && definition.operation
391
+ ? await buildTool(
392
+ definition.operation,
393
+ definition.method,
394
+ definition.config,
395
+ )
396
+ : undefined;
397
+
398
+ if (
399
+ !handler ||
400
+ !definition ||
401
+ definition.type !== 'route' ||
402
+ !tool ||
403
+ tool === 'skipped'
404
+ ) {
405
+ return {
406
+ content: [
407
+ { type: 'text', text: `Unknown tool: ${request.params.name}` },
408
+ ],
409
+ isError: true,
410
+ };
411
+ }
412
+
413
+ if (
414
+ !checkSecurityScopes(
415
+ authInfo?.scopes || [],
416
+ definition?.operation?.security ?? API.security,
417
+ )
418
+ ) {
419
+ return {
420
+ content: [
421
+ { type: 'text', text: `Unauthorized tool: ${request.params.name}` },
422
+ ],
423
+ isError: true,
424
+ };
425
+ }
426
+
427
+ const parameters: WhookRouteHandlerParameters = {
428
+ path: {},
429
+ query: {},
430
+ cookies: {},
431
+ headers: {},
432
+ ...(request.params.arguments as Partial<WhookRouteHandlerParameters>),
433
+ };
434
+
435
+ log('debug', `➕ - Parameters "${JSON.stringify(parameters)}"`);
436
+
437
+ const validate = schemaValidators(tool.inputSchema);
438
+
439
+ validate(parameters);
440
+
441
+ if (validate.errors) {
442
+ return {
443
+ content: [
444
+ {
445
+ type: 'text',
446
+ text: `Bad parameters: ${JSON.stringify(validate.errors)}`,
447
+ structuredContent: validate.errors,
448
+ },
449
+ ],
450
+ isError: true,
451
+ };
452
+ }
453
+
454
+ try {
455
+ const response = await handler(
456
+ {
457
+ ...parameters,
458
+ headers: {
459
+ authorization: requestInfo?.headers.get('authorization'),
460
+ ...parameters.headers,
461
+ },
462
+ },
463
+ definition,
464
+ );
465
+
466
+ log('debug', `➕ - Response "${JSON.stringify(response)}"!`);
467
+
468
+ if (
469
+ response.body instanceof Readable ||
470
+ response.body instanceof Buffer
471
+ ) {
472
+ if (typeof response.headers?.['content-type'] === 'string') {
473
+ const isImage =
474
+ response.headers['content-type'].startsWith('image/');
475
+ const isAudio =
476
+ response.headers['content-type'].startsWith('audio/');
477
+
478
+ return {
479
+ content: [
480
+ isImage || isAudio
481
+ ? {
482
+ type: isImage ? 'image' : 'audio',
483
+ mimeType: response.headers['content-type'],
484
+ data: Buffer.from(
485
+ response.body instanceof Readable
486
+ ? await response.body.toArray()
487
+ : response.body,
488
+ ).toString('base64'),
489
+ }
490
+ : {
491
+ type: 'resource',
492
+ resource: {
493
+ uri: requestInfo?.url as string,
494
+ mimeType: response.headers['content-type'],
495
+ blob: Buffer.from(
496
+ response.body instanceof Readable
497
+ ? await response.body.toArray()
498
+ : response.body,
499
+ ).toString('base64url'),
500
+ },
501
+ },
502
+ ],
503
+ };
504
+ } else {
505
+ return {
506
+ content: [
507
+ {
508
+ type: 'text',
509
+ text: 'Cannot encode resource.',
510
+ },
511
+ ],
512
+ isError: true,
513
+ };
514
+ }
515
+ }
516
+
517
+ return {
518
+ content: [
519
+ {
520
+ type: 'text',
521
+ text: JSON.stringify(response),
522
+ structuredContent: response,
523
+ },
524
+ ],
525
+ };
526
+ } catch (err) {
527
+ log('error-stack', printStackTrace(err));
528
+ return {
529
+ content: [
530
+ {
531
+ type: 'text',
532
+ text: `Unexpected error: ${(err as YError).message}`,
533
+ },
534
+ ],
535
+ isError: true,
536
+ };
537
+ }
538
+ });
539
+
540
+ return server;
541
+ });
542
+
543
+ return {
544
+ service: handler,
545
+ dispose: async () => {
546
+ await handler.close();
547
+ },
548
+ };
549
+ }
550
+
551
+ export default name('mcpHandler', autoProvider(initWhookMCPHandler));
package/src/types.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ import { type WhookBaseRouteConfig } from '@whook/whook';
2
+ import { type WhookMCPRouteConfig } from './services/mcpHandler.ts';
3
+
4
+ declare module '@whook/whook' {
5
+ export interface WhookRouteConfig
6
+ extends WhookBaseRouteConfig, WhookMCPRouteConfig {}
7
+ }
@@ -0,0 +1,137 @@
1
+ import { type WhookAuthenticationService } from '@whook/authorization';
2
+ import {
3
+ type WhookHTTPRouterProvider,
4
+ type WhookHTTPRouterService,
5
+ castWhookHeaders,
6
+ pickFirstHeaderValue,
7
+ } from '@whook/whook';
8
+
9
+ import { toNodeHandler } from '@modelcontextprotocol/node';
10
+ import { type LogService, noop } from 'common-services';
11
+ import { alsoInject, wrapInitializer } from 'knifecycle';
12
+ import { type Dependencies, type ProviderInitializer } from 'knifecycle';
13
+ import { type IncomingMessage, type ServerResponse } from 'node:http';
14
+ import { hasYErrorCode, printStackTrace } from 'yerror';
15
+ import { YHTTPError } from 'yhttperror';
16
+
17
+ import {
18
+ type WhookMCPOptions,
19
+ type WhookMCPHandlerService,
20
+ } from '../services/mcpHandler.js';
21
+
22
+ export interface BearerPayload {
23
+ hash: string;
24
+ }
25
+ export interface WhookMCPServerConfig {
26
+ MCP_OPTIONS: WhookMCPOptions;
27
+ }
28
+ export type WhookMCPServerDependencies = WhookMCPServerConfig & {
29
+ mcpHandler: WhookMCPHandlerService;
30
+ authentication: WhookAuthenticationService<BearerPayload>;
31
+ log?: LogService;
32
+ };
33
+
34
+ export default function wrapHTTPRouterWithMCPServer<D extends Dependencies>(
35
+ initHTTPRouter: ProviderInitializer<D, WhookHTTPRouterService>,
36
+ ): ProviderInitializer<D & WhookMCPServerDependencies, WhookHTTPRouterService> {
37
+ const augmentedInitializer = alsoInject<
38
+ WhookMCPServerDependencies,
39
+ D,
40
+ WhookHTTPRouterService
41
+ >(['MCP_OPTIONS', 'mcpHandler', 'authentication', '?log'], initHTTPRouter);
42
+
43
+ return wrapInitializer(
44
+ async (
45
+ {
46
+ MCP_OPTIONS,
47
+ mcpHandler,
48
+ authentication,
49
+ log = noop,
50
+ }: WhookMCPServerDependencies,
51
+ httpRouter: WhookHTTPRouterProvider,
52
+ ) => {
53
+ log(
54
+ 'warning',
55
+ `💁 - Serving API through MCP (path: ${MCP_OPTIONS.path})`,
56
+ );
57
+ const nodeHandler = toNodeHandler(mcpHandler);
58
+
59
+ const checkAuthentication = async (req: IncomingMessage) => {
60
+ const authorization = pickFirstHeaderValue(
61
+ 'authorization',
62
+ castWhookHeaders(req.headers),
63
+ );
64
+
65
+ if (!authorization) {
66
+ throw new YHTTPError(401, 'E_UNAUTHORIZED');
67
+ }
68
+
69
+ const [type, data] = (authorization || '').split(/\s+/, 2);
70
+
71
+ if (type.toLowerCase() !== 'bearer' || !data) {
72
+ throw new YHTTPError(401, 'E_UNAUTHORIZED', [type]);
73
+ }
74
+
75
+ const authenticationData = await authentication.check('bearer', {
76
+ hash: data,
77
+ });
78
+
79
+ log('debug', '➕ - MCP request authenticated');
80
+ return authenticationData;
81
+ };
82
+
83
+ async function customHTTPRouter(
84
+ req: IncomingMessage,
85
+ res: ServerResponse,
86
+ ) {
87
+ const url = req.url?.split('?', 1)[0];
88
+
89
+ if (
90
+ url &&
91
+ (url === MCP_OPTIONS.path || url.startsWith(MCP_OPTIONS.path + '/'))
92
+ ) {
93
+ try {
94
+ if (MCP_OPTIONS.securityKeys.length) {
95
+ (req as unknown as { auth: unknown }).auth =
96
+ await checkAuthentication(req);
97
+ } else {
98
+ log('warning', '⚠️ - MCP server is publicly available.');
99
+ }
100
+ } catch (err) {
101
+ const castedErr = hasYErrorCode(err, 'E_UNAUTHORIZED');
102
+
103
+ if (castedErr) {
104
+ // TODO: Eventually allow the MCP server for
105
+ // anonymous requests later. The main problem
106
+ // is that the MCP protocol errors seems to
107
+ // not allow to generate a 401/403 inside the
108
+ // MCP handler. A MCP server is then either
109
+ // protected or anonymous AFAIK
110
+ log('debug', '➕ - Authentication required');
111
+ log('debug-stack', printStackTrace(err));
112
+ res.statusCode = 401;
113
+ res.setHeader('WWW-Authenticate', 'Bearer');
114
+ res.end();
115
+ return;
116
+ }
117
+
118
+ log('error', '💥 - Unexpected MCP error!');
119
+ log('error-stack', printStackTrace(err));
120
+ res.statusCode = 500;
121
+ res.end();
122
+ return;
123
+ }
124
+
125
+ return nodeHandler(req, res);
126
+ }
127
+ return httpRouter.service(req, res);
128
+ }
129
+
130
+ return {
131
+ ...httpRouter,
132
+ service: customHTTPRouter,
133
+ };
134
+ },
135
+ augmentedInitializer,
136
+ );
137
+ }