-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathserver.ts
More file actions
549 lines (476 loc) · 18 KB
/
server.ts
File metadata and controls
549 lines (476 loc) · 18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
import {
McpServer,
type CompleteResourceTemplateCallback,
type ResourceTemplate,
type ResourceMetadata
} from '@modelcontextprotocol/sdk/server/mcp.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { registerResource } from './mcpSdk';
import { setMetaResources } from './server.resourceMeta';
import { usePatternFlyDocsTool } from './tool.patternFlyDocs';
import { searchPatternFlyDocsTool } from './tool.searchPatternFlyDocs';
import { patternFlyComponentsIndexResource } from './resource.patternFlyComponentsIndex';
import { patternFlyContextResource } from './resource.patternFlyContext';
import { patternFlyDocsIndexResource } from './resource.patternFlyDocsIndex';
import { patternFlyDocsTemplateResource } from './resource.patternFlyDocsTemplate';
import { patternFlySchemasIndexResource } from './resource.patternFlySchemasIndex';
import { patternFlySchemasTemplateResource } from './resource.patternFlySchemasTemplate';
import { startHttpTransport, type HttpServerHandle } from './server.http';
import { memo } from './server.caching';
import { log, type LogEvent } from './logger';
import { createServerLogger } from './server.logger';
import { composeTools, sendToolsHostShutdown } from './server.tools';
import { composeResources } from './server.resources';
import { type GlobalOptions } from './options';
import {
getOptions,
getSessionOptions,
runWithOptions,
runWithSession
} from './options.context';
import { DEFAULT_OPTIONS } from './options.defaults';
import { isZodRawShape, isZodSchema } from './server.schema';
import { isPlainObject, timeoutFunction } from './server.helpers';
import { createServerStats, type Stats } from './server.stats';
import { stat, type StatReport } from './stats';
/**
* A tool registered with the MCP server.
*
* @note Use of `any` here is intentional as part of a pass-through policy around
* `inputSchema`. Input schemas are actually reconstructed as part of the
* tools-as-plugins architecture to help guarantee that a minimal tool schema is
* always available and minimally valid.
*/
type McpTool = [
name: string,
schema: {
description: string;
inputSchema: any;
},
handler: (arg?: unknown) => any | Promise<any>
];
/**
* A function that creates a tool registered with the MCP server.
*/
type McpToolCreator = ((options?: GlobalOptions) => McpTool) & { toolName?: string };
/**
* Configuration for a generated metadata MCP resource.
*
* @interface McpResourceMetadataMetaConfig
*
* @property [uri] - Override URI for the meta-resource. (e.g., `test://lorem/meta`, `test://ipsum/meta{?var}`).
* @property [name] - Registered name for the meta-resource (defaults to `{primaryName}-meta`).
* @property [title] - Title shown for the meta-resource in listings and generated Markdown.
* @property [description] - Description for the meta-resource in listings and generated Markdown.
* @property [searchFields] - Query parameter names included on the meta-URI template for completion.
* - If an empty array is provided the meta-resource uses a static URI, no template
* - If omitted the search fields are inferred from the `uri` or the primary resource template.
* @property [mimeType] - MIME type of the meta-resource body. Acceptable values are:
* - 'text/markdown'
* - 'application/json'
* @property [metaHandler] - A custom handler for the meta-resource. It accepts an optional object as its
* argument for passing parameters and returns a serialized value to the MCP client. A default fallback
* async handler is used if none is provided.
*/
interface McpResourceMetadataMetaConfig {
uri?: string;
name?: string;
title?: string;
description?: string;
searchFields?: string[] | undefined;
mimeType?: 'text/markdown' | 'application/json';
metaHandler?: (params: Record<string, string> | undefined) => Promise<unknown> | unknown;
}
/**
* A resource metadata configuration for the MCP server.
*
* @property registerAllSearchCombinations - Whether to register all search combinations for the resource.
* @property metaConfig - Optional configuration for generating a metadata resource. Being defined
* (e.g. `{ metadata: { metaConfig: {} }}`) means a meta-resource will be generated for the related MCP resource.
* @property complete - Callback functions for resource completion.
*/
interface McpResourceMetadata {
registerAllSearchCombinations?: boolean | undefined;
metaConfig?: McpResourceMetadataMetaConfig;
complete?: {
[key: string]: CompleteResourceTemplateCallback;
} | undefined;
[key: string]: unknown;
}
/**
* A resource registered with the MCP server.
*
* 0. `name`: Registered name of the resource.
* 1. `uriOrTemplate`: URI string or template. {@link ResourceTemplate}
* 2. `config`: Resource configuration metadata. {@link ResourceMetadata}
* 3. `handler`: Resource handler function.
* 4. `metadata`: Optional **internal metadata** object, not used by the standard MCP SDK
* resource registry. {@link McpResourceMetadata}
*/
type McpResource = [
name: string,
uriOrTemplate: string | ResourceTemplate,
config: ResourceMetadata,
handler: (...args: any[]) => any | Promise<any>,
metadata?: McpResourceMetadata | undefined
];
/**
* A function that creates a resource registered with the MCP server.
*/
type McpResourceCreator = ((options?: GlobalOptions) => McpResource) & { resourceName?: string };
/**
* Server options. Equivalent to GlobalOptions.
*/
type ServerOptions = GlobalOptions;
/**
* Represents the configuration settings for a server.
*
* @interface ServerSettings
*
* @property {McpToolCreator[]} [tools] - An optional array of tool creators used by the server.
* @property {McpResourceCreator[]} [resources] - An optional array of resource creators used by the server.
* @property [enableSigint] - Indicates whether SIGINT signal handling is enabled.
* @property [allowProcessExit] - Determines if the process is allowed to exit explicitly.
*/
interface ServerSettings {
tools?: McpToolCreator[];
resources?: McpResourceCreator[];
enableSigint?: boolean;
allowProcessExit?: boolean;
}
/**
* Server stats.
*
* @alias Stats
*/
type ServerStats = Stats;
/**
* Server stats report.
*
* @alias StatReport
*/
type ServerStatReport = StatReport;
/**
* A callback to Promise return server stats.
*/
type ServerGetStats = () => Promise<ServerStats>;
/**
* Server log event.
*/
type ServerLogEvent = LogEvent;
/**
* A handler function to subscribe to server logs. Automatically unsubscribed on server shutdown.
*
* @param {ServerLogEvent} entry
*/
type ServerOnLogHandler = (entry: ServerLogEvent) => void;
/**
* Subscribes a handler function to server logs. Automatically unsubscribed on server shutdown.
*
* @param {ServerOnLogHandler} handler - The function responsible for handling server log events.
* @returns A cleanup function that unregisters the logging handler when called.
*/
type ServerOnLog = (handler: ServerOnLogHandler) => () => void;
/**
* Server instance with shutdown capability
*
* @property stop - Stops the server, gracefully.
* @property isRunning - Indicates whether the server is running.
* @property {ServerGetStats} getStats - Resolves server stats.
* @property {ServerOnLog} onLog - Subscribes to server logs. Automatically unsubscribed on server shutdown.
*/
interface ServerInstance {
stop(): Promise<void>;
isRunning(): boolean;
getStats: ServerGetStats;
onLog: ServerOnLog;
}
/**
* Built-in tools.
*
* Array of built-in tools
*/
const builtinTools: McpToolCreator[] = [
usePatternFlyDocsTool,
searchPatternFlyDocsTool
];
/**
* Built-in resources.
*
* Array of built-in resources
*/
const builtinResources: McpResourceCreator[] = [
patternFlyContextResource,
patternFlyComponentsIndexResource,
patternFlyDocsIndexResource,
patternFlyDocsTemplateResource,
patternFlySchemasIndexResource,
patternFlySchemasTemplateResource
];
/**
* Create and run the MCP server, register tools, and return a handle.
*
* - Built-in and inline tools are realized in-process
* - External plugins are realized in the Tools Host (child).
*
* @param [options] Server options
* @param [settings] Server settings (tools, signal handling, etc.)
* @param [settings.tools] - Built-in tools to register.
* @param [settings.enableSigint] - Indicates whether SIGINT signal handling is enabled.
* @param [settings.allowProcessExit] - Determines if the process is allowed to exit explicitly, useful for testing.
* @param settings.resources
* @returns Server instance with `stop()`, `getStats()` `isRunning()`, and `onLog()` subscription.
*/
const runServer = async (options: ServerOptions = getOptions(), {
tools = builtinTools,
resources = builtinResources,
enableSigint = true,
allowProcessExit = true
}: ServerSettings = {}): Promise<ServerInstance> => {
const session = getSessionOptions();
let server: McpServer | null = null;
let transport: StdioServerTransport | null = null;
let httpHandle: HttpServerHandle | null = null;
let unsubscribeServerLogger: (() => void) | null = null;
let unsubscribeServerStats: (() => void) | null = null;
let sigintHandler: (() => void) | null = null;
let running = false;
let onLogSetup: ServerOnLog = () => () => {};
let getStatsSetup: ServerGetStats = () => Promise.resolve({} as ServerStats);
const stopServer = async () => {
log.debug(`${options.name} attempting shutdown.`);
if (server && running) {
log.info(`${options.name} shutting down...`);
if (httpHandle) {
log.debug('...closing HTTP transport');
await httpHandle.close();
httpHandle = null;
}
if (sigintHandler) {
process.off('SIGINT', sigintHandler);
sigintHandler = null;
}
log.debug('...closing Server');
await server?.close();
running = false;
await sendToolsHostShutdown();
log.info(`${options.name} closed!\n`);
unsubscribeServerLogger?.();
unsubscribeServerStats?.();
if (allowProcessExit) {
process.exit(0);
}
}
};
try {
const enableProtocolLogging = options?.logging?.protocol;
const serverInstructions = options?.serverInstanceOptions?.instructions;
server = new McpServer(
{
name: options.name,
version: options.version
},
{
capabilities: {
tools: {},
resources: {},
completions: {},
...(enableProtocolLogging ? { logging: {} } : {})
},
...(serverInstructions ? { instructions: serverInstructions } : {})
}
);
// Setup server logging.
const loggerSubUnsub = createServerLogger.memo(server);
log.info(`Server logging enabled.`);
if (options?.logging?.stderr === undefined || enableProtocolLogging === undefined) {
log.debug(
`${options.name} server logging enabled with partial flags`,
`isStderr = ${options?.logging?.stderr !== undefined}`,
`isProtocol = ${enableProtocolLogging !== undefined};`
);
}
const statsTracker = createServerStats();
log.info(`Server stats enabled.`);
// Compose resources after logging is set up.
let updatedResources = await composeResources(resources);
// Add dynamic metadata to resources
updatedResources = setMetaResources(updatedResources);
// Combine built-in tools with custom ones after logging is set up.
const updatedTools = await composeTools(tools);
if (loggerSubUnsub) {
const { subscribe, unsubscribe } = loggerSubUnsub;
// Track active logging subscriptions to clean up on stop()
unsubscribeServerLogger = unsubscribe;
// Setup server logging for external handlers
onLogSetup = (handler: ServerOnLogHandler) => subscribe(handler);
}
if (statsTracker) {
// Track active stat subscriptions to clean up on stop()
unsubscribeServerStats = statsTracker.unsubscribe;
// Setup server stats for external handlers
getStatsSetup = () => statsTracker.getStats();
}
// Apply MCP resources, if available
updatedResources.forEach(resourceCreator => {
const [name, uri, config, callback, metadata] = resourceCreator(options);
log.info(`Registered resource: ${name}`);
if (server) {
registerResource(server, name, uri, config, (...args: unknown[]) =>
runWithSession(session, async () =>
runWithOptions(options, async () => {
log.debug(
`Running resource "${name}"`,
`isArgs = ${args?.length > 0}`
);
const timedReport = stat.traffic();
const resourceResult = await callback(...args);
timedReport({ resource: name });
return resourceResult;
})), metadata);
}
});
// Apply MCP tools, if available
updatedTools.forEach(toolCreator => {
const [name, schema, callback] = toolCreator(options);
// Do NOT normalize schemas here. This is by design and is a fallback check for malformed schemas.
const isZod = isZodSchema(schema?.inputSchema) || isZodRawShape(schema?.inputSchema);
const isSchemaDefined = schema?.inputSchema !== undefined;
if (!isZod) {
log.warn(`Tool "${name}" has a non Zod inputSchema. Skipping registration.`);
log.debug(
`Tool "${name}" has received a non Zod inputSchema from the tool pipeline.`,
`This will cause unexpected issues, such as failure to pass arguments.`,
`MCP SDK requires Zod. Kneel before Zod.`
);
return;
}
// Lightweight check for malformed schemas that bypass validation.
const isContextLike = (value: unknown) => isPlainObject(value) && 'requestId' in value && 'signal' in value;
try {
server?.registerTool(name, schema, (args: unknown = {}, ..._args: unknown[]) =>
runWithSession(session, async () =>
runWithOptions(options, async () => {
// Basic track for remaining args to account for future MCP SDK alterations.
log.debug(
`Running tool "${name}"`,
`isArgs = ${args !== undefined}`,
`isRemainingArgs = ${_args?.length > 0}`
);
const timedReport = stat.traffic();
const isContextLikeArgs = isContextLike(args);
// Log potential Zod validation errors triggered by context fail.
if (isContextLikeArgs) {
log.debug(
`Tool "${name}" handler received a context like object as the first parameter.`,
'If this is unexpected this is likely an undefined schema or a schema not registering as Zod.',
'Review the related schema definition and ensure it is defined and valid.',
`Schema is Defined = ${isSchemaDefined}; Schema is Zod = ${isZod}; Context like = ${isContextLikeArgs};`
);
}
const toolResult = await callback(args);
timedReport({ tool: name });
return toolResult;
})));
log.info(`Registered tool: ${name}`);
} catch (error) {
log.error(`Failed to register tool "${name}":`, error);
}
});
if (enableSigint && !sigintHandler) {
sigintHandler = () => {
void stopServer();
};
process.on('SIGINT', sigintHandler);
}
if (options.isHttp) {
httpHandle = await startHttpTransport(server, options);
} else {
transport = new StdioServerTransport();
await timeoutFunction(
server.connect(transport),
{
errorMessage: 'Transport connection timed out.'
}
);
}
if (!httpHandle && !transport) {
throw new Error('No transport available');
}
running = true;
log.info(`${options.name} server running on ${options.isHttp ? 'HTTP' : 'stdio'} transport`);
statsTracker.setStats(httpHandle);
} catch (error) {
log.error(`Error creating ${options.name} server:`, error);
throw error;
}
return {
async stop(): Promise<void> {
return await stopServer();
},
isRunning(): boolean {
return running;
},
async getStats(): Promise<ServerStats> {
return await getStatsSetup();
},
onLog(handler: ServerOnLogHandler): () => void {
// Simple one-off log event to notify the handler of the server startup.
handler({ level: 'info', msg: `${options.name} running!`, transport: options.logging?.transport } as LogEvent);
return onLogSetup(handler);
}
};
};
/**
* Memoized version of runServer.
* - Automatically cleans up servers when cache entries are rolled off (cache limit reached)
* - Prevents port conflicts by returning the same server instance via memoization
* - `onCacheRollout` closes servers that were rolled out of caching due to cache limit
*/
runServer.memo = memo(
runServer,
{
...DEFAULT_OPTIONS.resourceMemoOptions.default,
debug: info => {
log.debug(`Server memo: ${JSON.stringify(info, null, 2)}`);
},
onCacheRollout: async ({ removed }) => {
const results: PromiseSettledResult<ServerInstance>[] = await Promise.allSettled(removed);
for (const result of results) {
if (result.status === 'fulfilled') {
const server = result.value;
if (server?.isRunning?.()) {
try {
await server.stop();
} catch (error) {
// Avoid engaging the contextual log channel on rollout.
console.error(`Error stopping server: ${error}`);
}
}
} else {
// Avoid engaging the contextual log channel on rollout.
console.error(`Error cleaning up server: ${result?.reason?.message || result?.reason || 'Unknown error'}`);
}
}
}
}
);
export {
runServer,
builtinTools,
type McpTool,
type McpToolCreator,
type McpResource,
type McpResourceCreator,
type McpResourceMetadata,
type McpResourceMetadataMetaConfig,
type ServerInstance,
type ServerLogEvent,
type ServerOnLog,
type ServerOnLogHandler,
type ServerOptions,
type ServerSettings,
type ServerStatReport,
type ServerStats,
type ServerGetStats
};