snow-flow 2.0.3 → 2.0.5

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.
@@ -0,0 +1,281 @@
1
+ "use strict";
2
+ /**
3
+ * Snow-Flow Memory System MCP Integration Example
4
+ * Shows how MCP tools integrate with the memory system
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ const memory_client_js_1 = require("./memory-client.js");
8
+ const logger_js_1 = require("../utils/logger.js");
9
+ const logger = new logger_js_1.Logger('MCPIntegration');
10
+ /**
11
+ * Example MCP tool that follows the memory integration pattern from MCP_ARCHITECTURE.md
12
+ */
13
+ class WidgetCreatorMCP {
14
+ constructor(sessionId, agentId) {
15
+ this.memory = memory_client_js_1.MemoryClient.forAgent(agentId, 'widget-creator', sessionId);
16
+ }
17
+ /**
18
+ * Widget creation tool with full memory integration
19
+ */
20
+ async widget_create_structure(params) {
21
+ // 1. Read session context (as per MCP_ARCHITECTURE.md pattern)
22
+ const sessionContext = await this.memory.getSessionData();
23
+ const requirements = sessionContext.widget_requirements || {};
24
+ // Check for active agents
25
+ const activeAgents = await this.memory.getOperations().getActiveAgents(params.session_id);
26
+ logger.info('Active agents in session', {
27
+ count: activeAgents.length,
28
+ agents: activeAgents.map(a => ({ id: a.agent_id, type: a.agent_type, status: a.status }))
29
+ });
30
+ // 2. Execute ServiceNow operation (simulated)
31
+ const widgetResult = {
32
+ sys_id: `widget_${Date.now()}`,
33
+ name: params.widget_config.name,
34
+ title: params.widget_config.title,
35
+ status: 'created'
36
+ };
37
+ // 3. Update artifact tracking
38
+ if (params.update_memory) {
39
+ await this.memory.storeArtifact({
40
+ sys_id: widgetResult.sys_id,
41
+ type: 'widget',
42
+ name: params.widget_config.name,
43
+ description: `Widget created by ${params.agent_id}`,
44
+ status: 'created',
45
+ metadata: {
46
+ category: params.widget_config.category,
47
+ responsive: params.widget_config.responsive,
48
+ created_from_requirements: requirements
49
+ }
50
+ });
51
+ }
52
+ // 4. Notify other agents via shared context
53
+ await this.memory.store({
54
+ key: 'widget_template_ready',
55
+ value: {
56
+ widget_sys_id: widgetResult.sys_id,
57
+ template_ready: true,
58
+ next_agent: 'ui_specialist'
59
+ }
60
+ });
61
+ // 5. Update coordination status
62
+ await this.memory.updateProgress(100);
63
+ // 6. Send handoff message
64
+ await this.memory.handoff({
65
+ to_agent: 'ui_specialist_001',
66
+ artifact_reference: widgetResult.sys_id,
67
+ data: {
68
+ styling_needed: true,
69
+ requirements: requirements.styling_requirements || {}
70
+ }
71
+ });
72
+ return widgetResult;
73
+ }
74
+ /**
75
+ * Performance-tracked operation example
76
+ */
77
+ async widget_generate_template(params) {
78
+ // Start performance tracking
79
+ const tracker = this.memory.trackOperation('generate_widget_template');
80
+ try {
81
+ // Simulate template generation
82
+ await new Promise(resolve => setTimeout(resolve, 50));
83
+ const template = {
84
+ html: '<div class="widget-container">...</div>',
85
+ type: params.template_type,
86
+ size: 1024
87
+ };
88
+ // Complete tracking with success
89
+ await tracker.complete(true, undefined, {
90
+ template_size: template.size,
91
+ template_type: params.template_type
92
+ });
93
+ return template;
94
+ }
95
+ catch (error) {
96
+ // Complete tracking with failure
97
+ await tracker.complete(false, error.message);
98
+ throw error;
99
+ }
100
+ }
101
+ }
102
+ /**
103
+ * Example Queen Agent coordination with memory
104
+ */
105
+ class QueenCoordinationMCP {
106
+ constructor(sessionId) {
107
+ this.memory = memory_client_js_1.MemoryClient.forAgent('queen_001', 'queen', sessionId);
108
+ }
109
+ /**
110
+ * Monitor swarm progress using memory system
111
+ */
112
+ async queen_monitor_swarm(params) {
113
+ // Get session state from memory
114
+ const state = await this.memory.getSessionState();
115
+ // Analyze agent coordination
116
+ const agentStatus = state.agents.map(agent => ({
117
+ id: agent.agent_id,
118
+ type: agent.agent_type,
119
+ status: agent.status,
120
+ progress: agent.progress_percentage,
121
+ current_tool: agent.current_tool,
122
+ last_activity: agent.last_activity,
123
+ is_blocked: agent.status === 'blocked',
124
+ error: agent.error_state
125
+ }));
126
+ // Check for blocking issues
127
+ const blockingIssues = [];
128
+ // Check blocked agents
129
+ const blockedAgents = agentStatus.filter(a => a.is_blocked);
130
+ if (blockedAgents.length > 0) {
131
+ blockingIssues.push({
132
+ type: 'blocked_agents',
133
+ agents: blockedAgents,
134
+ recommendation: 'Check agent dependencies'
135
+ });
136
+ }
137
+ // Check failed deployments
138
+ const failedArtifacts = state.artifacts.filter(a => a.deployment_status === 'failed');
139
+ if (failedArtifacts.length > 0) {
140
+ blockingIssues.push({
141
+ type: 'failed_deployments',
142
+ artifacts: failedArtifacts,
143
+ recommendation: 'Review deployment errors and retry'
144
+ });
145
+ }
146
+ // Performance analysis
147
+ let performanceAnalysis = null;
148
+ if (params.detailed_metrics && state.performanceSummary) {
149
+ performanceAnalysis = {
150
+ total_operations: state.performanceSummary.total_operations,
151
+ avg_duration_ms: state.performanceSummary.avg_duration_ms,
152
+ success_rate: state.performanceSummary.success_rate,
153
+ slowest_operation_ms: state.performanceSummary.max_duration_ms,
154
+ recommendation: state.performanceSummary.avg_duration_ms > 100
155
+ ? 'Performance below target (<100ms), consider optimization'
156
+ : 'Performance meets requirements'
157
+ };
158
+ }
159
+ return {
160
+ session_id: params.session_id,
161
+ swarm_status: {
162
+ total_agents: state.agents.length,
163
+ active_agents: agentStatus.filter(a => a.status === 'active').length,
164
+ completed_agents: agentStatus.filter(a => a.status === 'completed').length,
165
+ blocked_agents: blockedAgents.length
166
+ },
167
+ agent_details: agentStatus,
168
+ artifacts_created: state.artifacts.length,
169
+ pending_messages: state.pendingMessages,
170
+ blocking_issues: blockingIssues,
171
+ performance_analysis: performanceAnalysis
172
+ };
173
+ }
174
+ /**
175
+ * Coordinate agent handoffs
176
+ */
177
+ async queen_coordinate_handoff(params) {
178
+ // Send coordination message
179
+ await this.memory.getOperations().sendMessage(this.memory.getSessionId(), 'queen_001', params.to_agent, 'coordination', {
180
+ handoff_from: params.from_agent,
181
+ artifact_type: params.artifact_type,
182
+ context: params.context_data,
183
+ coordination_time: new Date().toISOString()
184
+ });
185
+ // Update shared context for coordination
186
+ await this.memory.store({
187
+ key: `handoff_${params.from_agent}_to_${params.to_agent}`,
188
+ value: {
189
+ completed: true,
190
+ artifact_type: params.artifact_type,
191
+ timestamp: new Date().toISOString()
192
+ }
193
+ });
194
+ }
195
+ }
196
+ /**
197
+ * Example usage showing full integration
198
+ */
199
+ async function demonstrateIntegration() {
200
+ logger.info('Starting MCP integration demonstration');
201
+ const sessionId = `demo_session_${Date.now()}`;
202
+ // Initialize MCPs
203
+ const widgetMCP = new WidgetCreatorMCP(sessionId, 'widget_creator_001');
204
+ const queenMCP = new QueenCoordinationMCP(sessionId);
205
+ try {
206
+ // Register agents
207
+ const widgetMemory = memory_client_js_1.MemoryClient.forAgent('widget_creator_001', 'widget-creator', sessionId);
208
+ const uiMemory = memory_client_js_1.MemoryClient.forAgent('ui_specialist_001', 'ui-specialist', sessionId);
209
+ await widgetMemory.register(['create_dashboard_widget']);
210
+ await uiMemory.register(['style_widget']);
211
+ // Store requirements in memory (simulating earlier analysis)
212
+ await widgetMemory.store({
213
+ key: 'widget_requirements',
214
+ value: {
215
+ type: 'dashboard',
216
+ data_sources: ['incident', 'problem'],
217
+ styling_requirements: {
218
+ theme: 'modern',
219
+ responsive: true
220
+ }
221
+ }
222
+ });
223
+ logger.info('Step 1: Widget creation with memory integration');
224
+ // Create widget using MCP tool
225
+ const widgetResult = await widgetMCP.widget_create_structure({
226
+ session_id: sessionId,
227
+ widget_config: {
228
+ name: 'incident_dashboard',
229
+ title: 'Incident Dashboard',
230
+ category: 'custom',
231
+ responsive: true
232
+ },
233
+ agent_id: 'widget_creator_001',
234
+ update_memory: true
235
+ });
236
+ logger.info('Widget created', widgetResult);
237
+ logger.info('Step 2: Generate template with performance tracking');
238
+ // Generate template
239
+ const template = await widgetMCP.widget_generate_template({
240
+ requirements: { charts: true, filters: true },
241
+ template_type: 'dashboard'
242
+ });
243
+ logger.info('Template generated', { size: template.size });
244
+ logger.info('Step 3: Queen monitors swarm progress');
245
+ // Queen monitors progress
246
+ const swarmStatus = await queenMCP.queen_monitor_swarm({
247
+ session_id: sessionId,
248
+ detailed_metrics: true
249
+ });
250
+ logger.info('Swarm status', JSON.stringify(swarmStatus, null, 2));
251
+ logger.info('Step 4: UI specialist checks for handoffs');
252
+ // UI specialist checks messages
253
+ const handoffs = await uiMemory.checkHandoffs();
254
+ logger.info('UI specialist received handoffs', handoffs);
255
+ logger.info('Step 5: Check performance metrics');
256
+ // Get performance stats
257
+ const perfStats = await widgetMemory.getPerformanceStats('generate_widget_template');
258
+ logger.info('Performance statistics', perfStats);
259
+ logger.info('Integration demonstration completed successfully!');
260
+ }
261
+ catch (error) {
262
+ logger.error('Integration demonstration failed', error);
263
+ throw error;
264
+ }
265
+ finally {
266
+ // Cleanup
267
+ memory_client_js_1.MemoryClient.shutdown();
268
+ }
269
+ }
270
+ // Run demonstration if called directly
271
+ if (require.main === module) {
272
+ demonstrateIntegration()
273
+ .then(() => {
274
+ logger.info('MCP integration demonstration completed');
275
+ process.exit(0);
276
+ })
277
+ .catch((error) => {
278
+ logger.error('MCP integration demonstration failed', error);
279
+ process.exit(1);
280
+ });
281
+ }
@@ -0,0 +1,199 @@
1
+ /**
2
+ * Snow-Flow Memory Client
3
+ * Simple API for agents to interact with the memory system
4
+ */
5
+ import { SwarmMemory, SwarmMemoryConfig } from './swarm-memory.js';
6
+ import { MemoryOperations } from './memory-operations.js';
7
+ export interface MemoryClientConfig extends SwarmMemoryConfig {
8
+ sessionId?: string;
9
+ agentId?: string;
10
+ agentType?: string;
11
+ }
12
+ export interface MemoryStoreOptions {
13
+ key: string;
14
+ value: any;
15
+ expires?: Date;
16
+ permissions?: string[];
17
+ }
18
+ export interface MemoryRetrieveOptions {
19
+ key: string;
20
+ defaultValue?: any;
21
+ }
22
+ export interface ArtifactInfo {
23
+ sys_id: string;
24
+ type: 'widget' | 'flow' | 'script' | 'business_rule' | 'table' | 'catalog_item';
25
+ name: string;
26
+ description?: string;
27
+ status?: 'created' | 'tested' | 'deployed' | 'verified' | 'failed';
28
+ update_set_id?: string;
29
+ dependencies?: string[];
30
+ metadata?: any;
31
+ }
32
+ export interface AgentHandoff {
33
+ to_agent: string;
34
+ artifact_reference?: string;
35
+ data: any;
36
+ }
37
+ export interface PerformanceTracker {
38
+ complete(success: boolean, error?: string, metadata?: any): Promise<void>;
39
+ }
40
+ export declare class MemoryClient {
41
+ private memory;
42
+ private operations;
43
+ private logger;
44
+ private sessionId;
45
+ private agentId;
46
+ private agentType;
47
+ constructor(config?: MemoryClientConfig);
48
+ /**
49
+ * Store data in shared context
50
+ */
51
+ store(options: MemoryStoreOptions): Promise<void>;
52
+ /**
53
+ * Retrieve data from shared context with agent isolation
54
+ */
55
+ retrieve(options: MemoryRetrieveOptions): Promise<any>;
56
+ /**
57
+ * Retrieve data from truly shared context (no agent isolation)
58
+ * Use this when agents need to access shared coordination data
59
+ */
60
+ retrieveShared(options: MemoryRetrieveOptions): Promise<any>;
61
+ /**
62
+ * Store data in truly shared context (no agent isolation)
63
+ * Use this when you want all agents to access the same data
64
+ */
65
+ storeShared(options: MemoryStoreOptions): Promise<void>;
66
+ /**
67
+ * Get all context for current session
68
+ */
69
+ getSessionData(): Promise<Record<string, any>>;
70
+ /**
71
+ * Register current agent
72
+ */
73
+ register(assignedTasks?: string[]): Promise<void>;
74
+ /**
75
+ * Update agent progress
76
+ */
77
+ updateProgress(percentage: number, currentTool?: string): Promise<void>;
78
+ /**
79
+ * Mark agent as completed
80
+ */
81
+ complete(): Promise<void>;
82
+ /**
83
+ * Report agent error
84
+ */
85
+ reportError(error: string): Promise<void>;
86
+ /**
87
+ * Check if agent should wait for dependencies
88
+ */
89
+ checkDependencies(): Promise<boolean>;
90
+ /**
91
+ * Store ServiceNow artifact information
92
+ */
93
+ storeArtifact(artifact: ArtifactInfo): Promise<void>;
94
+ /**
95
+ * Update artifact status
96
+ */
97
+ updateArtifactStatus(sys_id: string, status: 'created' | 'tested' | 'deployed' | 'verified' | 'failed'): Promise<void>;
98
+ /**
99
+ * Find artifacts created in current session
100
+ */
101
+ findSessionArtifacts(type?: ArtifactInfo['type']): Promise<ArtifactInfo[]>;
102
+ /**
103
+ * Send handoff to another agent
104
+ */
105
+ handoff(handoff: AgentHandoff): Promise<void>;
106
+ /**
107
+ * Check for incoming handoffs
108
+ */
109
+ checkHandoffs(): Promise<Array<{
110
+ from: string;
111
+ data: any;
112
+ artifact_reference?: string;
113
+ }>>;
114
+ /**
115
+ * Send status update
116
+ */
117
+ sendStatus(status: string, details?: any): Promise<void>;
118
+ /**
119
+ * Report dependency ready
120
+ */
121
+ reportDependencyReady(dependent_agent: string, artifact_reference?: string): Promise<void>;
122
+ /**
123
+ * Start tracking an operation
124
+ */
125
+ trackOperation(operation: string): PerformanceTracker;
126
+ /**
127
+ * Get average performance for an operation
128
+ */
129
+ getPerformanceStats(operation: string): Promise<{
130
+ avgDuration: number;
131
+ successRate: number;
132
+ totalOperations: number;
133
+ } | null>;
134
+ /**
135
+ * Record successful deployment
136
+ */
137
+ recordDeployment(artifact_sys_id: string, type: 'create' | 'update' | 'test' | 'verify' | 'rollback', success?: boolean, error?: string): Promise<void>;
138
+ /**
139
+ * Get deployment history for an artifact
140
+ */
141
+ getDeploymentHistory(artifact_sys_id: string): Promise<Array<{
142
+ type: string;
143
+ success: boolean;
144
+ time: Date;
145
+ agent: string;
146
+ error?: string;
147
+ }>>;
148
+ /**
149
+ * Get current session ID
150
+ */
151
+ getSessionId(): string;
152
+ /**
153
+ * Get current agent ID
154
+ */
155
+ getAgentId(): string;
156
+ /**
157
+ * Get complete session state
158
+ */
159
+ getSessionState(): Promise<any>;
160
+ /**
161
+ * Clean up current session
162
+ */
163
+ cleanup(): Promise<void>;
164
+ /**
165
+ * Get memory statistics
166
+ */
167
+ getStats(): Record<string, any>;
168
+ /**
169
+ * Run memory cleanup
170
+ */
171
+ runCleanup(): Promise<void>;
172
+ /**
173
+ * Get direct access to operations (for advanced use cases)
174
+ */
175
+ getOperations(): MemoryOperations;
176
+ /**
177
+ * Get direct access to database (for custom queries)
178
+ */
179
+ getDatabase(): SwarmMemory;
180
+ /**
181
+ * Create a memory client for an agent
182
+ */
183
+ static forAgent(agentId: string, agentType: string, sessionId?: string): MemoryClient;
184
+ /**
185
+ * Create a memory client for a session
186
+ */
187
+ static forSession(sessionId: string): MemoryClient;
188
+ /**
189
+ * Close all connections (call when shutting down)
190
+ */
191
+ static shutdown(): void;
192
+ private generateSessionId;
193
+ /**
194
+ * COMPATIBILITY FIX: makeRequest method for phantom calls
195
+ * MemoryClient doesn't use HTTP requests, so this is a no-op fallback
196
+ */
197
+ makeRequest(config: any): Promise<any>;
198
+ }
199
+ //# sourceMappingURL=memory-client.d.ts.map