-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathindex.ts
More file actions
292 lines (267 loc) · 9.75 KB
/
Copy pathindex.ts
File metadata and controls
292 lines (267 loc) · 9.75 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
import type {
CliOptions,
ExperimentalOptions,
ProgrammaticOptions
} from './options';
import { parseCliOptions, parseProgrammaticOptions } from './options.parser';
import { getSessionOptions, setOptions, runWithSession } from './options.context';
import type {
ServerInstance,
ServerSettings,
ServerOnLog,
ServerOnLogHandler,
ServerLogEvent,
ServerStatReport,
ServerStats,
ServerGetStats,
ServerOptions
} from './server';
import {
createMcpTool as createMcpToolFromTools,
type ToolCreator,
type ToolModule,
type ToolConfig,
type ToolMultiConfig,
type ToolExternalOptions,
type ToolInternalOptions
} from './server.toolsUser';
/**
* Server instance with shutdown capability
*
* Alias of {@link ServerInstance} (Internal type).
*/
type PfMcpInstance = ServerInstance;
/**
* Subscribes a handler function, `PfMcpOnLogHandler`, to server logs. Automatically unsubscribed on server shutdown.
*
* Alias of {@link ServerOnLog} (Internal type).
*/
type PfMcpOnLog = ServerOnLog;
/**
* The handler function passed by `onLog`, `PfMcpOnLog`, to subscribe to server logs. Automatically unsubscribed on server shutdown.
*
* Alias of {@link ServerOnLogHandler} (Internal type).
*/
type PfMcpOnLogHandler = ServerOnLogHandler;
/**
* The log event passed to the `onLog` handler, `PfMcpOnLogHandler`.
*
* Alias of {@link ServerLogEvent} (Internal type).
*/
type PfMcpLogEvent = ServerLogEvent;
/**
* Get statistics about the server.
*
* Alias of {@link ServerGetStats} (Internal type).
*/
type PfMcpGetStats = ServerGetStats;
/**
* Statistics about the server.
*
* Alias of {@link ServerStats} (Internal type).
*/
type PfMcpStats = ServerStats;
/**
* Statistics report about the server.
*
* Alias of {@link ServerStatReport} (Internal type).
*/
type PfMcpStatReport = ServerStatReport;
/**
* Available experimental option keys (without prefixes).
*
* @see {@link MakeExperimental} for how these are transformed for consumers.
*/
type PfMcpExperimentalOptions = ExperimentalOptions;
/**
* Exposed options for CLI use. A focused options interface.
*
* Available CLI options:
* - `--mode <mode>`: Specifies the mode of operation. Valid values are `cli`, `programmatic`, and `test`.
* - `--mode-test-url`: Specifies the base URL for testing mode.
* - `--log-level <level>`: Specifies the logging level. Valid values are `debug`, `info`, `warn`, and `error`.
* - `--verbose`: Log all severity levels. Shortcut to set the logging level to `debug`.
* - `--log-stderr`: Enables terminal logging of channel events
* - `--log-protocol`: Enables MCP protocol logging. Forward server logs to MCP clients (requires advertising `capabilities.logging`).
* - `--http`: Indicates if the `--http` option is enabled.
* - `--port`: The port number specified via `--port`
* - `--host`: The host name specified via `--host`
* - `--allowed-origins`: List of allowed origins derived from the `--allowed-origins` parameter, split by commas, or undefined if not provided.
* - `--allowed-hosts`: List of allowed hosts derived from the `--allowed-hosts` parameter, split by commas, or undefined if not provided.
* - `--plugin-isolation <none|strict>`: Isolation preset for external tools-as-plugins.
* - `--tool <tool-spec>`: Either a repeatable single tool-as-plugin specification or a comma-separated list of tool-as-plugin specifications. Each tool-as-plugin
* specification is a local module name or path.
*
* @note Type is not a 1:1 match for available options.
* @note Experimental options appear as `--experimental-<lorem-ipsum>` when available.
* @note Alias of {@link CliOptions} (Internal type).
*/
type PfMcpCliOptions = CliOptions;
/**
* `CliOptions` renamed to `PfMcpCliOptions` to avoid conflicts with internal naming.
*
* @deprecated Use {@link PfMcpCliOptions} instead.
*/
type DeprecatedCliOptions = PfMcpCliOptions;
/**
* `createMcpTool` from the root entry is deprecated for external tool plugins.
*
* @deprecated Import from `@patternfly/patternfly-mcp/tools` instead.
*/
const DeprecatedCreateMcpTool = createMcpToolFromTools;
/**
* Exposed options for programmatic use. A limited `DefaultOptions` interface.
*
* @property [docsPaths] - Local documentation search paths.
* @property [name] - The server display name.
* @property [http] - HTTP server options.
* @property [isHttp] - Enable HTTP transport.
* @property [logging] - Logging configuration.
* @property [mode] - Specifies the mode of operation.
* @property [modeOptions] - Options for `mode`. Currently, limited to the base URL for `test` mode.
* @property [pluginIsolation] - Isolation preset for external tools-as-plugins.
* @property [toolModules] - Programmatic tool registrations.
* @property [version] - The server display version.
*
* @note Experimental options appear as `experimental<LoremIpsum>` when available.
* @note Alias of {@link ProgrammaticOptions} (Internal type).
*/
type PfMcpOptions = ProgrammaticOptions;
/**
* Additional settings for programmatic control.
*
* @property {boolean} allowProcessExit - Override process exits. Useful for tests
* or programmatic use to avoid exiting.
* - Setting directly overrides `mode` property defaults.
* - When `mode=cli` or `mode=programmatic` or `undefined`, defaults to `true`.
* - When `mode=test`, defaults to `false`.
*/
type PfMcpSettings = Pick<ServerSettings, 'allowProcessExit'>;
/**
* Main function - Programmatic and CLI entry point with optional overrides
*
* @param [pfMcpOptions] - User configurable options
* @param [pfMcpSettings] - MCP server settings
*
* @returns {Promise<PfMcpInstance>} Server-instance with shutdown capability
*
* @throws {Error} If `allowProcessExit` is set to `false` an error will be thrown rather than exiting
* the process. Server errors are noted as options or start failures.
*
* @example Programmatic: A MCP server with STDIO (Standard Input Output) transport.
* import { start } from '@patternfly/patternfly-mcp';
* const { stop, isRunning } = await start();
*
* if (isRunning()) {
* stop();
* }
*
* @example Programmatic: A MCP server with HTTP transport.
* import { start } from '@patternfly/patternfly-mcp';
* const { stop, isRunning } = await start({ http: { port: 8000 } });
*
* if (isRunning()) {
* stop();
* }
*
* @example Programmatic: Listening for server stats
* import { subscribe, unsubscribe } from 'node:diagnostics_channel';
* import { start } from '@patternfly/patternfly-mcp';
* import { createMcpTool } from '@patternfly/patternfly-mcp/tools';
*
* const { stop, isRunning, getStats } = await start();
* const stats = await getStats();
* const statsChannel = subscribe(stats.health.channelId, (healthStats: PfMcpHealthStats) => {
* stderr.write(`Health uptime: ${healthStats.uptime}\n`);
* })
*
* if (isRunning()) {
* unsubscribe(stats.health.channelId);
* stop();
* }
*
* @example Programmatic: A MCP server with inline tool configuration and JSON inputSchema.
* import { start } from '@patternfly/patternfly-mcp';
* import { createMcpTool } from '@patternfly/patternfly-mcp/tools';
*
* const myToolModule = createMcpTool({
* name: 'my-tool',
* description: 'My tool description',
* inputSchema: { type: 'object', properties: {} },
* handler: async (args) => args
* });
*
* const { stop, isRunning } = await start({ toolModules: [myToolModule] });
*
* if (isRunning()) {
* stop();
* }
*/
const main = async (
pfMcpOptions: PfMcpOptions = {},
pfMcpSettings: PfMcpSettings = {}
): Promise<PfMcpInstance> => {
const { mode: programmaticMode, ...options } = pfMcpOptions;
const { allowProcessExit } = pfMcpSettings;
// Check early for allowing process exits
let updatedAllowProcessExit = allowProcessExit ?? programmaticMode !== 'test';
let mergedOptions: ServerOptions;
// If allowed, exit the process on error otherwise log then throw the error.
const processExit = (message: string, error: unknown) => {
console.error(message, error);
if (updatedAllowProcessExit) {
process.exit(1);
}
throw error;
};
try {
const { options: cliOptions, experimentalOptions: cliExp } = parseCliOptions(process.argv);
const { options: progOptions, experimentalOptions: progExp } = parseProgrammaticOptions(options);
// Apply `mode` separately because `cli.ts` applies it programmatically. Doing this allows us to set mode through `CLI options`.
mergedOptions = setOptions({
...cliOptions,
...progOptions,
experimental: [...new Set([...cliExp, ...progExp])],
mode: cliOptions.mode ?? programmaticMode
});
// Finalize exit policy after merging options
updatedAllowProcessExit = allowProcessExit ?? mergedOptions.mode !== 'test';
} catch (error) {
processExit('Set options error, failed to start server:', error);
}
try {
// Generate session options
const session = getSessionOptions();
const { runServer } = await import('./server');
// Start the server, apply session values, then apply merged options to ensure stable hashing.
return await runWithSession(session, async () =>
await runServer.memo(mergedOptions, { allowProcessExit: updatedAllowProcessExit }));
} catch (error) {
processExit('Failed to start server:', error);
}
// Unreachable, processExit exits or throws. Kept for type satisfaction.
return undefined as never;
};
export {
DeprecatedCreateMcpTool as createMcpTool,
main,
main as start,
type DeprecatedCliOptions as CliOptions,
type PfMcpCliOptions,
type PfMcpExperimentalOptions,
type PfMcpOptions,
type PfMcpSettings,
type PfMcpInstance,
type PfMcpLogEvent,
type PfMcpOnLog,
type PfMcpOnLogHandler,
type PfMcpStatReport,
type PfMcpStats,
type PfMcpGetStats,
type ToolCreator,
type ToolModule,
type ToolConfig,
type ToolMultiConfig,
type ToolExternalOptions,
type ToolInternalOptions
};