claude-flow 1.0.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.
Files changed (83) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +612 -0
  3. package/bin/claude-flow +0 -0
  4. package/bin/claude-flow-simple +0 -0
  5. package/bin/claude-flow-typecheck +0 -0
  6. package/deno.json +84 -0
  7. package/package.json +45 -0
  8. package/scripts/check-links.ts +274 -0
  9. package/scripts/check-performance-regression.ts +168 -0
  10. package/scripts/claude-sparc.sh +562 -0
  11. package/scripts/coverage-report.ts +692 -0
  12. package/scripts/demo-task-system.ts +224 -0
  13. package/scripts/install.js +72 -0
  14. package/scripts/test-batch-tasks.ts +29 -0
  15. package/scripts/test-coordination-features.ts +238 -0
  16. package/scripts/test-mcp.ts +251 -0
  17. package/scripts/test-runner.ts +571 -0
  18. package/scripts/validate-examples.ts +288 -0
  19. package/src/cli/cli-core.ts +273 -0
  20. package/src/cli/commands/agent.ts +83 -0
  21. package/src/cli/commands/config.ts +442 -0
  22. package/src/cli/commands/help.ts +765 -0
  23. package/src/cli/commands/index.ts +963 -0
  24. package/src/cli/commands/mcp.ts +191 -0
  25. package/src/cli/commands/memory.ts +74 -0
  26. package/src/cli/commands/monitor.ts +403 -0
  27. package/src/cli/commands/session.ts +595 -0
  28. package/src/cli/commands/start.ts +156 -0
  29. package/src/cli/commands/status.ts +345 -0
  30. package/src/cli/commands/task.ts +79 -0
  31. package/src/cli/commands/workflow.ts +763 -0
  32. package/src/cli/completion.ts +553 -0
  33. package/src/cli/formatter.ts +310 -0
  34. package/src/cli/index.ts +211 -0
  35. package/src/cli/main.ts +23 -0
  36. package/src/cli/repl.ts +1050 -0
  37. package/src/cli/simple-cli.js +211 -0
  38. package/src/cli/simple-cli.ts +211 -0
  39. package/src/coordination/README.md +400 -0
  40. package/src/coordination/advanced-scheduler.ts +487 -0
  41. package/src/coordination/circuit-breaker.ts +366 -0
  42. package/src/coordination/conflict-resolution.ts +490 -0
  43. package/src/coordination/dependency-graph.ts +475 -0
  44. package/src/coordination/index.ts +63 -0
  45. package/src/coordination/manager.ts +460 -0
  46. package/src/coordination/messaging.ts +290 -0
  47. package/src/coordination/metrics.ts +585 -0
  48. package/src/coordination/resources.ts +322 -0
  49. package/src/coordination/scheduler.ts +390 -0
  50. package/src/coordination/work-stealing.ts +224 -0
  51. package/src/core/config.ts +627 -0
  52. package/src/core/event-bus.ts +186 -0
  53. package/src/core/json-persistence.ts +183 -0
  54. package/src/core/logger.ts +262 -0
  55. package/src/core/orchestrator-fixed.ts +312 -0
  56. package/src/core/orchestrator.ts +1234 -0
  57. package/src/core/persistence.ts +276 -0
  58. package/src/mcp/auth.ts +438 -0
  59. package/src/mcp/claude-flow-tools.ts +1280 -0
  60. package/src/mcp/load-balancer.ts +510 -0
  61. package/src/mcp/router.ts +240 -0
  62. package/src/mcp/server.ts +548 -0
  63. package/src/mcp/session-manager.ts +418 -0
  64. package/src/mcp/tools.ts +180 -0
  65. package/src/mcp/transports/base.ts +21 -0
  66. package/src/mcp/transports/http.ts +457 -0
  67. package/src/mcp/transports/stdio.ts +254 -0
  68. package/src/memory/backends/base.ts +22 -0
  69. package/src/memory/backends/markdown.ts +283 -0
  70. package/src/memory/backends/sqlite.ts +329 -0
  71. package/src/memory/cache.ts +238 -0
  72. package/src/memory/indexer.ts +238 -0
  73. package/src/memory/manager.ts +572 -0
  74. package/src/terminal/adapters/base.ts +29 -0
  75. package/src/terminal/adapters/native.ts +504 -0
  76. package/src/terminal/adapters/vscode.ts +340 -0
  77. package/src/terminal/manager.ts +308 -0
  78. package/src/terminal/pool.ts +271 -0
  79. package/src/terminal/session.ts +250 -0
  80. package/src/terminal/vscode-bridge.ts +242 -0
  81. package/src/utils/errors.ts +231 -0
  82. package/src/utils/helpers.ts +476 -0
  83. package/src/utils/types.ts +493 -0
@@ -0,0 +1,548 @@
1
+ /**
2
+ * MCP (Model Context Protocol) server implementation
3
+ */
4
+
5
+ import {
6
+ MCPConfig,
7
+ MCPRequest,
8
+ MCPResponse,
9
+ MCPError,
10
+ MCPTool,
11
+ MCPInitializeParams,
12
+ MCPInitializeResult,
13
+ MCPSession,
14
+ MCPMetrics,
15
+ MCPProtocolVersion,
16
+ MCPCapabilities,
17
+ MCPContext,
18
+ } from '../utils/types.ts';
19
+ import { IEventBus } from '../core/event-bus.ts';
20
+ import { ILogger } from '../core/logger.ts';
21
+ import { MCPError as MCPErrorClass, MCPMethodNotFoundError } from '../utils/errors.ts';
22
+ import { ITransport } from './transports/base.ts';
23
+ import { StdioTransport } from './transports/stdio.ts';
24
+ import { HttpTransport } from './transports/http.ts';
25
+ import { ToolRegistry } from './tools.ts';
26
+ import { RequestRouter } from './router.ts';
27
+ import { SessionManager, ISessionManager } from './session-manager.ts';
28
+ import { AuthManager, IAuthManager } from './auth.ts';
29
+ import { LoadBalancer, ILoadBalancer, RequestQueue } from './load-balancer.ts';
30
+ import { createClaudeFlowTools, ClaudeFlowToolContext } from './claude-flow-tools.ts';
31
+
32
+ export interface IMCPServer {
33
+ start(): Promise<void>;
34
+ stop(): Promise<void>;
35
+ registerTool(tool: MCPTool): void;
36
+ getHealthStatus(): Promise<{
37
+ healthy: boolean;
38
+ error?: string;
39
+ metrics?: Record<string, number>;
40
+ }>;
41
+ getMetrics(): MCPMetrics;
42
+ getSessions(): MCPSession[];
43
+ getSession(sessionId: string): MCPSession | undefined;
44
+ terminateSession(sessionId: string): void;
45
+ }
46
+
47
+ /**
48
+ * MCP server implementation
49
+ */
50
+ export class MCPServer implements IMCPServer {
51
+ private transport: ITransport;
52
+ private toolRegistry: ToolRegistry;
53
+ private router: RequestRouter;
54
+ private sessionManager: ISessionManager;
55
+ private authManager: IAuthManager;
56
+ private loadBalancer?: ILoadBalancer;
57
+ private requestQueue?: RequestQueue;
58
+ private running = false;
59
+ private currentSession?: MCPSession | undefined;
60
+
61
+ private readonly serverInfo = {
62
+ name: 'Claude-Flow MCP Server',
63
+ version: '1.0.0',
64
+ };
65
+
66
+ private readonly supportedProtocolVersion: MCPProtocolVersion = {
67
+ major: 2024,
68
+ minor: 11,
69
+ patch: 5,
70
+ };
71
+
72
+ private readonly serverCapabilities: MCPCapabilities = {
73
+ logging: {
74
+ level: 'info',
75
+ },
76
+ tools: {
77
+ listChanged: true,
78
+ },
79
+ resources: {
80
+ listChanged: false,
81
+ subscribe: false,
82
+ },
83
+ prompts: {
84
+ listChanged: false,
85
+ },
86
+ };
87
+
88
+ constructor(
89
+ private config: MCPConfig,
90
+ private eventBus: IEventBus,
91
+ private logger: ILogger,
92
+ private orchestrator?: any, // Reference to orchestrator instance
93
+ ) {
94
+ // Initialize transport
95
+ this.transport = this.createTransport();
96
+
97
+ // Initialize tool registry
98
+ this.toolRegistry = new ToolRegistry(logger);
99
+
100
+ // Initialize session manager
101
+ this.sessionManager = new SessionManager(config, logger);
102
+
103
+ // Initialize auth manager
104
+ this.authManager = new AuthManager(config.auth || { enabled: false, method: 'token' }, logger);
105
+
106
+ // Initialize load balancer if enabled
107
+ if (config.loadBalancer?.enabled) {
108
+ this.loadBalancer = new LoadBalancer(config.loadBalancer, logger);
109
+ this.requestQueue = new RequestQueue(1000, 30000, logger);
110
+ }
111
+
112
+ // Initialize request router
113
+ this.router = new RequestRouter(this.toolRegistry, logger);
114
+ }
115
+
116
+ async start(): Promise<void> {
117
+ if (this.running) {
118
+ throw new MCPErrorClass('MCP server already running');
119
+ }
120
+
121
+ this.logger.info('Starting MCP server', { transport: this.config.transport });
122
+
123
+ try {
124
+ // Set up request handler
125
+ this.transport.onRequest(async (request) => {
126
+ return await this.handleRequest(request);
127
+ });
128
+
129
+ // Start transport
130
+ await this.transport.start();
131
+
132
+ // Register built-in tools
133
+ this.registerBuiltInTools();
134
+
135
+ this.running = true;
136
+ this.logger.info('MCP server started successfully');
137
+ } catch (error) {
138
+ this.logger.error('Failed to start MCP server', error);
139
+ throw new MCPErrorClass('Failed to start MCP server', { error });
140
+ }
141
+ }
142
+
143
+ async stop(): Promise<void> {
144
+ if (!this.running) {
145
+ return;
146
+ }
147
+
148
+ this.logger.info('Stopping MCP server');
149
+
150
+ try {
151
+ // Stop transport
152
+ await this.transport.stop();
153
+
154
+ // Clean up session manager
155
+ if (this.sessionManager && 'destroy' in this.sessionManager) {
156
+ (this.sessionManager as any).destroy();
157
+ }
158
+
159
+ // Clean up all sessions
160
+ for (const session of this.sessionManager.getActiveSessions()) {
161
+ this.sessionManager.removeSession(session.id);
162
+ }
163
+
164
+ this.running = false;
165
+ this.currentSession = undefined;
166
+ this.logger.info('MCP server stopped');
167
+ } catch (error) {
168
+ this.logger.error('Error stopping MCP server', error);
169
+ throw error;
170
+ }
171
+ }
172
+
173
+ registerTool(tool: MCPTool): void {
174
+ this.toolRegistry.register(tool);
175
+ this.logger.info('Tool registered', { name: tool.name });
176
+ }
177
+
178
+ async getHealthStatus(): Promise<{
179
+ healthy: boolean;
180
+ error?: string;
181
+ metrics?: Record<string, number>;
182
+ }> {
183
+ try {
184
+ const transportHealth = await this.transport.getHealthStatus();
185
+ const registeredTools = this.toolRegistry.getToolCount();
186
+ const { totalRequests, successfulRequests, failedRequests } = this.router.getMetrics();
187
+ const sessionMetrics = this.sessionManager.getSessionMetrics();
188
+
189
+ const metrics: Record<string, number> = {
190
+ registeredTools,
191
+ totalRequests,
192
+ successfulRequests,
193
+ failedRequests,
194
+ totalSessions: sessionMetrics.total,
195
+ activeSessions: sessionMetrics.active,
196
+ authenticatedSessions: sessionMetrics.authenticated,
197
+ expiredSessions: sessionMetrics.expired,
198
+ ...transportHealth.metrics,
199
+ };
200
+
201
+ if (this.loadBalancer) {
202
+ const lbMetrics = this.loadBalancer.getMetrics();
203
+ metrics.rateLimitedRequests = lbMetrics.rateLimitedRequests;
204
+ metrics.averageResponseTime = lbMetrics.averageResponseTime;
205
+ metrics.requestsPerSecond = lbMetrics.requestsPerSecond;
206
+ metrics.circuitBreakerTrips = lbMetrics.circuitBreakerTrips;
207
+ }
208
+
209
+ const status: { healthy: boolean; error?: string; metrics?: Record<string, number> } = {
210
+ healthy: this.running && transportHealth.healthy,
211
+ metrics,
212
+ };
213
+ if (transportHealth.error !== undefined) {
214
+ status.error = transportHealth.error;
215
+ }
216
+ return status;
217
+ } catch (error) {
218
+ return {
219
+ healthy: false,
220
+ error: error instanceof Error ? error.message : 'Unknown error',
221
+ };
222
+ }
223
+ }
224
+
225
+ getMetrics(): MCPMetrics {
226
+ const routerMetrics = this.router.getMetrics();
227
+ const sessionMetrics = this.sessionManager.getSessionMetrics();
228
+ const lbMetrics = this.loadBalancer?.getMetrics();
229
+
230
+ return {
231
+ totalRequests: routerMetrics.totalRequests,
232
+ successfulRequests: routerMetrics.successfulRequests,
233
+ failedRequests: routerMetrics.failedRequests,
234
+ averageResponseTime: lbMetrics?.averageResponseTime || 0,
235
+ activeSessions: sessionMetrics.active,
236
+ toolInvocations: {}, // TODO: Implement tool-specific metrics
237
+ errors: {}, // TODO: Implement error categorization
238
+ lastReset: lbMetrics?.lastReset || new Date(),
239
+ };
240
+ }
241
+
242
+ getSessions(): MCPSession[] {
243
+ return this.sessionManager.getActiveSessions();
244
+ }
245
+
246
+ getSession(sessionId: string): MCPSession | undefined {
247
+ return this.sessionManager.getSession(sessionId);
248
+ }
249
+
250
+ terminateSession(sessionId: string): void {
251
+ this.sessionManager.removeSession(sessionId);
252
+ if (this.currentSession?.id === sessionId) {
253
+ this.currentSession = undefined;
254
+ }
255
+ }
256
+
257
+ private async handleRequest(request: MCPRequest): Promise<MCPResponse> {
258
+ this.logger.debug('Handling MCP request', {
259
+ id: request.id,
260
+ method: request.method,
261
+ });
262
+
263
+ try {
264
+ // Handle initialization request separately
265
+ if (request.method === 'initialize') {
266
+ return await this.handleInitialize(request);
267
+ }
268
+
269
+ // Get or create session
270
+ const session = this.getOrCreateSession();
271
+
272
+ // Check if session is initialized for non-initialize requests
273
+ if (!session.isInitialized) {
274
+ return {
275
+ jsonrpc: '2.0',
276
+ id: request.id,
277
+ error: {
278
+ code: -32002,
279
+ message: 'Server not initialized',
280
+ },
281
+ };
282
+ }
283
+
284
+ // Update session activity
285
+ this.sessionManager.updateActivity(session.id);
286
+
287
+ // Check load balancer constraints
288
+ if (this.loadBalancer) {
289
+ const allowed = await this.loadBalancer.shouldAllowRequest(session, request);
290
+ if (!allowed) {
291
+ return {
292
+ jsonrpc: '2.0',
293
+ id: request.id,
294
+ error: {
295
+ code: -32000,
296
+ message: 'Rate limit exceeded or circuit breaker open',
297
+ },
298
+ };
299
+ }
300
+ }
301
+
302
+ // Record request start
303
+ const requestMetrics = this.loadBalancer?.recordRequestStart(session, request);
304
+
305
+ try {
306
+ // Process request through router
307
+ const result = await this.router.route(request);
308
+
309
+ const response: MCPResponse = {
310
+ jsonrpc: '2.0',
311
+ id: request.id,
312
+ result,
313
+ };
314
+
315
+ // Record success
316
+ if (requestMetrics) {
317
+ this.loadBalancer?.recordRequestEnd(requestMetrics, response);
318
+ }
319
+
320
+ return response;
321
+ } catch (error) {
322
+ // Record failure
323
+ if (requestMetrics) {
324
+ this.loadBalancer?.recordRequestEnd(requestMetrics, undefined, error as Error);
325
+ }
326
+ throw error;
327
+ }
328
+ } catch (error) {
329
+ this.logger.error('Error handling MCP request', {
330
+ id: request.id,
331
+ method: request.method,
332
+ error,
333
+ });
334
+
335
+ return {
336
+ jsonrpc: '2.0',
337
+ id: request.id,
338
+ error: this.errorToMCPError(error),
339
+ };
340
+ }
341
+ }
342
+
343
+ private async handleInitialize(request: MCPRequest): Promise<MCPResponse> {
344
+ try {
345
+ const params = request.params as MCPInitializeParams;
346
+
347
+ if (!params) {
348
+ return {
349
+ jsonrpc: '2.0',
350
+ id: request.id,
351
+ error: {
352
+ code: -32602,
353
+ message: 'Invalid params',
354
+ },
355
+ };
356
+ }
357
+
358
+ // Create session
359
+ const session = this.sessionManager.createSession(this.config.transport);
360
+ this.currentSession = session;
361
+
362
+ // Initialize session
363
+ this.sessionManager.initializeSession(session.id, params);
364
+
365
+ // Prepare response
366
+ const result: MCPInitializeResult = {
367
+ protocolVersion: this.supportedProtocolVersion,
368
+ capabilities: this.serverCapabilities,
369
+ serverInfo: this.serverInfo,
370
+ instructions: 'Claude-Flow MCP Server ready for tool execution',
371
+ };
372
+
373
+ this.logger.info('Session initialized', {
374
+ sessionId: session.id,
375
+ clientInfo: params.clientInfo,
376
+ protocolVersion: params.protocolVersion,
377
+ });
378
+
379
+ return {
380
+ jsonrpc: '2.0',
381
+ id: request.id,
382
+ result,
383
+ };
384
+ } catch (error) {
385
+ this.logger.error('Error during initialization', error);
386
+ return {
387
+ jsonrpc: '2.0',
388
+ id: request.id,
389
+ error: this.errorToMCPError(error),
390
+ };
391
+ }
392
+ }
393
+
394
+ private getOrCreateSession(): MCPSession {
395
+ if (this.currentSession) {
396
+ return this.currentSession;
397
+ }
398
+
399
+ // For stdio transport, create a default session
400
+ const session = this.sessionManager.createSession(this.config.transport);
401
+ this.currentSession = session;
402
+ return session;
403
+ }
404
+
405
+ private createTransport(): ITransport {
406
+ switch (this.config.transport) {
407
+ case 'stdio':
408
+ return new StdioTransport(this.logger);
409
+
410
+ case 'http':
411
+ return new HttpTransport(
412
+ this.config.host || 'localhost',
413
+ this.config.port || 3000,
414
+ this.config.tlsEnabled || false,
415
+ this.logger,
416
+ );
417
+
418
+ default:
419
+ throw new MCPErrorClass(`Unknown transport type: ${this.config.transport}`);
420
+ }
421
+ }
422
+
423
+ private registerBuiltInTools(): void {
424
+ // System information tool
425
+ this.registerTool({
426
+ name: 'system/info',
427
+ description: 'Get system information',
428
+ inputSchema: {
429
+ type: 'object',
430
+ properties: {},
431
+ },
432
+ handler: async () => {
433
+ return {
434
+ version: '1.0.0',
435
+ platform: Deno.build.os,
436
+ arch: Deno.build.arch,
437
+ runtime: 'Deno',
438
+ uptime: performance.now(),
439
+ };
440
+ },
441
+ });
442
+
443
+ // Health check tool
444
+ this.registerTool({
445
+ name: 'system/health',
446
+ description: 'Get system health status',
447
+ inputSchema: {
448
+ type: 'object',
449
+ properties: {},
450
+ },
451
+ handler: async () => {
452
+ return await this.getHealthStatus();
453
+ },
454
+ });
455
+
456
+ // List tools
457
+ this.registerTool({
458
+ name: 'tools/list',
459
+ description: 'List all available tools',
460
+ inputSchema: {
461
+ type: 'object',
462
+ properties: {},
463
+ },
464
+ handler: async () => {
465
+ return this.toolRegistry.listTools();
466
+ },
467
+ });
468
+
469
+ // Tool schema
470
+ this.registerTool({
471
+ name: 'tools/schema',
472
+ description: 'Get schema for a specific tool',
473
+ inputSchema: {
474
+ type: 'object',
475
+ properties: {
476
+ name: { type: 'string' },
477
+ },
478
+ required: ['name'],
479
+ },
480
+ handler: async (input: any) => {
481
+ const tool = this.toolRegistry.getTool(input.name);
482
+ if (!tool) {
483
+ throw new Error(`Tool not found: ${input.name}`);
484
+ }
485
+ return {
486
+ name: tool.name,
487
+ description: tool.description,
488
+ inputSchema: tool.inputSchema,
489
+ };
490
+ },
491
+ });
492
+
493
+ // Register Claude-Flow specific tools if orchestrator is available
494
+ if (this.orchestrator) {
495
+ const claudeFlowTools = createClaudeFlowTools(this.logger);
496
+
497
+ for (const tool of claudeFlowTools) {
498
+ // Wrap the handler to inject orchestrator context
499
+ const originalHandler = tool.handler;
500
+ tool.handler = async (input: unknown, context?: MCPContext) => {
501
+ const claudeFlowContext: ClaudeFlowToolContext = {
502
+ ...context,
503
+ orchestrator: this.orchestrator,
504
+ } as ClaudeFlowToolContext;
505
+
506
+ return await originalHandler(input, claudeFlowContext);
507
+ };
508
+
509
+ this.registerTool(tool);
510
+ }
511
+
512
+ this.logger.info('Registered Claude-Flow tools', { count: claudeFlowTools.length });
513
+ } else {
514
+ this.logger.warn('Orchestrator not available - Claude-Flow tools not registered');
515
+ }
516
+ }
517
+
518
+ private errorToMCPError(error: unknown): MCPError {
519
+ if (error instanceof MCPMethodNotFoundError) {
520
+ return {
521
+ code: -32601,
522
+ message: error.message,
523
+ data: error.details,
524
+ };
525
+ }
526
+
527
+ if (error instanceof MCPErrorClass) {
528
+ return {
529
+ code: -32603,
530
+ message: error.message,
531
+ data: error.details,
532
+ };
533
+ }
534
+
535
+ if (error instanceof Error) {
536
+ return {
537
+ code: -32603,
538
+ message: error.message,
539
+ };
540
+ }
541
+
542
+ return {
543
+ code: -32603,
544
+ message: 'Internal error',
545
+ data: error,
546
+ };
547
+ }
548
+ }