Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

checkpoint: File edit:

rUvbe300f2e05dd
diff --git a/v3/@claude-flow/memory/src/index.ts b/v3/@claude-flow/memory/src/index.ts
index 940a1f1bad..6929e32c77 100644
--- a/v3/@claude-flow/memory/src/index.ts
+++ b/v3/@claude-flow/memory/src/index.ts
@@ -104,6 +104,14 @@ export {
// ===== Core Components =====
export { AgentDBAdapter, AgentDBAdapterConfig } from './agentdb-adapter.js';
+export { SQLiteBackend, SQLiteBackendConfig } from './sqlite-backend.js';
+export {
+ HybridBackend,
+ HybridBackendConfig,
+ StructuredQuery,
+ SemanticQuery,
+ HybridQuery,
+} from './hybrid-backend.js';
export { HNSWIndex } from './hnsw-index.js';
export { CacheManager, TieredCacheManager } from './cache-manager.js';
export { QueryBuilder, query, QueryTemplates, SortDirection, SortField } from './query-builder.js';
diff --git a/v3/mcp/tools/agent-tools.ts b/v3/mcp/tools/agent-tools.ts
new file mode 100644
index 0000000000..ef1b615682
--- /dev/null
+++ b/v3/mcp/tools/agent-tools.ts
@@ -0,0 +1,463 @@
+/**
+ * V3 MCP Agent Tools
+ *
+ * MCP tools for agent lifecycle operations:
+ * - agent/spawn - Spawn a new agent
+ * - agent/list - List all agents
+ * - agent/terminate - Terminate an agent
+ * - agent/status - Get agent status
+ *
+ * Implements ADR-005: MCP-First API Design
+ */
+
+import { z } from 'zod';
+import { MCPTool, ToolContext } from '../types.js';
+
+// ============================================================================
+// Input Schemas
+// ============================================================================
+
+const spawnAgentSchema = z.object({
+ agentType: z.string().describe('Type of agent to spawn (e.g., coder, reviewer, tester)'),
+ id: z.string().optional().describe('Optional agent ID (auto-generated if not provided)'),
+ config: z.record(z.unknown()).optional().describe('Agent-specific configuration'),
+ priority: z.enum(['low', 'normal', 'high', 'critical']).default('normal'),
+ metadata: z.record(z.unknown()).optional().describe('Additional metadata'),
+});
+
+const listAgentsSchema = z.object({
+ status: z.enum(['active', 'idle', 'terminated', 'all']).optional().describe('Filter by status'),
+ agentType: z.string().optional().describe('Filter by agent type'),
+ limit: z.number().int().positive().max(1000).optional().describe('Maximum number of agents to return'),
+ offset: z.number().int().nonnegative().optional().describe('Offset for pagination'),
+});
+
+const terminateAgentSchema = z.object({
+ agentId: z.string().describe('ID of the agent to terminate'),
+ graceful: z.boolean().default(true).describe('Whether to gracefully shutdown the agent'),
+ reason: z.string().optional().describe('Reason for termination'),
+});
+
+const agentStatusSchema = z.object({
+ agentId: z.string().describe('ID of the agent to get status for'),
+ includeMetrics: z.boolean().default(false).describe('Include performance metrics'),
+ includeHistory: z.boolean().default(false).describe('Include execution history'),
+});
+
+// ============================================================================
+// Type Definitions
+// ============================================================================
+
+interface AgentInfo {
+ id: string;
+ agentType: string;
+ status: 'active' | 'idle' | 'terminated';
+ createdAt: string;
+ lastActivityAt?: string;
+ config?: Record<string, unknown>;
+ metadata?: Record<string, unknown>;
+}
+
+interface AgentStatus extends AgentInfo {
+ metrics?: {
+ tasksCompleted: number;
+ tasksInProgress: number;
+ tasksFailed: number;
+ averageExecutionTime: number;
+ uptime: number;
+ };
+ history?: Array<{
+ timestamp: string;
+ event: string;
+ details?: unknown;
+ }>;
+}
+
+interface SpawnAgentResult {
+ agentId: string;
+ agentType: string;
+ status: string;
+ createdAt: string;
+}
+
+interface ListAgentsResult {
+ agents: AgentInfo[];
+ total: number;
+ limit?: number;
+ offset?: number;
+}
+
+interface TerminateAgentResult {
+ agentId: string;
+ terminated: boolean;
+ terminatedAt: string;
+ reason?: string;
+}
+
+// ============================================================================
+// Tool Handlers
+// ============================================================================
+
+/**
+ * Spawn a new agent
+ */
+async function handleSpawnAgent(
+ input: z.infer<typeof spawnAgentSchema>,
+ context?: ToolContext
+): Promise<SpawnAgentResult> {
+ // TODO: Integrate with actual agent manager when available
+ // For now, return stub response
+
+ const agentId = input.id || `agent-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
+ const createdAt = new Date().toISOString();
+
+ // Stub implementation - will be replaced with actual agent manager integration
+ const result: SpawnAgentResult = {
+ agentId,
+ agentType: input.agentType,
+ status: 'active',
+ createdAt,
+ };
+
+ // TODO: Call actual agent manager
+ // const agentManager = context?.agentManager as AgentManager;
+ // if (agentManager) {
+ // await agentManager.spawnAgent({
+ // id: agentId,
+ // type: input.agentType,
+ // config: input.config,
+ // priority: input.priority,
+ // metadata: input.metadata,
+ // });
+ // }
+
+ return result;
+}
+
+/**
+ * List all agents
+ */
+async function handleListAgents(
+ input: z.infer<typeof listAgentsSchema>,
+ context?: ToolContext
+): Promise<ListAgentsResult> {
+ // TODO: Integrate with actual agent manager when available
+ // For now, return stub response
+
+ // Stub implementation - will be replaced with actual agent manager integration
+ const agents: AgentInfo[] = [
+ {
+ id: 'agent-example-1',
+ agentType: 'coder',
+ status: 'active',
+ createdAt: new Date(Date.now() - 3600000).toISOString(),
+ lastActivityAt: new Date().toISOString(),
+ },
+ {
+ id: 'agent-example-2',
+ agentType: 'reviewer',
+ status: 'idle',
+ createdAt: new Date(Date.now() - 7200000).toISOString(),
+ lastActivityAt: new Date(Date.now() - 600000).toISOString(),
+ },
+ ];
+
+ // Apply filters
+ let filtered = agents;
+ if (input.status && input.status !== 'all') {
+ filtered = filtered.filter(a => a.status === input.status);
+ }
+ if (input.agentType) {
+ filtered = filtered.filter(a => a.agentType === input.agentType);
+ }
+
+ // Apply pagination
+ const offset = input.offset || 0;
+ const limit = input.limit || filtered.length;
+ const paginated = filtered.slice(offset, offset + limit);
+
+ // TODO: Call actual agent manager
+ // const agentManager = context?.agentManager as AgentManager;
+ // if (agentManager) {
+ // const agents = await agentManager.listAgents({
+ // status: input.status,
+ // agentType: input.agentType,
+ // limit: input.limit,
+ // offset: input.offset,
+ // });
+ // return agents;
+ // }
+
+ return {
+ agents: paginated,
+ total: filtered.length,
+ limit: input.limit,
+ offset: input.offset,
+ };
+}
+
+/**
+ * Terminate an agent
+ */
+async function handleTerminateAgent(
+ input: z.infer<typeof terminateAgentSchema>,
+ context?: ToolContext
+): Promise<TerminateAgentResult> {
+ // TODO: Integrate with actual agent manager when available
+ // For now, return stub response
+
+ const terminatedAt = new Date().toISOString();
+
+ // Stub implementation - will be replaced with actual agent manager integration
+ const result: TerminateAgentResult = {
+ agentId: input.agentId,
+ terminated: true,
+ terminatedAt,
+ reason: input.reason,
+ };
+
+ // TODO: Call actual agent manager
+ // const agentManager = context?.agentManager as AgentManager;
+ // if (agentManager) {
+ // await agentManager.terminateAgent(input.agentId, {
+ // graceful: input.graceful,
+ // reason: input.reason,
+ // });
+ // }
+
+ return result;
+}
+
+/**
+ * Get agent status
+ */
+async function handleAgentStatus(
+ input: z.infer<typeof agentStatusSchema>,
+ context?: ToolContext
+): Promise<AgentStatus> {
+ // TODO: Integrate with actual agent manager when available
+ // For now, return stub response
+
+ // Stub implementation - will be replaced with actual agent manager integration
+ const status: AgentStatus = {
+ id: input.agentId,
+ agentType: 'coder',
+ status: 'active',
+ createdAt: new Date(Date.now() - 3600000).toISOString(),
+ lastActivityAt: new Date().toISOString(),
+ config: { maxConcurrentTasks: 5 },
+ metadata: { version: '3.0.0' },
+ };
+
+ if (input.includeMetrics) {
+ status.metrics = {
+ tasksCompleted: 42,
+ tasksInProgress: 2,
+ tasksFailed: 3,
+ averageExecutionTime: 1234.56,
+ uptime: 3600000,
+ };
+ }
+
+ if (input.includeHistory) {
+ status.history = [
+ {
+ timestamp: new Date(Date.now() - 300000).toISOString(),
+ event: 'task_completed',
+ details: { taskId: 'task-123' },
+ },
+ {
+ timestamp: new Date(Date.now() - 600000).toISOString(),
+ event: 'task_started',
+ details: { taskId: 'task-123' },
+ },
+ ];
+ }
+
+ // TODO: Call actual agent manager
+ // const agentManager = context?.agentManager as AgentManager;
+ // if (agentManager) {
+ // const status = await agentManager.getAgentStatus(input.agentId, {
+ // includeMetrics: input.includeMetrics,
+ // includeHistory: input.includeHistory,
+ // });
+ // return status;
+ // }
+
+ return status;
+}
+
+// ============================================================================
+// Tool Definitions
+// ============================================================================
+
+/**
+ * agent/spawn tool
+ */
+export const spawnAgentTool: MCPTool = {
+ name: 'agent/spawn',
+ description: 'Spawn a new agent with specified type and configuration',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ agentType: {
+ type: 'string',
+ description: 'Type of agent to spawn (e.g., coder, reviewer, tester, researcher, planner)',
+ },
+ id: {
+ type: 'string',
+ description: 'Optional agent ID (auto-generated if not provided)',
+ },
+ config: {
+ type: 'object',
+ description: 'Agent-specific configuration',
+ additionalProperties: true,
+ },
+ priority: {
+ type: 'string',
+ enum: ['low', 'normal', 'high', 'critical'],
+ description: 'Agent priority level',
+ default: 'normal',
+ },
+ metadata: {
+ type: 'object',
+ description: 'Additional metadata',
+ additionalProperties: true,
+ },
+ },
+ required: ['agentType'],
+ },
+ handler: async (input, context) => {
+ const validated = spawnAgentSchema.parse(input);
+ return handleSpawnAgent(validated, context);
+ },
+ category: 'agent',
+ tags: ['agent', 'lifecycle', 'spawn'],
+ version: '1.0.0',
+};
+
+/**
+ * agent/list tool
+ */
+export const listAgentsTool: MCPTool = {
+ name: 'agent/list',
+ description: 'List all agents with optional filtering and pagination',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ status: {
+ type: 'string',
+ enum: ['active', 'idle', 'terminated', 'all'],
+ description: 'Filter by agent status',
+ },
+ agentType: {
+ type: 'string',
+ description: 'Filter by agent type',
+ },
+ limit: {
+ type: 'number',
+ description: 'Maximum number of agents to return',
+ minimum: 1,
+ maximum: 1000,
+ },
+ offset: {
+ type: 'number',
+ description: 'Offset for pagination',
+ minimum: 0,
+ },
+ },
+ },
+ handler: async (input, context) => {
+ const validated = listAgentsSchema.parse(input);
+ return handleListAgents(validated, context);
+ },
+ category: 'agent',
+ tags: ['agent', 'list', 'query'],
+ version: '1.0.0',
+ cacheable: true,
+ cacheTTL: 2000,
+};
+
+/**
+ * agent/terminate tool
+ */
+export const terminateAgentTool: MCPTool = {
+ name: 'agent/terminate',
+ description: 'Terminate a running agent gracefully or forcefully',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ agentId: {
+ type: 'string',
+ description: 'ID of the agent to terminate',
+ },
+ graceful: {
+ type: 'boolean',
+ description: 'Whether to gracefully shutdown the agent',
+ default: true,
+ },
+ reason: {
+ type: 'string',
+ description: 'Reason for termination',
+ },
+ },
+ required: ['agentId'],
+ },
+ handler: async (input, context) => {
+ const validated = terminateAgentSchema.parse(input);
+ return handleTerminateAgent(validated, context);
+ },
+ category: 'agent',
+ tags: ['agent', 'lifecycle', 'terminate'],
+ version: '1.0.0',
+};
+
+/**
+ * agent/status tool
+ */
+export const agentStatusTool: MCPTool = {
+ name: 'agent/status',
+ description: 'Get detailed status information for a specific agent',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ agentId: {
+ type: 'string',
+ description: 'ID of the agent to get status for',
+ },
+ includeMetrics: {
+ type: 'boolean',
+ description: 'Include performance metrics',
+ default: false,
+ },
+ includeHistory: {
+ type: 'boolean',
+ description: 'Include execution history',
+ default: false,
+ },
+ },
+ required: ['agentId'],
+ },
+ handler: async (input, context) => {
+ const validated = agentStatusSchema.parse(input);
+ return handleAgentStatus(validated, context);
+ },
+ category: 'agent',
+ tags: ['agent', 'status', 'metrics'],
+ version: '1.0.0',
+ cacheable: true,
+ cacheTTL: 1000,
+};
+
+// ============================================================================
+// Exports
+// ============================================================================
+
+export const agentTools: MCPTool[] = [
+ spawnAgentTool,
+ listAgentsTool,
+ terminateAgentTool,
+ agentStatusTool,
+];
+
+export default agentTools;
diff --git a/v3/mcp/tools/memory-tools.ts b/v3/mcp/tools/memory-tools.ts
new file mode 100644
index 0000000000..dbe211af98
--- /dev/null
+++ b/v3/mcp/tools/memory-tools.ts
@@ -0,0 +1,575 @@
+/**
+ * V3 MCP Memory Tools
+ *
+ * MCP tools for memory operations:
+ * - memory/store - Store memory entry
+ * - memory/search - Search memories (semantic + keyword)
+ * - memory/list - List memory entries
+ *
+ * Implements ADR-005: MCP-First API Design
+ * Implements ADR-006: Unified Memory Service (AgentDB integration)
+ */
+
+import { z } from 'zod';
+import { MCPTool, ToolContext } from '../types.js';
+
+// ============================================================================
+// Input Schemas
+// ============================================================================
+
+const storeMemorySchema = z.object({
+ content: z.string().min(1).describe('Memory content to store'),
+ type: z.enum(['episodic', 'semantic', 'procedural', 'working'])
+ .default('episodic')
+ .describe('Type of memory'),
+ category: z.string().optional().describe('Memory category (e.g., code, documentation, conversation)'),
+ tags: z.array(z.string()).optional().describe('Tags for categorization'),
+ metadata: z.record(z.unknown()).optional().describe('Additional metadata'),
+ importance: z.number().min(0).max(1).optional()
+ .describe('Importance score (0-1)'),
+ ttl: z.number().int().positive().optional()
+ .describe('Time-to-live in milliseconds (optional, for temporary memories)'),
+});
+
+const searchMemorySchema = z.object({
+ query: z.string().min(1).describe('Search query (semantic or keyword)'),
+ searchType: z.enum(['semantic', 'keyword', 'hybrid'])
+ .default('hybrid')
+ .describe('Type of search to perform'),
+ type: z.enum(['episodic', 'semantic', 'procedural', 'working', 'all'])
+ .default('all')
+ .describe('Filter by memory type'),
+ category: z.string().optional().describe('Filter by category'),
+ tags: z.array(z.string()).optional().describe('Filter by tags (AND logic)'),
+ limit: z.number().int().positive().max(1000).default(10)
+ .describe('Maximum number of results'),
+ minRelevance: z.number().min(0).max(1).optional()
+ .describe('Minimum relevance score (0-1)'),
+ includeMetadata: z.boolean().default(true)
+ .describe('Include metadata in results'),
+});
+
+const listMemorySchema = z.object({
+ type: z.enum(['episodic', 'semantic', 'procedural', 'working', 'all'])
+ .default('all')
+ .describe('Filter by memory type'),
+ category: z.string().optional().describe('Filter by category'),
+ tags: z.array(z.string()).optional().describe('Filter by tags'),
+ sortBy: z.enum(['created', 'accessed', 'importance', 'relevance'])
+ .default('created')
+ .describe('Sort order'),
+ sortOrder: z.enum(['asc', 'desc']).default('desc')
+ .describe('Sort direction'),
+ limit: z.number().int().positive().max(1000).default(50)
+ .describe('Maximum number of results'),
+ offset: z.number().int().nonnegative().default(0)
+ .describe('Offset for pagination'),
+ includeMetadata: z.boolean().default(true)
+ .describe('Include metadata in results'),
+});
+
+// ============================================================================
+// Type Definitions
+// ============================================================================
+
+interface Memory {
+ id: string;
+ content: string;
+ type: 'episodic' | 'semantic' | 'procedural' | 'working';
+ category?: string;
+ tags?: string[];
+ importance?: number;
+ createdAt: string;
+ accessedAt?: string;
+ accessCount?: number;
+ metadata?: Record<string, unknown>;
+}
+
+interface SearchResult extends Memory {
+ relevance: number;
+ highlights?: string[];
+}
+
+interface StoreMemoryResult {
+ id: string;
+ stored: boolean;
+ storedAt: string;
+}
+
+interface SearchMemoryResult {
+ results: SearchResult[];
+ total: number;
+ query: string;
+ searchType: string;
+ executionTime: number;
+}
+
+interface ListMemoryResult {
+ memories: Memory[];
+ total: number;
+ limit: number;
+ offset: number;
+}
+
+// ============================================================================
+// Tool Handlers
+// ============================================================================
+
+/**
+ * Store memory entry
+ */
+async function handleStoreMemory(
+ input: z.infer<typeof storeMemorySchema>,
+ context?: ToolContext
+): Promise<StoreMemoryResult> {
+ // TODO: Integrate with actual memory service/AgentDB when available
+ // For now, return stub response
+
+ const id = `mem-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
+ const storedAt = new Date().toISOString();
+
+ // Stub implementation - will be replaced with AgentDB integration
+ const result: StoreMemoryResult = {
+ id,
+ stored: true,
+ storedAt,
+ };
+
+ // TODO: Call actual memory service
+ // const memoryService = context?.resourceManager?.memoryService;
+ // if (memoryService) {
+ // await memoryService.store({
+ // content: input.content,
+ // type: input.type,
+ // category: input.category,
+ // tags: input.tags,
+ // metadata: input.metadata,
+ // importance: input.importance,
+ // ttl: input.ttl,
+ // });
+ // }
+
+ return result;
+}
+
+/**
+ * Search memories (semantic + keyword)
+ */
+async function handleSearchMemory(
+ input: z.infer<typeof searchMemorySchema>,
+ context?: ToolContext
+): Promise<SearchMemoryResult> {
+ // TODO: Integrate with actual memory service/AgentDB when available
+ // For now, return stub response
+
+ const startTime = performance.now();
+
+ // Stub implementation - will be replaced with AgentDB integration
+ const results: SearchResult[] = [
+ {
+ id: 'mem-example-1',
+ content: 'Example memory content matching the query',
+ type: 'episodic',
+ category: 'code',
+ tags: ['implementation', 'typescript'],
+ importance: 0.8,
+ createdAt: new Date(Date.now() - 3600000).toISOString(),
+ accessedAt: new Date().toISOString(),
+ accessCount: 5,
+ relevance: 0.92,
+ highlights: ['matching the query'],
+ },
+ {
+ id: 'mem-example-2',
+ content: 'Another relevant memory entry',
+ type: 'semantic',
+ category: 'documentation',
+ tags: ['api', 'reference'],
+ importance: 0.6,
+ createdAt: new Date(Date.now() - 7200000).toISOString(),
+ accessedAt: new Date(Date.now() - 600000).toISOString(),
+ accessCount: 12,
+ relevance: 0.85,
+ highlights: ['relevant memory'],
+ },
+ ];
+
+ // Apply filters
+ let filtered = results;
+ if (input.type !== 'all') {
+ filtered = filtered.filter(m => m.type === input.type);
+ }
+ if (input.category) {
+ filtered = filtered.filter(m => m.category === input.category);
+ }
+ if (input.tags && input.tags.length > 0) {
+ filtered = filtered.filter(m =>
+ input.tags!.every(tag => m.tags?.includes(tag))
+ );
+ }
+ if (input.minRelevance !== undefined) {
+ filtered = filtered.filter(m => m.relevance >= input.minRelevance!);
+ }
+
+ // Apply limit
+ const limited = filtered.slice(0, input.limit);
+
+ // Remove metadata if not requested
+ if (!input.includeMetadata) {
+ limited.forEach(m => delete m.metadata);
+ }
+
+ const executionTime = performance.now() - startTime;
+
+ // TODO: Call actual memory service with AgentDB
+ // const memoryService = context?.resourceManager?.memoryService;
+ // if (memoryService) {
+ // const results = await memoryService.search({
+ // query: input.query,
+ // searchType: input.searchType,
+ // type: input.type,
+ // category: input.category,
+ // tags: input.tags,
+ // limit: input.limit,
+ // minRelevance: input.minRelevance,
+ // });
+ // return results;
+ // }
+
+ return {
+ results: limited,
+ total: filtered.length,
+ query: input.query,
+ searchType: input.searchType,
+ executionTime,
+ };
+}
+
+/**
+ * List memory entries
+ */
+async function handleListMemory(
+ input: z.infer<typeof listMemorySchema>,
+ context?: ToolContext
+): Promise<ListMemoryResult> {
+ // TODO: Integrate with actual memory service/AgentDB when available
+ // For now, return stub response
+
+ // Stub implementation - will be replaced with AgentDB integration
+ const memories: Memory[] = [
+ {
+ id: 'mem-example-1',
+ content: 'Example memory content 1',
+ type: 'episodic',
+ category: 'code',
+ tags: ['implementation', 'typescript'],
+ importance: 0.8,
+ createdAt: new Date(Date.now() - 3600000).toISOString(),
+ accessedAt: new Date().toISOString(),
+ accessCount: 5,
+ },
+ {
+ id: 'mem-example-2',
+ content: 'Example memory content 2',
+ type: 'semantic',
+ category: 'documentation',
+ tags: ['api', 'reference'],
+ importance: 0.6,
+ createdAt: new Date(Date.now() - 7200000).toISOString(),
+ accessedAt: new Date(Date.now() - 600000).toISOString(),
+ accessCount: 12,
+ },
+ {
+ id: 'mem-example-3',
+ content: 'Example memory content 3',
+ type: 'procedural',
+ category: 'workflow',
+ tags: ['deployment', 'cicd'],
+ importance: 0.9,
+ createdAt: new Date(Date.now() - 10800000).toISOString(),
+ accessedAt: new Date(Date.now() - 300000).toISOString(),
+ accessCount: 8,
+ },
+ ];
+
+ // Apply filters
+ let filtered = memories;
+ if (input.type !== 'all') {
+ filtered = filtered.filter(m => m.type === input.type);
+ }
+ if (input.category) {
+ filtered = filtered.filter(m => m.category === input.category);
+ }
+ if (input.tags && input.tags.length > 0) {
+ filtered = filtered.filter(m =>
+ input.tags!.every(tag => m.tags?.includes(tag))
+ );
+ }
+
+ // Apply sorting
+ const sorted = [...filtered].sort((a, b) => {
+ let aVal: number | string;
+ let bVal: number | string;
+
+ switch (input.sortBy) {
+ case 'created':
+ aVal = new Date(a.createdAt).getTime();
+ bVal = new Date(b.createdAt).getTime();
+ break;
+ case 'accessed':
+ aVal = a.accessedAt ? new Date(a.accessedAt).getTime() : 0;
+ bVal = b.accessedAt ? new Date(b.accessedAt).getTime() : 0;
+ break;
+ case 'importance':
+ aVal = a.importance || 0;
+ bVal = b.importance || 0;
+ break;
+ default:
+ aVal = 0;
+ bVal = 0;
+ }
+
+ if (input.sortOrder === 'asc') {
+ return aVal < bVal ? -1 : aVal > bVal ? 1 : 0;
+ } else {
+ return aVal > bVal ? -1 : aVal < bVal ? 1 : 0;
+ }
+ });
+
+ // Apply pagination
+ const paginated = sorted.slice(input.offset, input.offset + input.limit);
+
+ // Remove metadata if not requested
+ if (!input.includeMetadata) {
+ paginated.forEach(m => delete m.metadata);
+ }
+
+ // TODO: Call actual memory service with AgentDB
+ // const memoryService = context?.resourceManager?.memoryService;
+ // if (memoryService) {
+ // const memories = await memoryService.list({
+ // type: input.type,
+ // category: input.category,
+ // tags: input.tags,
+ // sortBy: input.sortBy,
+ // sortOrder: input.sortOrder,
+ // limit: input.limit,
+ // offset: input.offset,
+ // });
+ // return memories;
+ // }
+
+ return {
+ memories: paginated,
+ total: filtered.length,
+ limit: input.limit,
+ offset: input.offset,
+ };
+}
+
+// ============================================================================
+// Tool Definitions
+// ============================================================================
+
+/**
+ * memory/store tool
+ */
+export const storeMemoryTool: MCPTool = {
+ name: 'memory/store',
+ description: 'Store a memory entry with specified type, category, and metadata',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ content: {
+ type: 'string',
+ description: 'Memory content to store',
+ minLength: 1,
+ },
+ type: {
+ type: 'string',
+ enum: ['episodic', 'semantic', 'procedural', 'working'],
+ description: 'Type of memory',
+ default: 'episodic',
+ },
+ category: {
+ type: 'string',
+ description: 'Memory category (e.g., code, documentation, conversation)',
+ },
+ tags: {
+ type: 'array',
+ items: { type: 'string' },
+ description: 'Tags for categorization',
+ },
+ metadata: {
+ type: 'object',
+ description: 'Additional metadata',
+ additionalProperties: true,
+ },
+ importance: {
+ type: 'number',
+ description: 'Importance score (0-1)',
+ minimum: 0,
+ maximum: 1,
+ },
+ ttl: {
+ type: 'number',
+ description: 'Time-to-live in milliseconds',
+ minimum: 1,
+ },
+ },
+ required: ['content'],
+ },
+ handler: async (input, context) => {
+ const validated = storeMemorySchema.parse(input);
+ return handleStoreMemory(validated, context);
+ },
+ category: 'memory',
+ tags: ['memory', 'storage', 'agentdb'],
+ version: '1.0.0',
+};
+
+/**
+ * memory/search tool
+ */
+export const searchMemoryTool: MCPTool = {
+ name: 'memory/search',
+ description: 'Search memories using semantic and keyword search with filtering',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ query: {
+ type: 'string',
+ description: 'Search query (semantic or keyword)',
+ minLength: 1,
+ },
+ searchType: {
+ type: 'string',
+ enum: ['semantic', 'keyword', 'hybrid'],
+ description: 'Type of search to perform',
+ default: 'hybrid',
+ },
+ type: {
+ type: 'string',
+ enum: ['episodic', 'semantic', 'procedural', 'working', 'all'],
+ description: 'Filter by memory type',
+ default: 'all',
+ },
+ category: {
+ type: 'string',
+ description: 'Filter by category',
+ },
+ tags: {
+ type: 'array',
+ items: { type: 'string' },
+ description: 'Filter by tags (AND logic)',
+ },
+ limit: {
+ type: 'number',
+ description: 'Maximum number of results',
+ minimum: 1,
+ maximum: 1000,
+ default: 10,
+ },
+ minRelevance: {
+ type: 'number',
+ description: 'Minimum relevance score (0-1)',
+ minimum: 0,
+ maximum: 1,
+ },
+ includeMetadata: {
+ type: 'boolean',
+ description: 'Include metadata in results',
+ default: true,
+ },
+ },
+ required: ['query'],
+ },
+ handler: async (input, context) => {
+ const validated = searchMemorySchema.parse(input);
+ return handleSearchMemory(validated, context);
+ },
+ category: 'memory',
+ tags: ['memory', 'search', 'agentdb', 'semantic'],
+ version: '1.0.0',
+ cacheable: true,
+ cacheTTL: 5000,
+};
+
+/**
+ * memory/list tool
+ */
+export const listMemoryTool: MCPTool = {
+ name: 'memory/list',
+ description: 'List memory entries with filtering, sorting, and pagination',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ type: {
+ type: 'string',
+ enum: ['episodic', 'semantic', 'procedural', 'working', 'all'],
+ description: 'Filter by memory type',
+ default: 'all',
+ },
+ category: {
+ type: 'string',
+ description: 'Filter by category',
+ },
+ tags: {
+ type: 'array',
+ items: { type: 'string' },
+ description: 'Filter by tags',
+ },
+ sortBy: {
+ type: 'string',
+ enum: ['created', 'accessed', 'importance', 'relevance'],
+ description: 'Sort order',
+ default: 'created',
+ },
+ sortOrder: {
+ type: 'string',
+ enum: ['asc', 'desc'],
+ description: 'Sort direction',
+ default: 'desc',
+ },
+ limit: {
+ type: 'number',
+ description: 'Maximum number of results',
+ minimum: 1,
+ maximum: 1000,
+ default: 50,
+ },
+ offset: {
+ type: 'number',
+ description: 'Offset for pagination',
+ minimum: 0,
+ default: 0,
+ },
+ includeMetadata: {
+ type: 'boolean',
+ description: 'Include metadata in results',
+ default: true,
+ },
+ },
+ },
+ handler: async (input, context) => {
+ const validated = listMemorySchema.parse(input);
+ return handleListMemory(validated, context);
+ },
+ category: 'memory',
+ tags: ['memory', 'list', 'agentdb'],
+ version: '1.0.0',
+ cacheable: true,
+ cacheTTL: 3000,
+};
+
+// ============================================================================
+// Exports
+// ============================================================================
+
+export const memoryTools: MCPTool[] = [
+ storeMemoryTool,
+ searchMemoryTool,
+ listMemoryTool,
+];
+
+export default memoryTools;
diff --git a/v3/mcp/tools/swarm-tools.ts b/v3/mcp/tools/swarm-tools.ts
new file mode 100644
index 0000000000..b1f6174a43
--- /dev/null
+++ b/v3/mcp/tools/swarm-tools.ts
@@ -0,0 +1,489 @@
+/**
+ * V3 MCP Swarm Tools
+ *
+ * MCP tools for swarm coordination operations:
+ * - swarm/init - Initialize swarm coordination
+ * - swarm/status - Get swarm status
+ * - swarm/scale - Scale swarm agents
+ *
+ * Implements ADR-005: MCP-First API Design
+ */
+
+import { z } from 'zod';
+import { MCPTool, ToolContext } from '../types.js';
+
+// ============================================================================
+// Input Schemas
+// ============================================================================
+
+const initSwarmSchema = z.object({
+ topology: z.enum(['hierarchical', 'mesh', 'adaptive', 'collective', 'hierarchical-mesh'])
+ .default('hierarchical-mesh')
+ .describe('Swarm coordination topology'),
+ maxAgents: z.number().int().positive().max(1000).default(15)
+ .describe('Maximum number of agents in the swarm'),
+ config: z.object({
+ communicationProtocol: z.enum(['direct', 'message-bus', 'pubsub']).optional(),
+ consensusMechanism: z.enum(['majority', 'unanimous', 'weighted', 'none']).optional(),
+ failureHandling: z.enum(['retry', 'failover', 'ignore']).optional(),
+ loadBalancing: z.boolean().optional(),
+ autoScaling: z.boolean().optional(),
+ }).optional().describe('Swarm configuration'),
+ metadata: z.record(z.unknown()).optional().describe('Additional metadata'),
+});
+
+const swarmStatusSchema = z.object({
+ includeAgents: z.boolean().default(true).describe('Include individual agent information'),
+ includeMetrics: z.boolean().default(false).describe('Include performance metrics'),
+ includeTopology: z.boolean().default(false).describe('Include topology graph'),
+});
+
+const scaleSwarmSchema = z.object({
+ targetAgents: z.number().int().positive().max(1000)
+ .describe('Target number of agents'),
+ scaleStrategy: z.enum(['gradual', 'immediate', 'adaptive']).default('gradual')
+ .describe('Scaling strategy'),
+ agentTypes: z.array(z.string()).optional()
+ .describe('Specific agent types to scale (if not provided, will scale proportionally)'),
+ reason: z.string().optional().describe('Reason for scaling'),
+});
+
+// ============================================================================
+// Type Definitions
+// ============================================================================
+
+interface SwarmConfig {
+ topology: 'hierarchical' | 'mesh' | 'adaptive' | 'collective' | 'hierarchical-mesh';
+ maxAgents: number;
+ currentAgents: number;
+ communicationProtocol?: string;
+ consensusMechanism?: string;
+ failureHandling?: string;
+ loadBalancing?: boolean;
+ autoScaling?: boolean;
+}
+
+interface SwarmAgent {
+ id: string;
+ type: string;
+ status: 'active' | 'idle' | 'busy' | 'error';
+ role?: 'coordinator' | 'worker' | 'specialist';
+ connections?: string[];
+}
+
+interface SwarmMetrics {
+ totalTasks: number;
+ completedTasks: number;
+ failedTasks: number;
+ inProgressTasks: number;
+ averageTaskDuration: number;
+ throughput: number;
+ efficiency: number;
+ uptime: number;
+}
+
+interface SwarmTopology {
+ nodes: Array<{ id: string; type: string; role?: string }>;
+ edges: Array<{ from: string; to: string; weight?: number }>;
+ depth?: number;
+ fanout?: number;
+}
+
+interface InitSwarmResult {
+ swarmId: string;
+ topology: string;
+ initializedAt: string;
+ config: SwarmConfig;
+}
+
+interface SwarmStatusResult {
+ swarmId: string;
+ status: 'initializing' | 'active' | 'scaling' | 'degraded' | 'stopped';
+ config: SwarmConfig;
+ agents?: SwarmAgent[];
+ metrics?: SwarmMetrics;
+ topology?: SwarmTopology;
+ lastActivityAt?: string;
+}
+
+interface ScaleSwarmResult {
+ swarmId: string;
+ previousAgents: number;
+ targetAgents: number;
+ currentAgents: number;
+ scalingStatus: 'in-progress' | 'completed' | 'failed';
+ scaledAt: string;
+ addedAgents?: string[];
+ removedAgents?: string[];
+}
+
+// ============================================================================
+// Tool Handlers
+// ============================================================================
+
+/**
+ * Initialize swarm coordination
+ */
+async function handleInitSwarm(
+ input: z.infer<typeof initSwarmSchema>,
+ context?: ToolContext
+): Promise<InitSwarmResult> {
+ // TODO: Integrate with actual swarm coordinator when available
+ // For now, return stub response
+
+ const swarmId = `swarm-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
+ const initializedAt = new Date().toISOString();
+
+ const config: SwarmConfig = {
+ topology: input.topology,
+ maxAgents: input.maxAgents,
+ currentAgents: 0,
+ communicationProtocol: input.config?.communicationProtocol || 'message-bus',
+ consensusMechanism: input.config?.consensusMechanism || 'majority',
+ failureHandling: input.config?.failureHandling || 'retry',
+ loadBalancing: input.config?.loadBalancing ?? true,
+ autoScaling: input.config?.autoScaling ?? true,
+ };
+
+ // Stub implementation - will be replaced with actual swarm coordinator integration
+ const result: InitSwarmResult = {
+ swarmId,
+ topology: input.topology,
+ initializedAt,
+ config,
+ };
+
+ // TODO: Call actual swarm coordinator
+ // const swarmCoordinator = context?.swarmCoordinator as SwarmCoordinator;
+ // if (swarmCoordinator) {
+ // await swarmCoordinator.initialize({
+ // topology: input.topology,
+ // maxAgents: input.maxAgents,
+ // config: input.config,
+ // metadata: input.metadata,
+ // });
+ // }
+
+ return result;
+}
+
+/**
+ * Get swarm status
+ */
+async function handleSwarmStatus(
+ input: z.infer<typeof swarmStatusSchema>,
+ context?: ToolContext
+): Promise<SwarmStatusResult> {
+ // TODO: Integrate with actual swarm coordinator when available
+ // For now, return stub response
+
+ const swarmId = 'swarm-current';
+ const config: SwarmConfig = {
+ topology: 'hierarchical-mesh',
+ maxAgents: 15,
+ currentAgents: 5,
+ communicationProtocol: 'message-bus',
+ consensusMechanism: 'majority',
+ failureHandling: 'retry',
+ loadBalancing: true,
+ autoScaling: true,
+ };
+
+ const result: SwarmStatusResult = {
+ swarmId,
+ status: 'active',
+ config,
+ lastActivityAt: new Date().toISOString(),
+ };
+
+ if (input.includeAgents) {
+ result.agents = [
+ {
+ id: 'agent-coordinator-1',
+ type: 'queen-coordinator',
+ status: 'active',
+ role: 'coordinator',
+ connections: ['agent-security-1', 'agent-core-1', 'agent-integration-1'],
+ },
+ {
+ id: 'agent-security-1',
+ type: 'security-architect',
+ status: 'busy',
+ role: 'specialist',
+ connections: ['agent-coordinator-1'],
+ },
+ {
+ id: 'agent-core-1',
+ type: 'core-architect',
+ status: 'active',
+ role: 'worker',
+ connections: ['agent-coordinator-1'],
+ },
+ {
+ id: 'agent-integration-1',
+ type: 'integration-architect',
+ status: 'idle',
+ role: 'worker',
+ connections: ['agent-coordinator-1'],
+ },
+ {
+ id: 'agent-performance-1',
+ type: 'performance-engineer',
+ status: 'active',
+ role: 'specialist',
+ connections: ['agent-coordinator-1'],
+ },
+ ];
+ }
+
+ if (input.includeMetrics) {
+ result.metrics = {
+ totalTasks: 150,
+ completedTasks: 120,
+ failedTasks: 5,
+ inProgressTasks: 25,
+ averageTaskDuration: 2345.67,
+ throughput: 0.85,
+ efficiency: 0.92,
+ uptime: 7200000,
+ };
+ }
+
+ if (input.includeTopology) {
+ result.topology = {
+ nodes: [
+ { id: 'agent-coordinator-1', type: 'queen-coordinator', role: 'coordinator' },
+ { id: 'agent-security-1', type: 'security-architect', role: 'specialist' },
+ { id: 'agent-core-1', type: 'core-architect', role: 'worker' },
+ { id: 'agent-integration-1', type: 'integration-architect', role: 'worker' },
+ { id: 'agent-performance-1', type: 'performance-engineer', role: 'specialist' },
+ ],
+ edges: [
+ { from: 'agent-coordinator-1', to: 'agent-security-1', weight: 1.0 },
+ { from: 'agent-coordinator-1', to: 'agent-core-1', weight: 0.8 },
+ { from: 'agent-coordinator-1', to: 'agent-integration-1', weight: 0.9 },
+ { from: 'agent-coordinator-1', to: 'agent-performance-1', weight: 0.7 },
+ ],
+ depth: 2,
+ fanout: 4,
+ };
+ }
+
+ // TODO: Call actual swarm coordinator
+ // const swarmCoordinator = context?.swarmCoordinator as SwarmCoordinator;
+ // if (swarmCoordinator) {
+ // const status = await swarmCoordinator.getStatus({
+ // includeAgents: input.includeAgents,
+ // includeMetrics: input.includeMetrics,
+ // includeTopology: input.includeTopology,
+ // });
+ // return status;
+ // }
+
+ return result;
+}
+
+/**
+ * Scale swarm agents
+ */
+async function handleScaleSwarm(
+ input: z.infer<typeof scaleSwarmSchema>,
+ context?: ToolContext
+): Promise<ScaleSwarmResult> {
+ // TODO: Integrate with actual swarm coordinator when available
+ // For now, return stub response
+
+ const swarmId = 'swarm-current';
+ const previousAgents = 5;
+ const scaledAt = new Date().toISOString();
+
+ const result: ScaleSwarmResult = {
+ swarmId,
+ previousAgents,
+ targetAgents: input.targetAgents,
+ currentAgents: input.targetAgents,
+ scalingStatus: 'completed',
+ scaledAt,
+ };
+
+ if (input.targetAgents > previousAgents) {
+ // Scaling up
+ const newAgentCount = input.targetAgents - previousAgents;
+ result.addedAgents = Array.from({ length: newAgentCount }, (_, i) =>
+ `agent-new-${i + 1}`
+ );
+ } else if (input.targetAgents < previousAgents) {
+ // Scaling down
+ const removedAgentCount = previousAgents - input.targetAgents;
+ result.removedAgents = Array.from({ length: removedAgentCount }, (_, i) =>
+ `agent-removed-${i + 1}`
+ );
+ }
+
+ // TODO: Call actual swarm coordinator
+ // const swarmCoordinator = context?.swarmCoordinator as SwarmCoordinator;
+ // if (swarmCoordinator) {
+ // const scaleResult = await swarmCoordinator.scale({
+ // targetAgents: input.targetAgents,
+ // strategy: input.scaleStrategy,
+ // agentTypes: input.agentTypes,
+ // reason: input.reason,
+ // });
+ // return scaleResult;
+ // }
+
+ return result;
+}
+
+// ============================================================================
+// Tool Definitions
+// ============================================================================
+
+/**
+ * swarm/init tool
+ */
+export const initSwarmTool: MCPTool = {
+ name: 'swarm/init',
+ description: 'Initialize swarm coordination with specified topology and configuration',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ topology: {
+ type: 'string',
+ enum: ['hierarchical', 'mesh', 'adaptive', 'collective', 'hierarchical-mesh'],
+ description: 'Swarm coordination topology',
+ default: 'hierarchical-mesh',
+ },
+ maxAgents: {
+ type: 'number',
+ description: 'Maximum number of agents in the swarm',
+ minimum: 1,
+ maximum: 1000,
+ default: 15,
+ },
+ config: {
+ type: 'object',
+ description: 'Swarm configuration',
+ properties: {
+ communicationProtocol: {
+ type: 'string',
+ enum: ['direct', 'message-bus', 'pubsub'],
+ },
+ consensusMechanism: {
+ type: 'string',
+ enum: ['majority', 'unanimous', 'weighted', 'none'],
+ },
+ failureHandling: {
+ type: 'string',
+ enum: ['retry', 'failover', 'ignore'],
+ },
+ loadBalancing: { type: 'boolean' },
+ autoScaling: { type: 'boolean' },
+ },
+ },
+ metadata: {
+ type: 'object',
+ description: 'Additional metadata',
+ additionalProperties: true,
+ },
+ },
+ },
+ handler: async (input, context) => {
+ const validated = initSwarmSchema.parse(input);
+ return handleInitSwarm(validated, context);
+ },
+ category: 'swarm',
+ tags: ['swarm', 'coordination', 'initialization'],
+ version: '1.0.0',
+};
+
+/**
+ * swarm/status tool
+ */
+export const swarmStatusTool: MCPTool = {
+ name: 'swarm/status',
+ description: 'Get current swarm status including agents, metrics, and topology',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ includeAgents: {
+ type: 'boolean',
+ description: 'Include individual agent information',
+ default: true,
+ },
+ includeMetrics: {
+ type: 'boolean',
+ description: 'Include performance metrics',
+ default: false,
+ },
+ includeTopology: {
+ type: 'boolean',
+ description: 'Include topology graph',
+ default: false,
+ },
+ },
+ },
+ handler: async (input, context) => {
+ const validated = swarmStatusSchema.parse(input);
+ return handleSwarmStatus(validated, context);
+ },
+ category: 'swarm',
+ tags: ['swarm', 'status', 'monitoring'],
+ version: '1.0.0',
+ cacheable: true,
+ cacheTTL: 2000,
+};
+
+/**
+ * swarm/scale tool
+ */
+export const scaleSwarmTool: MCPTool = {
+ name: 'swarm/scale',
+ description: 'Scale swarm up or down to target number of agents',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ targetAgents: {
+ type: 'number',
+ description: 'Target number of agents',
+ minimum: 1,
+ maximum: 1000,
+ },
+ scaleStrategy: {
+ type: 'string',
+ enum: ['gradual', 'immediate', 'adaptive'],
+ description: 'Scaling strategy',
+ default: 'gradual',
+ },
+ agentTypes: {
+ type: 'array',
+ items: { type: 'string' },
+ description: 'Specific agent types to scale',
+ },
+ reason: {
+ type: 'string',
+ description: 'Reason for scaling',
+ },
+ },
+ required: ['targetAgents'],
+ },
+ handler: async (input, context) => {
+ const validated = scaleSwarmSchema.parse(input);
+ return handleScaleSwarm(validated, context);
+ },
+ category: 'swarm',
+ tags: ['swarm', 'scaling', 'coordination'],
+ version: '1.0.0',
+};
+
+// ============================================================================
+// Exports
+// ============================================================================
+
+export const swarmTools: MCPTool[] = [
+ initSwarmTool,
+ swarmStatusTool,
+ scaleSwarmTool,
+];
+
+export default swarmTools;