@gotza02/smartagent 1.2.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 (75) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +422 -0
  3. package/dist/config/index.d.ts +72 -0
  4. package/dist/config/index.d.ts.map +1 -0
  5. package/dist/config/index.js +329 -0
  6. package/dist/config/index.js.map +1 -0
  7. package/dist/core/agent-manager.d.ts +116 -0
  8. package/dist/core/agent-manager.d.ts.map +1 -0
  9. package/dist/core/agent-manager.js +460 -0
  10. package/dist/core/agent-manager.js.map +1 -0
  11. package/dist/core/context-manager.d.ts +107 -0
  12. package/dist/core/context-manager.d.ts.map +1 -0
  13. package/dist/core/context-manager.js +467 -0
  14. package/dist/core/context-manager.js.map +1 -0
  15. package/dist/core/database.d.ts +82 -0
  16. package/dist/core/database.d.ts.map +1 -0
  17. package/dist/core/database.js +751 -0
  18. package/dist/core/database.js.map +1 -0
  19. package/dist/core/event-emitter.d.ts +110 -0
  20. package/dist/core/event-emitter.d.ts.map +1 -0
  21. package/dist/core/event-emitter.js +240 -0
  22. package/dist/core/event-emitter.js.map +1 -0
  23. package/dist/core/metrics.d.ts +108 -0
  24. package/dist/core/metrics.d.ts.map +1 -0
  25. package/dist/core/metrics.js +281 -0
  26. package/dist/core/metrics.js.map +1 -0
  27. package/dist/core/middleware.d.ts +63 -0
  28. package/dist/core/middleware.d.ts.map +1 -0
  29. package/dist/core/middleware.js +194 -0
  30. package/dist/core/middleware.js.map +1 -0
  31. package/dist/core/plugin-system.d.ts +86 -0
  32. package/dist/core/plugin-system.d.ts.map +1 -0
  33. package/dist/core/plugin-system.js +251 -0
  34. package/dist/core/plugin-system.js.map +1 -0
  35. package/dist/core/task-scheduler.d.ts +130 -0
  36. package/dist/core/task-scheduler.d.ts.map +1 -0
  37. package/dist/core/task-scheduler.js +401 -0
  38. package/dist/core/task-scheduler.js.map +1 -0
  39. package/dist/engines/auto-router.d.ts +76 -0
  40. package/dist/engines/auto-router.d.ts.map +1 -0
  41. package/dist/engines/auto-router.js +445 -0
  42. package/dist/engines/auto-router.js.map +1 -0
  43. package/dist/engines/parallel-execution.d.ts +104 -0
  44. package/dist/engines/parallel-execution.d.ts.map +1 -0
  45. package/dist/engines/parallel-execution.js +591 -0
  46. package/dist/engines/parallel-execution.js.map +1 -0
  47. package/dist/engines/sequential-thinking.d.ts +88 -0
  48. package/dist/engines/sequential-thinking.d.ts.map +1 -0
  49. package/dist/engines/sequential-thinking.js +406 -0
  50. package/dist/engines/sequential-thinking.js.map +1 -0
  51. package/dist/index.d.ts +12 -0
  52. package/dist/index.d.ts.map +1 -0
  53. package/dist/index.js +1101 -0
  54. package/dist/index.js.map +1 -0
  55. package/dist/security/validation.d.ts +87 -0
  56. package/dist/security/validation.d.ts.map +1 -0
  57. package/dist/security/validation.js +465 -0
  58. package/dist/security/validation.js.map +1 -0
  59. package/dist/tools/filesystem.d.ts +90 -0
  60. package/dist/tools/filesystem.d.ts.map +1 -0
  61. package/dist/tools/filesystem.js +292 -0
  62. package/dist/tools/filesystem.js.map +1 -0
  63. package/dist/tools/terminal.d.ts +99 -0
  64. package/dist/tools/terminal.d.ts.map +1 -0
  65. package/dist/tools/terminal.js +363 -0
  66. package/dist/tools/terminal.js.map +1 -0
  67. package/dist/types/index.d.ts +306 -0
  68. package/dist/types/index.d.ts.map +1 -0
  69. package/dist/types/index.js +54 -0
  70. package/dist/types/index.js.map +1 -0
  71. package/dist/utils/logger.d.ts +22 -0
  72. package/dist/utils/logger.d.ts.map +1 -0
  73. package/dist/utils/logger.js +189 -0
  74. package/dist/utils/logger.js.map +1 -0
  75. package/package.json +71 -0
package/dist/index.js ADDED
@@ -0,0 +1,1101 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Swarm MCP Enterprise Server
4
+ * Enterprise-Grade Multi-Agent Swarm System with Sequential Thinking & Auto-Routing
5
+ *
6
+ * @module swarm-mcp-enterprise
7
+ * @version 1.0.0
8
+ * @author Enterprise AI Team
9
+ * @license MIT
10
+ */
11
+ import { randomUUID } from "crypto";
12
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
13
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
14
+ import { CallToolRequestSchema, ListToolsRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
15
+ // Core modules
16
+ import { database } from "./core/database.js";
17
+ import { agentManager } from "./core/agent-manager.js";
18
+ import { contextManager } from "./core/context-manager.js";
19
+ import { eventEmitter } from "./core/event-emitter.js";
20
+ import { taskScheduler } from "./core/task-scheduler.js";
21
+ import { middlewareManager } from "./core/middleware.js";
22
+ import { metricsManager } from "./core/metrics.js";
23
+ import { pluginManager } from "./core/plugin-system.js";
24
+ import { configManager } from "./config/index.js";
25
+ // Engines
26
+ import { SequentialThinkingEngine } from "./engines/sequential-thinking.js";
27
+ import { AutoRouter } from "./engines/auto-router.js";
28
+ import { parallelEngine } from "./engines/parallel-execution.js";
29
+ // Tools
30
+ import { FileSystemTool } from "./tools/filesystem.js";
31
+ import { TerminalTool } from "./tools/terminal.js";
32
+ // Utils
33
+ import { logger, logRequest, logError } from "./utils/logger.js";
34
+ // ============================================
35
+ // Server Configuration
36
+ // ============================================
37
+ const SERVER_NAME = "swarm-mcp-enterprise";
38
+ const SERVER_VERSION = "1.0.0";
39
+ // Initialize configuration
40
+ configManager.initialize();
41
+ // Get configuration
42
+ const config = configManager.getConfig();
43
+ const DEBUG = process.env.SWARM_DEBUG === "true" || config.logLevel === "debug";
44
+ const LOG_LEVEL = process.env.SWARM_LOG_LEVEL || config.logLevel;
45
+ // ============================================
46
+ // Engine Instances
47
+ // ============================================
48
+ const thinkingEngine = new SequentialThinkingEngine(config.sequentialThinking);
49
+ const autoRouter = new AutoRouter(config.autoRouting);
50
+ // Tool instances (available for future use)
51
+ new FileSystemTool();
52
+ new TerminalTool();
53
+ // Initialize metrics
54
+ metricsManager.registerDefaultMetrics();
55
+ // ============================================
56
+ // MCP Tools Definition
57
+ // ============================================
58
+ const TOOLS = [
59
+ // Agent Management
60
+ {
61
+ name: "spawn_agent",
62
+ description: "Spawn a new agent in the swarm system",
63
+ inputSchema: {
64
+ type: "object",
65
+ properties: {
66
+ type: {
67
+ type: "string",
68
+ enum: ["product_manager", "architect", "engineer", "qa", "reviewer"],
69
+ description: "Type of agent to spawn",
70
+ },
71
+ name: {
72
+ type: "string",
73
+ description: "Optional name for the agent",
74
+ },
75
+ mode: {
76
+ type: "string",
77
+ enum: ["plan", "edit", "ralph"],
78
+ description: "Operating mode for the agent",
79
+ },
80
+ capabilities: {
81
+ type: "array",
82
+ items: { type: "string" },
83
+ description: "Additional capabilities for the agent",
84
+ },
85
+ metadata: {
86
+ type: "object",
87
+ description: "Additional metadata",
88
+ },
89
+ },
90
+ required: ["type"],
91
+ },
92
+ },
93
+ {
94
+ name: "spawn_agents_batch",
95
+ description: "Spawn multiple agents simultaneously (max 10)",
96
+ inputSchema: {
97
+ type: "object",
98
+ properties: {
99
+ type: {
100
+ type: "string",
101
+ enum: ["product_manager", "architect", "engineer", "qa", "reviewer"],
102
+ description: "Type of agents to spawn",
103
+ },
104
+ count: {
105
+ type: "number",
106
+ minimum: 1,
107
+ maximum: 10,
108
+ description: "Number of agents to spawn",
109
+ },
110
+ baseName: {
111
+ type: "string",
112
+ description: "Base name for agents (will be suffixed with _1, _2, etc.)",
113
+ },
114
+ mode: {
115
+ type: "string",
116
+ enum: ["plan", "edit", "ralph"],
117
+ description: "Operating mode for all agents",
118
+ },
119
+ metadata: {
120
+ type: "object",
121
+ description: "Metadata to apply to all agents",
122
+ },
123
+ },
124
+ required: ["type", "count"],
125
+ },
126
+ },
127
+ {
128
+ name: "get_agent",
129
+ description: "Get agent details by ID",
130
+ inputSchema: {
131
+ type: "object",
132
+ properties: {
133
+ agentId: {
134
+ type: "string",
135
+ description: "ID of the agent",
136
+ },
137
+ },
138
+ required: ["agentId"],
139
+ },
140
+ },
141
+ {
142
+ name: "list_agents",
143
+ description: "List all agents with optional filtering",
144
+ inputSchema: {
145
+ type: "object",
146
+ properties: {
147
+ type: {
148
+ type: "string",
149
+ enum: ["product_manager", "architect", "engineer", "qa", "reviewer"],
150
+ description: "Filter by agent type",
151
+ },
152
+ status: {
153
+ type: "string",
154
+ enum: ["idle", "busy", "completed", "error", "terminated"],
155
+ description: "Filter by agent status",
156
+ },
157
+ },
158
+ },
159
+ },
160
+ {
161
+ name: "terminate_agent",
162
+ description: "Terminate an agent",
163
+ inputSchema: {
164
+ type: "object",
165
+ properties: {
166
+ agentId: {
167
+ type: "string",
168
+ description: "ID of the agent to terminate",
169
+ },
170
+ },
171
+ required: ["agentId"],
172
+ },
173
+ },
174
+ {
175
+ name: "send_agent_message",
176
+ description: "Send a message from one agent to another",
177
+ inputSchema: {
178
+ type: "object",
179
+ properties: {
180
+ fromAgentId: {
181
+ type: "string",
182
+ description: "ID of the sender agent",
183
+ },
184
+ toAgentId: {
185
+ type: "string",
186
+ description: "ID of the recipient agent",
187
+ },
188
+ messageType: {
189
+ type: "string",
190
+ description: "Type of message",
191
+ },
192
+ content: {
193
+ type: "object",
194
+ description: "Message content",
195
+ },
196
+ },
197
+ required: ["fromAgentId", "toAgentId", "messageType", "content"],
198
+ },
199
+ },
200
+ {
201
+ name: "get_agent_messages",
202
+ description: "Get messages for an agent",
203
+ inputSchema: {
204
+ type: "object",
205
+ properties: {
206
+ agentId: {
207
+ type: "string",
208
+ description: "ID of the agent",
209
+ },
210
+ limit: {
211
+ type: "number",
212
+ description: "Maximum number of messages to return",
213
+ },
214
+ },
215
+ required: ["agentId"],
216
+ },
217
+ },
218
+ // Task Management
219
+ {
220
+ name: "assign_task",
221
+ description: "Assign a task to an agent",
222
+ inputSchema: {
223
+ type: "object",
224
+ properties: {
225
+ agentId: {
226
+ type: "string",
227
+ description: "ID of the agent",
228
+ },
229
+ type: {
230
+ type: "string",
231
+ description: "Type of task",
232
+ },
233
+ description: {
234
+ type: "string",
235
+ description: "Task description",
236
+ },
237
+ context: {
238
+ type: "object",
239
+ description: "Task context data",
240
+ },
241
+ priority: {
242
+ type: "number",
243
+ minimum: 1,
244
+ maximum: 10,
245
+ description: "Task priority (1-10)",
246
+ },
247
+ timeout: {
248
+ type: "number",
249
+ description: "Task timeout in seconds",
250
+ },
251
+ dependencies: {
252
+ type: "array",
253
+ items: { type: "string" },
254
+ description: "IDs of tasks that must complete before this task",
255
+ },
256
+ },
257
+ required: ["agentId", "type", "description"],
258
+ },
259
+ },
260
+ {
261
+ name: "get_task",
262
+ description: "Get task details by ID",
263
+ inputSchema: {
264
+ type: "object",
265
+ properties: {
266
+ taskId: {
267
+ type: "string",
268
+ description: "ID of the task",
269
+ },
270
+ },
271
+ required: ["taskId"],
272
+ },
273
+ },
274
+ {
275
+ name: "complete_task",
276
+ description: "Mark a task as completed",
277
+ inputSchema: {
278
+ type: "object",
279
+ properties: {
280
+ taskId: {
281
+ type: "string",
282
+ description: "ID of the task",
283
+ },
284
+ result: {
285
+ type: "object",
286
+ description: "Task result data",
287
+ },
288
+ },
289
+ required: ["taskId"],
290
+ },
291
+ },
292
+ {
293
+ name: "fail_task",
294
+ description: "Mark a task as failed",
295
+ inputSchema: {
296
+ type: "object",
297
+ properties: {
298
+ taskId: {
299
+ type: "string",
300
+ description: "ID of the task",
301
+ },
302
+ error: {
303
+ type: "string",
304
+ description: "Error message",
305
+ },
306
+ },
307
+ required: ["taskId", "error"],
308
+ },
309
+ },
310
+ {
311
+ name: "cancel_task",
312
+ description: "Cancel a task",
313
+ inputSchema: {
314
+ type: "object",
315
+ properties: {
316
+ taskId: {
317
+ type: "string",
318
+ description: "ID of the task",
319
+ },
320
+ },
321
+ required: ["taskId"],
322
+ },
323
+ },
324
+ {
325
+ name: "list_tasks",
326
+ description: "List all tasks with optional filtering",
327
+ inputSchema: {
328
+ type: "object",
329
+ properties: {
330
+ agentId: {
331
+ type: "string",
332
+ description: "Filter by agent ID",
333
+ },
334
+ status: {
335
+ type: "string",
336
+ enum: ["pending", "in_progress", "completed", "failed", "cancelled"],
337
+ description: "Filter by task status",
338
+ },
339
+ },
340
+ },
341
+ },
342
+ // Sequential Thinking
343
+ {
344
+ name: "thinking_create_chain",
345
+ description: "Create a new thought chain for sequential thinking",
346
+ inputSchema: {
347
+ type: "object",
348
+ properties: {
349
+ agentId: {
350
+ type: "string",
351
+ description: "ID of the agent",
352
+ },
353
+ taskId: {
354
+ type: "string",
355
+ description: "ID of the associated task",
356
+ },
357
+ title: {
358
+ type: "string",
359
+ description: "Title for the thought chain",
360
+ },
361
+ },
362
+ required: ["agentId", "taskId", "title"],
363
+ },
364
+ },
365
+ {
366
+ name: "thinking_add_thought",
367
+ description: "Add a thought to a chain",
368
+ inputSchema: {
369
+ type: "object",
370
+ properties: {
371
+ chainId: {
372
+ type: "string",
373
+ description: "ID of the thought chain",
374
+ },
375
+ content: {
376
+ type: "string",
377
+ description: "Thought content",
378
+ },
379
+ reasoning: {
380
+ type: "string",
381
+ description: "Reasoning behind this thought",
382
+ },
383
+ confidence: {
384
+ type: "number",
385
+ minimum: 0,
386
+ maximum: 1,
387
+ description: "Confidence score (0-1)",
388
+ },
389
+ branchFrom: {
390
+ type: "string",
391
+ description: "Parent thought ID for branching",
392
+ },
393
+ revisionOf: {
394
+ type: "string",
395
+ description: "Thought ID being revised",
396
+ },
397
+ },
398
+ required: ["chainId", "content", "reasoning", "confidence"],
399
+ },
400
+ },
401
+ {
402
+ name: "thinking_get_chain",
403
+ description: "Get a thought chain by ID",
404
+ inputSchema: {
405
+ type: "object",
406
+ properties: {
407
+ chainId: {
408
+ type: "string",
409
+ description: "ID of the thought chain",
410
+ },
411
+ },
412
+ required: ["chainId"],
413
+ },
414
+ },
415
+ {
416
+ name: "thinking_export",
417
+ description: "Export thought chain as JSON or Markdown",
418
+ inputSchema: {
419
+ type: "object",
420
+ properties: {
421
+ chainId: {
422
+ type: "string",
423
+ description: "ID of the thought chain",
424
+ },
425
+ format: {
426
+ type: "string",
427
+ enum: ["json", "markdown"],
428
+ description: "Export format",
429
+ },
430
+ },
431
+ required: ["chainId", "format"],
432
+ },
433
+ },
434
+ // Auto-Routing
435
+ {
436
+ name: "routing_classify_intent",
437
+ description: "Classify intent from input text",
438
+ inputSchema: {
439
+ type: "object",
440
+ properties: {
441
+ input: {
442
+ type: "string",
443
+ description: "Input text to classify",
444
+ },
445
+ },
446
+ required: ["input"],
447
+ },
448
+ },
449
+ {
450
+ name: "routing_route",
451
+ description: "Route a request to the appropriate agent",
452
+ inputSchema: {
453
+ type: "object",
454
+ properties: {
455
+ input: {
456
+ type: "string",
457
+ description: "Input to route",
458
+ },
459
+ preferredAgent: {
460
+ type: "string",
461
+ enum: ["product_manager", "architect", "engineer", "qa", "reviewer"],
462
+ description: "Preferred agent type",
463
+ },
464
+ },
465
+ required: ["input"],
466
+ },
467
+ },
468
+ // Parallel Execution
469
+ {
470
+ name: "parallel_execute",
471
+ description: "Execute multiple tasks in parallel",
472
+ inputSchema: {
473
+ type: "object",
474
+ properties: {
475
+ tasks: {
476
+ type: "array",
477
+ items: {
478
+ type: "object",
479
+ properties: {
480
+ agentType: {
481
+ type: "string",
482
+ enum: ["product_manager", "architect", "engineer", "qa", "reviewer"],
483
+ },
484
+ type: { type: "string" },
485
+ description: { type: "string" },
486
+ context: { type: "object" },
487
+ priority: { type: "number" },
488
+ },
489
+ required: ["agentType", "type", "description"],
490
+ },
491
+ description: "Tasks to execute in parallel",
492
+ },
493
+ maxConcurrency: {
494
+ type: "number",
495
+ minimum: 1,
496
+ maximum: 5,
497
+ description: "Maximum concurrent tasks",
498
+ },
499
+ aggregationStrategy: {
500
+ type: "string",
501
+ enum: ["all", "first", "majority", "custom"],
502
+ description: "Result aggregation strategy",
503
+ },
504
+ },
505
+ required: ["tasks"],
506
+ },
507
+ },
508
+ {
509
+ name: "parallel_get_execution",
510
+ description: "Get parallel execution details",
511
+ inputSchema: {
512
+ type: "object",
513
+ properties: {
514
+ executionId: {
515
+ type: "string",
516
+ description: "ID of the execution",
517
+ },
518
+ },
519
+ required: ["executionId"],
520
+ },
521
+ },
522
+ // Context & Handoff
523
+ {
524
+ name: "context_create",
525
+ description: "Create a new context for an agent",
526
+ inputSchema: {
527
+ type: "object",
528
+ properties: {
529
+ agentId: {
530
+ type: "string",
531
+ description: "ID of the agent",
532
+ },
533
+ maxTokens: {
534
+ type: "number",
535
+ description: "Maximum tokens for context",
536
+ },
537
+ },
538
+ required: ["agentId"],
539
+ },
540
+ },
541
+ {
542
+ name: "context_handoff",
543
+ description: "Perform handoff between agents",
544
+ inputSchema: {
545
+ type: "object",
546
+ properties: {
547
+ fromAgentId: {
548
+ type: "string",
549
+ description: "Source agent ID",
550
+ },
551
+ toAgentId: {
552
+ type: "string",
553
+ description: "Target agent ID",
554
+ },
555
+ taskId: {
556
+ type: "string",
557
+ description: "Associated task ID",
558
+ },
559
+ notes: {
560
+ type: "string",
561
+ description: "Handoff notes",
562
+ },
563
+ },
564
+ required: ["fromAgentId", "toAgentId", "taskId"],
565
+ },
566
+ },
567
+ {
568
+ name: "context_get_handoff_history",
569
+ description: "Get handoff history for an agent",
570
+ inputSchema: {
571
+ type: "object",
572
+ properties: {
573
+ agentId: {
574
+ type: "string",
575
+ description: "ID of the agent",
576
+ },
577
+ },
578
+ required: ["agentId"],
579
+ },
580
+ },
581
+ // System
582
+ {
583
+ name: "system_stats",
584
+ description: "Get system statistics",
585
+ inputSchema: {
586
+ type: "object",
587
+ properties: {},
588
+ },
589
+ },
590
+ {
591
+ name: "system_health",
592
+ description: "Perform system health check",
593
+ inputSchema: {
594
+ type: "object",
595
+ properties: {},
596
+ },
597
+ },
598
+ {
599
+ name: "system_config",
600
+ description: "Get or update system configuration",
601
+ inputSchema: {
602
+ type: "object",
603
+ properties: {
604
+ action: {
605
+ type: "string",
606
+ enum: ["get", "update", "reset"],
607
+ description: "Action to perform",
608
+ },
609
+ config: {
610
+ type: "object",
611
+ description: "Configuration updates (for update action)",
612
+ },
613
+ },
614
+ required: ["action"],
615
+ },
616
+ },
617
+ {
618
+ name: "system_metrics",
619
+ description: "Get system metrics",
620
+ inputSchema: {
621
+ type: "object",
622
+ properties: {
623
+ format: {
624
+ type: "string",
625
+ enum: ["json", "prometheus"],
626
+ description: "Output format",
627
+ },
628
+ },
629
+ },
630
+ },
631
+ // Plugin Management
632
+ {
633
+ name: "plugin_list",
634
+ description: "List all registered plugins",
635
+ inputSchema: {
636
+ type: "object",
637
+ properties: {},
638
+ },
639
+ },
640
+ {
641
+ name: "plugin_register",
642
+ description: "Register a new plugin",
643
+ inputSchema: {
644
+ type: "object",
645
+ properties: {
646
+ pluginPath: {
647
+ type: "string",
648
+ description: "Path to plugin file",
649
+ },
650
+ },
651
+ required: ["pluginPath"],
652
+ },
653
+ },
654
+ {
655
+ name: "plugin_unregister",
656
+ description: "Unregister a plugin",
657
+ inputSchema: {
658
+ type: "object",
659
+ properties: {
660
+ pluginId: {
661
+ type: "string",
662
+ description: "ID of the plugin to unregister",
663
+ },
664
+ },
665
+ required: ["pluginId"],
666
+ },
667
+ },
668
+ ];
669
+ // ============================================
670
+ // Tool Handlers
671
+ // ============================================
672
+ async function handleToolCall(name, args) {
673
+ const requestId = randomUUID();
674
+ const startTime = Date.now();
675
+ // Increment request counter
676
+ metricsManager.increment("swarm_requests_total", 1, { tool: name });
677
+ try {
678
+ let result;
679
+ switch (name) {
680
+ // Agent Management
681
+ case "spawn_agent": {
682
+ const config = args;
683
+ result = await agentManager.spawnAgent(config);
684
+ metricsManager.increment("swarm_agents_total");
685
+ break;
686
+ }
687
+ case "spawn_agents_batch": {
688
+ const { type, count, baseName, mode, metadata } = args;
689
+ result = await agentManager.spawnMultiple(type, count, {
690
+ baseName,
691
+ mode,
692
+ metadata,
693
+ });
694
+ metricsManager.increment("swarm_agents_total", count);
695
+ break;
696
+ }
697
+ case "get_agent": {
698
+ const { agentId } = args;
699
+ result = await agentManager.getAgent(agentId);
700
+ break;
701
+ }
702
+ case "list_agents": {
703
+ const { type, status } = args;
704
+ if (type) {
705
+ result = await agentManager.getAgentsByType(type);
706
+ }
707
+ else if (status) {
708
+ result = await agentManager.getAgentsByStatus(status);
709
+ }
710
+ else {
711
+ result = await agentManager.getAllAgents();
712
+ }
713
+ break;
714
+ }
715
+ case "terminate_agent": {
716
+ const { agentId } = args;
717
+ result = { success: await agentManager.terminateAgent(agentId) };
718
+ break;
719
+ }
720
+ case "send_agent_message": {
721
+ const { fromAgentId, toAgentId, messageType, content } = args;
722
+ result = {
723
+ success: eventEmitter.sendMessage({
724
+ fromAgentId,
725
+ toAgentId,
726
+ type: messageType,
727
+ content,
728
+ }),
729
+ };
730
+ break;
731
+ }
732
+ case "get_agent_messages": {
733
+ const { agentId, limit } = args;
734
+ result = eventEmitter.getMessages(agentId, { limit });
735
+ break;
736
+ }
737
+ // Task Management
738
+ case "assign_task": {
739
+ const { agentId, type, description, context: taskContext, priority, timeout, dependencies } = args;
740
+ // Use task scheduler if dependencies are specified
741
+ if (dependencies && dependencies.length > 0) {
742
+ result = taskScheduler.scheduleTask(agentId, type, description, {
743
+ priority,
744
+ dependencies,
745
+ });
746
+ }
747
+ else {
748
+ result = await agentManager.assignTask(agentId, {
749
+ type,
750
+ description,
751
+ context: taskContext,
752
+ priority,
753
+ timeout,
754
+ });
755
+ }
756
+ metricsManager.increment("swarm_tasks_created_total");
757
+ break;
758
+ }
759
+ case "get_task": {
760
+ const { taskId } = args;
761
+ // Try task scheduler first, then database
762
+ result = taskScheduler.getTask(taskId) || await database.getTask(taskId);
763
+ break;
764
+ }
765
+ case "complete_task": {
766
+ const { taskId, result: taskResult } = args;
767
+ // Try task scheduler first
768
+ const scheduledTask = taskScheduler.getTask(taskId);
769
+ if (scheduledTask) {
770
+ result = taskScheduler.completeTask(taskId, taskResult);
771
+ }
772
+ else {
773
+ result = await agentManager.completeTask(taskId, taskResult);
774
+ }
775
+ metricsManager.increment("swarm_tasks_completed_total");
776
+ break;
777
+ }
778
+ case "fail_task": {
779
+ const { taskId, error } = args;
780
+ // Try task scheduler first
781
+ const scheduledTask = taskScheduler.getTask(taskId);
782
+ if (scheduledTask) {
783
+ result = taskScheduler.failTask(taskId, error);
784
+ }
785
+ else {
786
+ result = await agentManager.failTask(taskId, error);
787
+ }
788
+ metricsManager.increment("swarm_tasks_failed_total");
789
+ break;
790
+ }
791
+ case "cancel_task": {
792
+ const { taskId } = args;
793
+ result = { success: taskScheduler.cancelTask(taskId) };
794
+ break;
795
+ }
796
+ case "list_tasks": {
797
+ const { agentId, status } = args;
798
+ if (agentId) {
799
+ result = taskScheduler.getTasksByAgent(agentId);
800
+ }
801
+ else if (status) {
802
+ result = taskScheduler.getTasksByStatus(status);
803
+ }
804
+ else {
805
+ result = taskScheduler.getAllTasks();
806
+ }
807
+ break;
808
+ }
809
+ // Sequential Thinking
810
+ case "thinking_create_chain": {
811
+ const { agentId, taskId, title } = args;
812
+ result = await thinkingEngine.createChain(agentId, taskId, title);
813
+ break;
814
+ }
815
+ case "thinking_add_thought": {
816
+ const { chainId, content, reasoning, confidence, branchFrom, revisionOf } = args;
817
+ result = await thinkingEngine.addThought(chainId, content, reasoning, confidence, { branchFrom, revisionOf });
818
+ break;
819
+ }
820
+ case "thinking_get_chain": {
821
+ const { chainId } = args;
822
+ result = await thinkingEngine.getChain(chainId);
823
+ break;
824
+ }
825
+ case "thinking_export": {
826
+ const { chainId, format } = args;
827
+ if (format === "json") {
828
+ result = thinkingEngine.exportToJSON(chainId);
829
+ }
830
+ else {
831
+ result = thinkingEngine.exportToMarkdown(chainId);
832
+ }
833
+ break;
834
+ }
835
+ // Auto-Routing
836
+ case "routing_classify_intent": {
837
+ const { input } = args;
838
+ result = autoRouter.classifyIntent(input);
839
+ break;
840
+ }
841
+ case "routing_route": {
842
+ const { input, preferredAgent } = args;
843
+ result = autoRouter.route(input, { preferredAgent });
844
+ break;
845
+ }
846
+ // Parallel Execution
847
+ case "parallel_execute": {
848
+ const { tasks, maxConcurrency, aggregationStrategy } = args;
849
+ result = await parallelEngine.executeParallel(tasks, {
850
+ maxConcurrency,
851
+ aggregationStrategy,
852
+ });
853
+ break;
854
+ }
855
+ case "parallel_get_execution": {
856
+ const { executionId } = args;
857
+ result = parallelEngine.getExecution(executionId);
858
+ break;
859
+ }
860
+ // Context & Handoff
861
+ case "context_create": {
862
+ const { agentId, maxTokens } = args;
863
+ result = await contextManager.createContext(agentId, { maxTokens });
864
+ break;
865
+ }
866
+ case "context_handoff": {
867
+ const { fromAgentId, toAgentId, taskId, notes } = args;
868
+ result = await contextManager.handoff(fromAgentId, toAgentId, taskId, {
869
+ notes,
870
+ });
871
+ break;
872
+ }
873
+ case "context_get_handoff_history": {
874
+ const { agentId } = args;
875
+ result = await contextManager.getHandoffHistory(agentId);
876
+ break;
877
+ }
878
+ // System
879
+ case "system_stats": {
880
+ const [agentStats, dbStats, parallelStats] = await Promise.all([
881
+ agentManager.getAgentStats(),
882
+ database.getSystemStats(),
883
+ Promise.resolve(parallelEngine.getStats()),
884
+ ]);
885
+ const taskStats = taskScheduler.getStats();
886
+ result = {
887
+ agents: agentStats,
888
+ tasks: taskStats,
889
+ database: dbStats,
890
+ parallel: parallelStats,
891
+ plugins: {
892
+ count: pluginManager.getPluginCount(),
893
+ hooks: pluginManager.getAvailableHooks(),
894
+ },
895
+ timestamp: new Date().toISOString(),
896
+ };
897
+ break;
898
+ }
899
+ case "system_health": {
900
+ const healthCheck = await agentManager.performHealthCheck();
901
+ const config = configManager.getConfig();
902
+ result = {
903
+ status: "healthy",
904
+ healthCheck,
905
+ config: {
906
+ maxAgents: config.maxAgents,
907
+ logLevel: config.logLevel,
908
+ healthCheckInterval: config.healthCheckInterval,
909
+ },
910
+ timestamp: new Date().toISOString(),
911
+ };
912
+ break;
913
+ }
914
+ case "system_config": {
915
+ const { action, config: updateConfig } = args;
916
+ switch (action) {
917
+ case "get":
918
+ result = configManager.getConfig();
919
+ break;
920
+ case "update":
921
+ if (updateConfig) {
922
+ configManager.updateConfig(updateConfig);
923
+ }
924
+ result = { success: true, config: configManager.getConfig() };
925
+ break;
926
+ case "reset":
927
+ configManager.reset();
928
+ result = { success: true, config: configManager.getConfig() };
929
+ break;
930
+ }
931
+ break;
932
+ }
933
+ case "system_metrics": {
934
+ const { format } = args;
935
+ if (format === "prometheus") {
936
+ result = metricsManager.exportPrometheus();
937
+ }
938
+ else {
939
+ result = metricsManager.exportJSON();
940
+ }
941
+ break;
942
+ }
943
+ // Plugin Management
944
+ case "plugin_list": {
945
+ result = {
946
+ plugins: pluginManager.getAllPlugins().map((p) => ({
947
+ id: p.manifest.id,
948
+ name: p.manifest.name,
949
+ version: p.manifest.version,
950
+ description: p.manifest.description,
951
+ })),
952
+ hooks: pluginManager.getAvailableHooks(),
953
+ };
954
+ break;
955
+ }
956
+ case "plugin_register": {
957
+ const { pluginPath } = args;
958
+ const success = await pluginManager.loadPluginFromFile(pluginPath);
959
+ result = { success };
960
+ break;
961
+ }
962
+ case "plugin_unregister": {
963
+ const { pluginId } = args;
964
+ const success = await pluginManager.unregisterPlugin(pluginId);
965
+ result = { success };
966
+ break;
967
+ }
968
+ default:
969
+ throw new Error(`Unknown tool: ${name}`);
970
+ }
971
+ const duration = Date.now() - startTime;
972
+ // Record metrics
973
+ metricsManager.observe("swarm_request_duration_seconds", duration / 1000, { tool: name });
974
+ logRequest(requestId, name, args, duration, true);
975
+ return {
976
+ success: true,
977
+ data: result,
978
+ meta: {
979
+ timestamp: new Date().toISOString(),
980
+ requestId,
981
+ duration,
982
+ },
983
+ };
984
+ }
985
+ catch (error) {
986
+ const duration = Date.now() - startTime;
987
+ const errorMessage = error instanceof Error ? error.message : String(error);
988
+ // Record failed request
989
+ metricsManager.increment("swarm_requests_failed_total", 1, { tool: name });
990
+ metricsManager.observe("swarm_request_duration_seconds", duration / 1000, { tool: name });
991
+ logError(error instanceof Error ? error : new Error(errorMessage), {
992
+ category: "tool",
993
+ operation: name,
994
+ });
995
+ logRequest(requestId, name, args, duration, false);
996
+ return {
997
+ success: false,
998
+ error: {
999
+ code: "TOOL_EXECUTION_ERROR",
1000
+ message: errorMessage,
1001
+ details: { tool: name, args },
1002
+ },
1003
+ meta: {
1004
+ timestamp: new Date().toISOString(),
1005
+ requestId,
1006
+ duration,
1007
+ },
1008
+ };
1009
+ }
1010
+ }
1011
+ // ============================================
1012
+ // Main Server
1013
+ // ============================================
1014
+ async function main() {
1015
+ logger.info(`Starting ${SERVER_NAME} v${SERVER_VERSION}`);
1016
+ logger.info(`Node version: ${process.version}`);
1017
+ logger.info(`Debug mode: ${DEBUG}`);
1018
+ logger.info(`Log level: ${LOG_LEVEL}`);
1019
+ // Initialize database
1020
+ await database.initialize();
1021
+ // Register built-in plugins
1022
+ const loggingPlugin = pluginManager.createBuiltinPlugin("logging", "Logging Plugin", {
1023
+ "request:before": (data) => {
1024
+ logger.debug("Request started", data);
1025
+ },
1026
+ "request:after": (data) => {
1027
+ logger.debug("Request completed", data);
1028
+ },
1029
+ });
1030
+ await pluginManager.registerPlugin(loggingPlugin);
1031
+ // Create MCP Server
1032
+ const server = new Server({
1033
+ name: SERVER_NAME,
1034
+ version: SERVER_VERSION,
1035
+ }, {
1036
+ capabilities: {
1037
+ tools: {},
1038
+ },
1039
+ });
1040
+ // Handle list tools
1041
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
1042
+ return { tools: TOOLS };
1043
+ });
1044
+ // Handle tool calls with middleware
1045
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
1046
+ const { name, arguments: args } = request.params;
1047
+ // Execute through middleware
1048
+ const response = await middlewareManager.execute(name, args, async () => handleToolCall(name, args), { tool: name });
1049
+ return {
1050
+ content: [
1051
+ {
1052
+ type: "text",
1053
+ text: JSON.stringify(response, null, 2),
1054
+ },
1055
+ ],
1056
+ isError: !response.success,
1057
+ };
1058
+ });
1059
+ // Start server
1060
+ const transport = new StdioServerTransport();
1061
+ logger.info("Server initialized and ready");
1062
+ logger.info("Waiting for connections...");
1063
+ await server.connect(transport);
1064
+ }
1065
+ // Run main
1066
+ main().catch((error) => {
1067
+ logger.error("Fatal error", {
1068
+ error: error instanceof Error ? error.message : String(error),
1069
+ stack: error instanceof Error ? error.stack : undefined,
1070
+ });
1071
+ process.exit(1);
1072
+ });
1073
+ // Graceful shutdown
1074
+ process.on("SIGINT", async () => {
1075
+ logger.info("Received SIGINT, shutting down gracefully...");
1076
+ agentManager.stopHealthChecks();
1077
+ await database.close();
1078
+ await pluginManager.reset();
1079
+ process.exit(0);
1080
+ });
1081
+ process.on("SIGTERM", async () => {
1082
+ logger.info("Received SIGTERM, shutting down gracefully...");
1083
+ agentManager.stopHealthChecks();
1084
+ await database.close();
1085
+ await pluginManager.reset();
1086
+ process.exit(0);
1087
+ });
1088
+ // Handle uncaught errors
1089
+ process.on("uncaughtException", (error) => {
1090
+ logger.error("Uncaught exception", {
1091
+ error: error.message,
1092
+ stack: error.stack,
1093
+ });
1094
+ process.exit(1);
1095
+ });
1096
+ process.on("unhandledRejection", (reason) => {
1097
+ logger.error("Unhandled rejection", {
1098
+ reason: reason instanceof Error ? reason.message : String(reason),
1099
+ });
1100
+ });
1101
+ //# sourceMappingURL=index.js.map