@claude-flow/cli 3.38.8 → 3.38.11

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.
Files changed (91) hide show
  1. package/.claude/helpers/helpers.manifest.json +2 -2
  2. package/catalog-manifest.json +2 -2
  3. package/dist/src/commands/doctor.js +53 -8
  4. package/dist/src/commands/mcp.js +4 -3
  5. package/dist/src/init/helper-refresh.d.ts +16 -9
  6. package/dist/src/init/helper-refresh.js +177 -20
  7. package/dist/src/log-filters.d.ts +3 -3
  8. package/dist/src/mcp-server.d.ts +1 -0
  9. package/dist/src/mcp-server.js +39 -3
  10. package/dist/src/mcp-tools/neural-tools.js +4 -3
  11. package/dist/src/memory/memory-bridge.d.ts +8 -0
  12. package/dist/src/memory/memory-bridge.js +18 -0
  13. package/node_modules/@claude-flow/codex/dist/cli.js +0 -0
  14. package/node_modules/@claude-flow/mcp/README.md +429 -0
  15. package/node_modules/@claude-flow/mcp/dist/connection-pool.d.ts +36 -0
  16. package/node_modules/@claude-flow/mcp/dist/connection-pool.d.ts.map +1 -0
  17. package/node_modules/@claude-flow/mcp/dist/connection-pool.js +273 -0
  18. package/node_modules/@claude-flow/mcp/dist/connection-pool.js.map +1 -0
  19. package/node_modules/@claude-flow/mcp/dist/index.d.ts +75 -0
  20. package/node_modules/@claude-flow/mcp/dist/index.d.ts.map +1 -0
  21. package/node_modules/@claude-flow/mcp/dist/index.js +85 -0
  22. package/node_modules/@claude-flow/mcp/dist/index.js.map +1 -0
  23. package/node_modules/@claude-flow/mcp/dist/oauth.d.ts +146 -0
  24. package/node_modules/@claude-flow/mcp/dist/oauth.d.ts.map +1 -0
  25. package/node_modules/@claude-flow/mcp/dist/oauth.js +318 -0
  26. package/node_modules/@claude-flow/mcp/dist/oauth.js.map +1 -0
  27. package/node_modules/@claude-flow/mcp/dist/prompt-registry.d.ts +90 -0
  28. package/node_modules/@claude-flow/mcp/dist/prompt-registry.d.ts.map +1 -0
  29. package/node_modules/@claude-flow/mcp/dist/prompt-registry.js +209 -0
  30. package/node_modules/@claude-flow/mcp/dist/prompt-registry.js.map +1 -0
  31. package/node_modules/@claude-flow/mcp/dist/rate-limiter.d.ts +86 -0
  32. package/node_modules/@claude-flow/mcp/dist/rate-limiter.d.ts.map +1 -0
  33. package/node_modules/@claude-flow/mcp/dist/rate-limiter.js +197 -0
  34. package/node_modules/@claude-flow/mcp/dist/rate-limiter.js.map +1 -0
  35. package/node_modules/@claude-flow/mcp/dist/resource-registry.d.ts +144 -0
  36. package/node_modules/@claude-flow/mcp/dist/resource-registry.d.ts.map +1 -0
  37. package/node_modules/@claude-flow/mcp/dist/resource-registry.js +405 -0
  38. package/node_modules/@claude-flow/mcp/dist/resource-registry.js.map +1 -0
  39. package/node_modules/@claude-flow/mcp/dist/sampling.d.ts +102 -0
  40. package/node_modules/@claude-flow/mcp/dist/sampling.d.ts.map +1 -0
  41. package/node_modules/@claude-flow/mcp/dist/sampling.js +268 -0
  42. package/node_modules/@claude-flow/mcp/dist/sampling.js.map +1 -0
  43. package/node_modules/@claude-flow/mcp/dist/schema-validator.d.ts +30 -0
  44. package/node_modules/@claude-flow/mcp/dist/schema-validator.d.ts.map +1 -0
  45. package/node_modules/@claude-flow/mcp/dist/schema-validator.js +182 -0
  46. package/node_modules/@claude-flow/mcp/dist/schema-validator.js.map +1 -0
  47. package/node_modules/@claude-flow/mcp/dist/server.d.ts +125 -0
  48. package/node_modules/@claude-flow/mcp/dist/server.d.ts.map +1 -0
  49. package/node_modules/@claude-flow/mcp/dist/server.js +849 -0
  50. package/node_modules/@claude-flow/mcp/dist/server.js.map +1 -0
  51. package/node_modules/@claude-flow/mcp/dist/session-manager.d.ts +55 -0
  52. package/node_modules/@claude-flow/mcp/dist/session-manager.d.ts.map +1 -0
  53. package/node_modules/@claude-flow/mcp/dist/session-manager.js +252 -0
  54. package/node_modules/@claude-flow/mcp/dist/session-manager.js.map +1 -0
  55. package/node_modules/@claude-flow/mcp/dist/task-manager.d.ts +81 -0
  56. package/node_modules/@claude-flow/mcp/dist/task-manager.d.ts.map +1 -0
  57. package/node_modules/@claude-flow/mcp/dist/task-manager.js +337 -0
  58. package/node_modules/@claude-flow/mcp/dist/task-manager.js.map +1 -0
  59. package/node_modules/@claude-flow/mcp/dist/tool-registry.d.ts +96 -0
  60. package/node_modules/@claude-flow/mcp/dist/tool-registry.d.ts.map +1 -0
  61. package/node_modules/@claude-flow/mcp/dist/tool-registry.js +399 -0
  62. package/node_modules/@claude-flow/mcp/dist/tool-registry.js.map +1 -0
  63. package/node_modules/@claude-flow/mcp/dist/transport/http.d.ts +60 -0
  64. package/node_modules/@claude-flow/mcp/dist/transport/http.d.ts.map +1 -0
  65. package/node_modules/@claude-flow/mcp/dist/transport/http.js +503 -0
  66. package/node_modules/@claude-flow/mcp/dist/transport/http.js.map +1 -0
  67. package/node_modules/@claude-flow/mcp/dist/transport/index.d.ts +50 -0
  68. package/node_modules/@claude-flow/mcp/dist/transport/index.d.ts.map +1 -0
  69. package/node_modules/@claude-flow/mcp/dist/transport/index.js +181 -0
  70. package/node_modules/@claude-flow/mcp/dist/transport/index.js.map +1 -0
  71. package/node_modules/@claude-flow/mcp/dist/transport/stdio.d.ts +43 -0
  72. package/node_modules/@claude-flow/mcp/dist/transport/stdio.d.ts.map +1 -0
  73. package/node_modules/@claude-flow/mcp/dist/transport/stdio.js +194 -0
  74. package/node_modules/@claude-flow/mcp/dist/transport/stdio.js.map +1 -0
  75. package/node_modules/@claude-flow/mcp/dist/transport/websocket.d.ts +65 -0
  76. package/node_modules/@claude-flow/mcp/dist/transport/websocket.d.ts.map +1 -0
  77. package/node_modules/@claude-flow/mcp/dist/transport/websocket.js +314 -0
  78. package/node_modules/@claude-flow/mcp/dist/transport/websocket.js.map +1 -0
  79. package/node_modules/@claude-flow/mcp/dist/types.d.ts +482 -0
  80. package/node_modules/@claude-flow/mcp/dist/types.d.ts.map +1 -0
  81. package/node_modules/@claude-flow/mcp/dist/types.js +40 -0
  82. package/node_modules/@claude-flow/mcp/dist/types.js.map +1 -0
  83. package/node_modules/@claude-flow/mcp/package.json +50 -0
  84. package/node_modules/@claude-flow/plugin-agent-federation/dist/bin.js +0 -0
  85. package/node_modules/@claude-flow/security/dist/path-validator.d.ts +23 -0
  86. package/node_modules/@claude-flow/security/dist/path-validator.d.ts.map +1 -1
  87. package/node_modules/@claude-flow/security/dist/path-validator.js +128 -5
  88. package/node_modules/@claude-flow/security/dist/path-validator.js.map +1 -1
  89. package/package.json +9 -2
  90. package/.claude/.proven-config-version +0 -1
  91. package/.claude/proven-config.json +0 -42
@@ -0,0 +1,849 @@
1
+ /**
2
+ * @claude-flow/mcp - MCP Server
3
+ *
4
+ * High-performance MCP server implementation
5
+ */
6
+ import { EventEmitter } from 'events';
7
+ import { platform, arch } from 'os';
8
+ import { MCPServerError, ErrorCodes } from './types.js';
9
+ import { createToolRegistry, } from './tool-registry.js';
10
+ import { createSessionManager } from './session-manager.js';
11
+ import { createConnectionPool } from './connection-pool.js';
12
+ import { createResourceRegistry } from './resource-registry.js';
13
+ import { createPromptRegistry } from './prompt-registry.js';
14
+ import { createTaskManager } from './task-manager.js';
15
+ import { createTransport, createTransportManager } from './transport/index.js';
16
+ import { createRateLimiter } from './rate-limiter.js';
17
+ import { createSamplingManager } from './sampling.js';
18
+ const DEFAULT_CONFIG = {
19
+ name: 'Claude-Flow MCP Server V3',
20
+ version: '3.0.0',
21
+ transport: 'stdio',
22
+ host: 'localhost',
23
+ port: 3000,
24
+ enableMetrics: true,
25
+ enableCaching: true,
26
+ cacheTTL: 10000,
27
+ logLevel: 'info',
28
+ requestTimeout: 30000,
29
+ maxRequestSize: 10 * 1024 * 1024,
30
+ };
31
+ export class MCPServer extends EventEmitter {
32
+ logger;
33
+ orchestrator;
34
+ swarmCoordinator;
35
+ config;
36
+ toolRegistry;
37
+ sessionManager;
38
+ resourceRegistry;
39
+ promptRegistry;
40
+ taskManager;
41
+ connectionPool;
42
+ transportManager;
43
+ rateLimiter;
44
+ samplingManager;
45
+ transports = [];
46
+ running = false;
47
+ startTime;
48
+ startupDuration;
49
+ currentSession;
50
+ resourceSubscriptions = new Map(); // sessionId -> subscribed URIs
51
+ serverInfo = {
52
+ name: 'Claude-Flow MCP Server V3',
53
+ version: '3.0.0',
54
+ };
55
+ // MCP protocol version — spec-required YYYY-MM-DD date string (#1874).
56
+ // Claude Code's Zod validator rejects any other shape.
57
+ protocolVersion = '2025-11-25';
58
+ // Full MCP 2025-11-25 capabilities
59
+ capabilities = {
60
+ logging: { level: 'info' },
61
+ tools: { listChanged: true },
62
+ resources: { listChanged: true, subscribe: true },
63
+ prompts: { listChanged: true },
64
+ sampling: {},
65
+ };
66
+ requestStats = {
67
+ total: 0,
68
+ successful: 0,
69
+ failed: 0,
70
+ totalResponseTime: 0,
71
+ };
72
+ constructor(config, logger, orchestrator, swarmCoordinator, toolAuthorizer) {
73
+ super();
74
+ this.logger = logger;
75
+ this.orchestrator = orchestrator;
76
+ this.swarmCoordinator = swarmCoordinator;
77
+ this.config = { ...DEFAULT_CONFIG, ...config };
78
+ this.toolRegistry = createToolRegistry(logger);
79
+ if (this.config.requireToolAuthorization && !toolAuthorizer) {
80
+ throw new Error('tool authorization is required but no authorizer was provided');
81
+ }
82
+ this.toolRegistry.setAuthorizer(toolAuthorizer);
83
+ this.sessionManager = createSessionManager(logger, {
84
+ maxSessions: 100,
85
+ sessionTimeout: 30 * 60 * 1000,
86
+ });
87
+ this.resourceRegistry = createResourceRegistry(logger, {
88
+ enableSubscriptions: true,
89
+ cacheEnabled: true,
90
+ cacheTTL: 60000,
91
+ });
92
+ this.promptRegistry = createPromptRegistry(logger);
93
+ this.taskManager = createTaskManager(logger, {
94
+ maxConcurrentTasks: 10,
95
+ taskTimeout: 300000,
96
+ });
97
+ this.transportManager = createTransportManager(logger);
98
+ this.rateLimiter = createRateLimiter(logger, {
99
+ requestsPerSecond: 100,
100
+ burstSize: 200,
101
+ perSessionLimit: 50,
102
+ });
103
+ this.samplingManager = createSamplingManager(logger);
104
+ if (this.config.connectionPool) {
105
+ this.connectionPool = createConnectionPool(this.config.connectionPool, logger, this.config.transport);
106
+ }
107
+ this.setupEventHandlers();
108
+ }
109
+ /**
110
+ * Get resource registry for external registration
111
+ */
112
+ getResourceRegistry() {
113
+ return this.resourceRegistry;
114
+ }
115
+ /**
116
+ * Get prompt registry for external registration
117
+ */
118
+ getPromptRegistry() {
119
+ return this.promptRegistry;
120
+ }
121
+ /**
122
+ * Get task manager for async operations
123
+ */
124
+ getTaskManager() {
125
+ return this.taskManager;
126
+ }
127
+ /**
128
+ * Get rate limiter for configuration
129
+ */
130
+ getRateLimiter() {
131
+ return this.rateLimiter;
132
+ }
133
+ /**
134
+ * Get sampling manager for LLM provider registration
135
+ */
136
+ getSamplingManager() {
137
+ return this.samplingManager;
138
+ }
139
+ /**
140
+ * Register an LLM provider for sampling
141
+ */
142
+ registerLLMProvider(provider, isDefault = false) {
143
+ this.samplingManager.registerProvider(provider, isDefault);
144
+ }
145
+ async start() {
146
+ if (this.running) {
147
+ throw new MCPServerError('Server already running');
148
+ }
149
+ const startTime = performance.now();
150
+ this.startTime = new Date();
151
+ this.logger.info('Starting MCP server', {
152
+ name: this.config.name,
153
+ version: this.config.version,
154
+ transport: this.config.transport,
155
+ });
156
+ try {
157
+ const hosts = this.config.transport === 'http'
158
+ ? [...new Set([this.config.host, ...(this.config.additionalHosts ?? [])])]
159
+ : [this.config.host];
160
+ const transports = hosts.map((host) => createTransport(this.config.transport, this.logger, {
161
+ type: this.config.transport,
162
+ host,
163
+ port: this.config.port,
164
+ corsEnabled: this.config.corsEnabled,
165
+ corsOrigins: this.config.corsOrigins,
166
+ auth: this.config.auth,
167
+ maxRequestSize: String(this.config.maxRequestSize),
168
+ requestTimeout: this.config.requestTimeout,
169
+ }));
170
+ for (const transport of transports) {
171
+ transport.onRequest(async (request) => await this.handleRequest(request));
172
+ transport.onNotification(async (notification) => {
173
+ await this.handleNotification(notification);
174
+ });
175
+ }
176
+ const started = [];
177
+ try {
178
+ for (const transport of transports) {
179
+ await transport.start();
180
+ started.push(transport);
181
+ }
182
+ }
183
+ catch (error) {
184
+ await Promise.all(started.map((transport) => transport.stop()));
185
+ throw error;
186
+ }
187
+ this.transports = started;
188
+ await this.registerBuiltInTools();
189
+ this.running = true;
190
+ this.startupDuration = performance.now() - startTime;
191
+ this.logger.info('MCP server started', {
192
+ startupTime: `${this.startupDuration.toFixed(2)}ms`,
193
+ tools: this.toolRegistry.getToolCount(),
194
+ });
195
+ this.emit('server:started', {
196
+ startupTime: this.startupDuration,
197
+ tools: this.toolRegistry.getToolCount(),
198
+ });
199
+ }
200
+ catch (error) {
201
+ this.logger.error('Failed to start MCP server', { error });
202
+ throw new MCPServerError('Failed to start server', ErrorCodes.INTERNAL_ERROR, { error });
203
+ }
204
+ }
205
+ async stop() {
206
+ if (!this.running) {
207
+ return;
208
+ }
209
+ this.logger.info('Stopping MCP server');
210
+ try {
211
+ if (this.transports.length > 0) {
212
+ const transports = this.transports;
213
+ this.transports = [];
214
+ await Promise.all(transports.map((transport) => transport.stop()));
215
+ }
216
+ this.sessionManager.clearAll();
217
+ this.taskManager.destroy();
218
+ this.resourceSubscriptions.clear();
219
+ this.rateLimiter.destroy();
220
+ if (this.connectionPool) {
221
+ await this.connectionPool.clear();
222
+ }
223
+ this.running = false;
224
+ this.currentSession = undefined;
225
+ this.logger.info('MCP server stopped');
226
+ this.emit('server:stopped');
227
+ }
228
+ catch (error) {
229
+ this.logger.error('Error stopping MCP server', { error });
230
+ throw error;
231
+ }
232
+ }
233
+ registerTool(tool) {
234
+ return this.toolRegistry.register(tool);
235
+ }
236
+ registerTools(tools) {
237
+ return this.toolRegistry.registerBatch(tools);
238
+ }
239
+ setToolAuthorizer(authorizer) {
240
+ if (this.config.requireToolAuthorization && !authorizer) {
241
+ throw new Error('tool authorization is required and cannot be disabled');
242
+ }
243
+ this.toolRegistry.setAuthorizer(authorizer);
244
+ }
245
+ unregisterTool(name) {
246
+ return this.toolRegistry.unregister(name);
247
+ }
248
+ async getHealthStatus() {
249
+ try {
250
+ const transportHealth = this.transports.length > 0
251
+ ? await Promise.all(this.transports.map((transport) => transport.getHealthStatus()))
252
+ : [{ healthy: false, error: 'Transport not initialized' }];
253
+ const sessionMetrics = this.sessionManager.getSessionMetrics();
254
+ const poolStats = this.connectionPool?.getStats();
255
+ const metrics = {
256
+ registeredTools: this.toolRegistry.getToolCount(),
257
+ totalRequests: this.requestStats.total,
258
+ successfulRequests: this.requestStats.successful,
259
+ failedRequests: this.requestStats.failed,
260
+ totalSessions: sessionMetrics.total,
261
+ activeSessions: sessionMetrics.active,
262
+ ...Object.assign({}, ...transportHealth.map((health) => health.metrics || {})),
263
+ };
264
+ if (poolStats) {
265
+ metrics.poolConnections = poolStats.totalConnections;
266
+ metrics.poolIdleConnections = poolStats.idleConnections;
267
+ metrics.poolBusyConnections = poolStats.busyConnections;
268
+ }
269
+ return {
270
+ healthy: this.running && transportHealth.every((health) => health.healthy),
271
+ error: transportHealth.map((health) => health.error).filter(Boolean).join('; ') || undefined,
272
+ metrics,
273
+ };
274
+ }
275
+ catch (error) {
276
+ return {
277
+ healthy: false,
278
+ error: error instanceof Error ? error.message : 'Unknown error',
279
+ };
280
+ }
281
+ }
282
+ getMetrics() {
283
+ const sessionMetrics = this.sessionManager.getSessionMetrics();
284
+ const registryStats = this.toolRegistry.getStats();
285
+ return {
286
+ totalRequests: this.requestStats.total,
287
+ successfulRequests: this.requestStats.successful,
288
+ failedRequests: this.requestStats.failed,
289
+ averageResponseTime: this.requestStats.total > 0
290
+ ? this.requestStats.totalResponseTime / this.requestStats.total
291
+ : 0,
292
+ activeSessions: sessionMetrics.active,
293
+ toolInvocations: Object.fromEntries(registryStats.topTools.map((t) => [t.name, t.calls])),
294
+ errors: {},
295
+ lastReset: this.startTime || new Date(),
296
+ startupTime: this.startupDuration,
297
+ uptime: this.startTime ? Date.now() - this.startTime.getTime() : 0,
298
+ };
299
+ }
300
+ getSessions() {
301
+ return this.sessionManager.getActiveSessions();
302
+ }
303
+ getSession(sessionId) {
304
+ return this.sessionManager.getSession(sessionId);
305
+ }
306
+ terminateSession(sessionId) {
307
+ const result = this.sessionManager.closeSession(sessionId, 'Terminated by server');
308
+ if (this.currentSession?.id === sessionId) {
309
+ this.currentSession = undefined;
310
+ }
311
+ return result;
312
+ }
313
+ async handleRequest(request) {
314
+ const startTime = performance.now();
315
+ this.requestStats.total++;
316
+ this.logger.debug('Handling request', {
317
+ id: request.id,
318
+ method: request.method,
319
+ });
320
+ // Rate limiting check (skip for initialize)
321
+ if (request.method !== 'initialize') {
322
+ const sessionId = this.currentSession?.id;
323
+ const rateLimitResult = this.rateLimiter.check(sessionId);
324
+ if (!rateLimitResult.allowed) {
325
+ this.requestStats.failed++;
326
+ return {
327
+ jsonrpc: '2.0',
328
+ id: request.id,
329
+ error: {
330
+ code: -32000,
331
+ message: 'Rate limit exceeded',
332
+ data: { retryAfter: rateLimitResult.retryAfter },
333
+ },
334
+ };
335
+ }
336
+ this.rateLimiter.consume(sessionId);
337
+ }
338
+ try {
339
+ if (request.method === 'initialize') {
340
+ return await this.handleInitialize(request);
341
+ }
342
+ const session = this.getOrCreateSession();
343
+ if (!session.isInitialized && request.method !== 'initialized') {
344
+ return this.createErrorResponse(request.id, ErrorCodes.SERVER_NOT_INITIALIZED, 'Server not initialized');
345
+ }
346
+ this.sessionManager.updateActivity(session.id);
347
+ const response = await this.routeRequest(request);
348
+ const duration = performance.now() - startTime;
349
+ this.requestStats.successful++;
350
+ this.requestStats.totalResponseTime += duration;
351
+ this.logger.debug('Request completed', {
352
+ id: request.id,
353
+ method: request.method,
354
+ duration: `${duration.toFixed(2)}ms`,
355
+ });
356
+ return response;
357
+ }
358
+ catch (error) {
359
+ const duration = performance.now() - startTime;
360
+ this.requestStats.failed++;
361
+ this.requestStats.totalResponseTime += duration;
362
+ this.logger.error('Request failed', {
363
+ id: request.id,
364
+ method: request.method,
365
+ error,
366
+ });
367
+ return this.createErrorResponse(request.id, ErrorCodes.INTERNAL_ERROR, error instanceof Error ? error.message : 'Internal error');
368
+ }
369
+ }
370
+ async handleNotification(notification) {
371
+ this.logger.debug('Handling notification', { method: notification.method });
372
+ switch (notification.method) {
373
+ case 'initialized':
374
+ this.logger.info('Client initialized notification received');
375
+ break;
376
+ case 'notifications/cancelled':
377
+ this.logger.debug('Request cancelled', notification.params);
378
+ break;
379
+ default:
380
+ this.logger.debug('Unknown notification', { method: notification.method });
381
+ }
382
+ }
383
+ async handleInitialize(request) {
384
+ const params = request.params;
385
+ if (!params) {
386
+ return this.createErrorResponse(request.id, ErrorCodes.INVALID_PARAMS, 'Invalid params');
387
+ }
388
+ const session = this.sessionManager.createSession(this.config.transport);
389
+ this.sessionManager.initializeSession(session.id, params);
390
+ this.currentSession = session;
391
+ const result = {
392
+ protocolVersion: this.protocolVersion,
393
+ capabilities: this.capabilities,
394
+ serverInfo: this.serverInfo,
395
+ instructions: 'Claude-Flow MCP Server V3 ready for tool execution',
396
+ };
397
+ this.logger.info('Session initialized', {
398
+ sessionId: session.id,
399
+ clientInfo: params.clientInfo,
400
+ });
401
+ return {
402
+ jsonrpc: '2.0',
403
+ id: request.id,
404
+ result,
405
+ };
406
+ }
407
+ async routeRequest(request) {
408
+ switch (request.method) {
409
+ // Tool methods
410
+ case 'tools/list':
411
+ return this.handleToolsList(request);
412
+ case 'tools/call':
413
+ return this.handleToolsCall(request);
414
+ // Resource methods (MCP 2025-11-25)
415
+ case 'resources/list':
416
+ return this.handleResourcesList(request);
417
+ case 'resources/read':
418
+ return this.handleResourcesRead(request);
419
+ case 'resources/subscribe':
420
+ return this.handleResourcesSubscribe(request);
421
+ case 'resources/unsubscribe':
422
+ return this.handleResourcesUnsubscribe(request);
423
+ // Prompt methods (MCP 2025-11-25)
424
+ case 'prompts/list':
425
+ return this.handlePromptsList(request);
426
+ case 'prompts/get':
427
+ return this.handlePromptsGet(request);
428
+ // Task methods (MCP 2025-11-25)
429
+ case 'tasks/status':
430
+ return this.handleTasksStatus(request);
431
+ case 'tasks/cancel':
432
+ return this.handleTasksCancel(request);
433
+ // Completion (MCP 2025-11-25)
434
+ case 'completion/complete':
435
+ return this.handleCompletion(request);
436
+ // Logging (MCP 2025-11-25)
437
+ case 'logging/setLevel':
438
+ return this.handleLoggingSetLevel(request);
439
+ // Sampling (MCP 2025-11-25)
440
+ case 'sampling/createMessage':
441
+ return this.handleSamplingCreateMessage(request);
442
+ // Utility
443
+ case 'ping':
444
+ return {
445
+ jsonrpc: '2.0',
446
+ id: request.id,
447
+ result: { pong: true, timestamp: Date.now() },
448
+ };
449
+ default:
450
+ // Check if it's a direct tool call
451
+ if (this.toolRegistry.hasTool(request.method)) {
452
+ return this.handleToolExecution(request);
453
+ }
454
+ return this.createErrorResponse(request.id, ErrorCodes.METHOD_NOT_FOUND, `Method not found: ${request.method}`);
455
+ }
456
+ }
457
+ handleToolsList(request) {
458
+ const tools = this.toolRegistry.listTools().map((t) => ({
459
+ name: t.name,
460
+ description: t.description,
461
+ inputSchema: this.toolRegistry.getTool(t.name)?.inputSchema,
462
+ }));
463
+ return {
464
+ jsonrpc: '2.0',
465
+ id: request.id,
466
+ result: { tools },
467
+ };
468
+ }
469
+ async handleToolsCall(request) {
470
+ const params = request.params;
471
+ if (!params?.name) {
472
+ return this.createErrorResponse(request.id, ErrorCodes.INVALID_PARAMS, 'Tool name is required');
473
+ }
474
+ const context = {
475
+ sessionId: this.currentSession?.id || 'unknown',
476
+ requestId: request.id,
477
+ orchestrator: this.orchestrator,
478
+ swarmCoordinator: this.swarmCoordinator,
479
+ };
480
+ const result = await this.toolRegistry.execute(params.name, params.arguments || {}, context);
481
+ return {
482
+ jsonrpc: '2.0',
483
+ id: request.id,
484
+ result,
485
+ };
486
+ }
487
+ async handleToolExecution(request) {
488
+ const context = {
489
+ sessionId: this.currentSession?.id || 'unknown',
490
+ requestId: request.id,
491
+ orchestrator: this.orchestrator,
492
+ swarmCoordinator: this.swarmCoordinator,
493
+ };
494
+ const result = await this.toolRegistry.execute(request.method, request.params || {}, context);
495
+ return {
496
+ jsonrpc: '2.0',
497
+ id: request.id,
498
+ result,
499
+ };
500
+ }
501
+ // ============================================================================
502
+ // Resource Handlers (MCP 2025-11-25)
503
+ // ============================================================================
504
+ handleResourcesList(request) {
505
+ const params = request.params;
506
+ const result = this.resourceRegistry.list(params?.cursor);
507
+ return {
508
+ jsonrpc: '2.0',
509
+ id: request.id,
510
+ result,
511
+ };
512
+ }
513
+ async handleResourcesRead(request) {
514
+ const params = request.params;
515
+ if (!params?.uri) {
516
+ return this.createErrorResponse(request.id, ErrorCodes.INVALID_PARAMS, 'Resource URI is required');
517
+ }
518
+ try {
519
+ const result = await this.resourceRegistry.read(params.uri);
520
+ return {
521
+ jsonrpc: '2.0',
522
+ id: request.id,
523
+ result,
524
+ };
525
+ }
526
+ catch (error) {
527
+ return this.createErrorResponse(request.id, ErrorCodes.INVALID_PARAMS, error instanceof Error ? error.message : 'Resource read failed');
528
+ }
529
+ }
530
+ handleResourcesSubscribe(request) {
531
+ const params = request.params;
532
+ const sessionId = this.currentSession?.id;
533
+ if (!params?.uri) {
534
+ return this.createErrorResponse(request.id, ErrorCodes.INVALID_PARAMS, 'Resource URI is required');
535
+ }
536
+ if (!sessionId) {
537
+ return this.createErrorResponse(request.id, ErrorCodes.SERVER_NOT_INITIALIZED, 'No active session');
538
+ }
539
+ try {
540
+ // Track subscription for this session
541
+ let sessionSubs = this.resourceSubscriptions.get(sessionId);
542
+ if (!sessionSubs) {
543
+ sessionSubs = new Set();
544
+ this.resourceSubscriptions.set(sessionId, sessionSubs);
545
+ }
546
+ const subscriptionId = this.resourceRegistry.subscribe(params.uri, (uri, content) => {
547
+ // Send notification when resource updates
548
+ this.sendNotification('notifications/resources/updated', { uri });
549
+ });
550
+ sessionSubs.add(params.uri);
551
+ return {
552
+ jsonrpc: '2.0',
553
+ id: request.id,
554
+ result: { subscriptionId },
555
+ };
556
+ }
557
+ catch (error) {
558
+ return this.createErrorResponse(request.id, ErrorCodes.INTERNAL_ERROR, error instanceof Error ? error.message : 'Subscription failed');
559
+ }
560
+ }
561
+ handleResourcesUnsubscribe(request) {
562
+ const params = request.params;
563
+ const sessionId = this.currentSession?.id;
564
+ if (!params?.uri) {
565
+ return this.createErrorResponse(request.id, ErrorCodes.INVALID_PARAMS, 'Resource URI is required');
566
+ }
567
+ if (sessionId) {
568
+ const sessionSubs = this.resourceSubscriptions.get(sessionId);
569
+ if (sessionSubs) {
570
+ sessionSubs.delete(params.uri);
571
+ }
572
+ }
573
+ return {
574
+ jsonrpc: '2.0',
575
+ id: request.id,
576
+ result: { success: true },
577
+ };
578
+ }
579
+ // ============================================================================
580
+ // Prompt Handlers (MCP 2025-11-25)
581
+ // ============================================================================
582
+ handlePromptsList(request) {
583
+ const params = request.params;
584
+ const result = this.promptRegistry.list(params?.cursor);
585
+ return {
586
+ jsonrpc: '2.0',
587
+ id: request.id,
588
+ result,
589
+ };
590
+ }
591
+ async handlePromptsGet(request) {
592
+ const params = request.params;
593
+ if (!params?.name) {
594
+ return this.createErrorResponse(request.id, ErrorCodes.INVALID_PARAMS, 'Prompt name is required');
595
+ }
596
+ try {
597
+ const result = await this.promptRegistry.get(params.name, params.arguments);
598
+ return {
599
+ jsonrpc: '2.0',
600
+ id: request.id,
601
+ result,
602
+ };
603
+ }
604
+ catch (error) {
605
+ return this.createErrorResponse(request.id, ErrorCodes.INVALID_PARAMS, error instanceof Error ? error.message : 'Prompt get failed');
606
+ }
607
+ }
608
+ // ============================================================================
609
+ // Task Handlers (MCP 2025-11-25)
610
+ // ============================================================================
611
+ handleTasksStatus(request) {
612
+ const params = request.params;
613
+ if (params?.taskId) {
614
+ const task = this.taskManager.getTask(params.taskId);
615
+ if (!task) {
616
+ return this.createErrorResponse(request.id, ErrorCodes.INVALID_PARAMS, `Task not found: ${params.taskId}`);
617
+ }
618
+ return {
619
+ jsonrpc: '2.0',
620
+ id: request.id,
621
+ result: task,
622
+ };
623
+ }
624
+ // Return all tasks
625
+ return {
626
+ jsonrpc: '2.0',
627
+ id: request.id,
628
+ result: { tasks: this.taskManager.getAllTasks() },
629
+ };
630
+ }
631
+ handleTasksCancel(request) {
632
+ const params = request.params;
633
+ if (!params?.taskId) {
634
+ return this.createErrorResponse(request.id, ErrorCodes.INVALID_PARAMS, 'Task ID is required');
635
+ }
636
+ const success = this.taskManager.cancelTask(params.taskId, params.reason);
637
+ return {
638
+ jsonrpc: '2.0',
639
+ id: request.id,
640
+ result: { success },
641
+ };
642
+ }
643
+ // ============================================================================
644
+ // Completion Handler (MCP 2025-11-25)
645
+ // ============================================================================
646
+ handleCompletion(request) {
647
+ const params = request.params;
648
+ if (!params?.ref || !params?.argument) {
649
+ return this.createErrorResponse(request.id, ErrorCodes.INVALID_PARAMS, 'Completion reference and argument are required');
650
+ }
651
+ // Basic completion implementation - can be extended
652
+ const completions = [];
653
+ if (params.ref.type === 'ref/prompt') {
654
+ // Get prompt argument completions
655
+ const prompt = this.promptRegistry.getPrompt(params.ref.name || '');
656
+ if (prompt?.arguments) {
657
+ for (const arg of prompt.arguments) {
658
+ if (arg.name === params.argument.name) {
659
+ // Could add domain-specific completions here
660
+ }
661
+ }
662
+ }
663
+ }
664
+ else if (params.ref.type === 'ref/resource') {
665
+ // Get resource URI completions
666
+ const { resources } = this.resourceRegistry.list();
667
+ for (const resource of resources) {
668
+ if (resource.uri.startsWith(params.argument.value)) {
669
+ completions.push(resource.uri);
670
+ }
671
+ }
672
+ }
673
+ return {
674
+ jsonrpc: '2.0',
675
+ id: request.id,
676
+ result: {
677
+ completion: {
678
+ values: completions.slice(0, 10),
679
+ total: completions.length,
680
+ hasMore: completions.length > 10,
681
+ },
682
+ },
683
+ };
684
+ }
685
+ // ============================================================================
686
+ // Logging Handler (MCP 2025-11-25)
687
+ // ============================================================================
688
+ handleLoggingSetLevel(request) {
689
+ const params = request.params;
690
+ if (!params?.level) {
691
+ return this.createErrorResponse(request.id, ErrorCodes.INVALID_PARAMS, 'Log level is required');
692
+ }
693
+ // Update capabilities
694
+ this.capabilities.logging = { level: params.level };
695
+ this.logger.info('Log level updated', { level: params.level });
696
+ return {
697
+ jsonrpc: '2.0',
698
+ id: request.id,
699
+ result: { success: true },
700
+ };
701
+ }
702
+ // ============================================================================
703
+ // Sampling Handler (MCP 2025-11-25)
704
+ // ============================================================================
705
+ async handleSamplingCreateMessage(request) {
706
+ const params = request.params;
707
+ if (!params?.messages || !params?.maxTokens) {
708
+ return this.createErrorResponse(request.id, ErrorCodes.INVALID_PARAMS, 'messages and maxTokens are required');
709
+ }
710
+ // Check if sampling is available
711
+ const available = await this.samplingManager.isAvailable();
712
+ if (!available) {
713
+ return this.createErrorResponse(request.id, ErrorCodes.INTERNAL_ERROR, 'No LLM provider available for sampling');
714
+ }
715
+ try {
716
+ const result = await this.samplingManager.createMessage({
717
+ messages: params.messages.map((m) => ({
718
+ role: m.role,
719
+ content: m.content,
720
+ })),
721
+ maxTokens: params.maxTokens,
722
+ systemPrompt: params.systemPrompt,
723
+ modelPreferences: params.modelPreferences,
724
+ includeContext: params.includeContext,
725
+ temperature: params.temperature,
726
+ stopSequences: params.stopSequences,
727
+ metadata: params.metadata,
728
+ }, {
729
+ sessionId: this.currentSession?.id || 'unknown',
730
+ serverId: this.serverInfo.name,
731
+ });
732
+ return {
733
+ jsonrpc: '2.0',
734
+ id: request.id,
735
+ result,
736
+ };
737
+ }
738
+ catch (error) {
739
+ return this.createErrorResponse(request.id, ErrorCodes.INTERNAL_ERROR, error instanceof Error ? error.message : 'Sampling failed');
740
+ }
741
+ }
742
+ // ============================================================================
743
+ // Notification Sender
744
+ // ============================================================================
745
+ async sendNotification(method, params) {
746
+ await Promise.all(this.transports.map(async (transport) => {
747
+ if (transport.sendNotification) {
748
+ await transport.sendNotification({ jsonrpc: '2.0', method, params });
749
+ }
750
+ }));
751
+ }
752
+ getOrCreateSession() {
753
+ if (this.currentSession) {
754
+ return this.currentSession;
755
+ }
756
+ const session = this.sessionManager.createSession(this.config.transport);
757
+ this.currentSession = session;
758
+ return session;
759
+ }
760
+ createErrorResponse(id, code, message) {
761
+ return {
762
+ jsonrpc: '2.0',
763
+ id,
764
+ error: { code, message },
765
+ };
766
+ }
767
+ async registerBuiltInTools() {
768
+ this.registerTool({
769
+ name: 'system/info',
770
+ description: 'Get system information',
771
+ inputSchema: { type: 'object', properties: {} },
772
+ handler: async () => ({
773
+ name: this.serverInfo.name,
774
+ version: this.serverInfo.version,
775
+ platform: platform(),
776
+ arch: arch(),
777
+ runtime: 'Node.js',
778
+ uptime: this.startTime ? Date.now() - this.startTime.getTime() : 0,
779
+ }),
780
+ category: 'system',
781
+ });
782
+ this.registerTool({
783
+ name: 'system/health',
784
+ description: 'Get system health status',
785
+ inputSchema: { type: 'object', properties: {} },
786
+ handler: async () => await this.getHealthStatus(),
787
+ category: 'system',
788
+ cacheable: true,
789
+ cacheTTL: 2000,
790
+ });
791
+ this.registerTool({
792
+ name: 'system/metrics',
793
+ description: 'Get server metrics',
794
+ inputSchema: { type: 'object', properties: {} },
795
+ handler: async () => this.getMetrics(),
796
+ category: 'system',
797
+ cacheable: true,
798
+ cacheTTL: 1000,
799
+ });
800
+ this.registerTool({
801
+ name: 'tools/list-detailed',
802
+ description: 'List all registered tools with details',
803
+ inputSchema: {
804
+ type: 'object',
805
+ properties: {
806
+ category: { type: 'string', description: 'Filter by category' },
807
+ },
808
+ },
809
+ handler: async (input) => {
810
+ const params = input;
811
+ if (params.category) {
812
+ return this.toolRegistry.getByCategory(params.category);
813
+ }
814
+ return this.toolRegistry.listTools();
815
+ },
816
+ category: 'system',
817
+ });
818
+ this.logger.info('Built-in tools registered', {
819
+ count: 4,
820
+ });
821
+ }
822
+ setupEventHandlers() {
823
+ this.toolRegistry.on('tool:registered', (name) => {
824
+ this.emit('tool:registered', name);
825
+ });
826
+ this.toolRegistry.on('tool:called', (data) => {
827
+ this.emit('tool:called', data);
828
+ });
829
+ this.toolRegistry.on('tool:completed', (data) => {
830
+ this.emit('tool:completed', data);
831
+ });
832
+ this.toolRegistry.on('tool:error', (data) => {
833
+ this.emit('tool:error', data);
834
+ });
835
+ this.sessionManager.on('session:created', (session) => {
836
+ this.emit('session:created', session);
837
+ });
838
+ this.sessionManager.on('session:closed', (data) => {
839
+ this.emit('session:closed', data);
840
+ });
841
+ this.sessionManager.on('session:expired', (session) => {
842
+ this.emit('session:expired', session);
843
+ });
844
+ }
845
+ }
846
+ export function createMCPServer(config, logger, orchestrator, swarmCoordinator, toolAuthorizer) {
847
+ return new MCPServer(config, logger, orchestrator, swarmCoordinator, toolAuthorizer);
848
+ }
849
+ //# sourceMappingURL=server.js.map