ai-debug-local-mcp
Version:
🎯 ENHANCED AI GUIDANCE v4.1.2: Dramatically improved tool descriptions help AI users choose the right tools instead of 'close enough' options. Ultra-fast keyboard automation (10x speed), universal recording, multi-ecosystem debugging support, and compreh
617 lines • 28.3 kB
JavaScript
/**
* Context Sharing Handler
* MCP tool integration for bidirectional context sharing
*/
import { BidirectionalContextManager } from '../context-sharing/bidirectional-context-manager.js';
import { ContextAwareAgentWrapper } from '../context-sharing/context-aware-agent-wrapper.js';
import { BaseToolHandler } from './base-handler-migrated.js';
export class ContextSharingHandler extends BaseToolHandler {
contextManager;
agentWrappers = new Map();
constructor() {
super();
this.contextManager = new BidirectionalContextManager();
this.setupGlobalContextMonitoring();
}
get tools() {
return [
{
name: 'enable_bidirectional_context_sharing',
description: 'Enable bidirectional context sharing between primary agent and sub-agents. CRITICAL: Ensures coordinated decision-making and shared understanding across all agents.',
inputSchema: {
type: 'object',
properties: {
agentConfig: {
type: 'object',
properties: {
agentId: {
type: 'string',
description: 'Unique identifier for this agent'
},
agentType: {
type: 'string',
enum: ['primary', 'sub', 'background'],
description: 'Type of agent (primary, sub, or background)'
},
contextDependencies: {
type: 'array',
items: { type: 'string' },
description: 'Types of context this agent critically needs (e.g., ["discovery", "decision", "error"])'
},
contextContributions: {
type: 'array',
items: { type: 'string' },
description: 'Types of context this agent provides to others'
},
sharingImportanceScore: {
type: 'number',
minimum: 0,
maximum: 1,
description: 'How critical context sharing is for this agent (0-1, where 1 is critical)'
}
},
required: ['agentId', 'agentType', 'contextDependencies', 'contextContributions', 'sharingImportanceScore']
},
behaviorConfig: {
type: 'object',
properties: {
shareDiscoveries: {
type: 'boolean',
default: true,
description: 'Share discoveries with relevant agents'
},
shareDecisions: {
type: 'boolean',
default: true,
description: 'Share decisions with relevant agents'
},
shareProgress: {
type: 'boolean',
default: true,
description: 'Share progress updates'
},
shareErrors: {
type: 'boolean',
default: true,
description: 'Share errors and problems'
},
contextSyncInterval: {
type: 'number',
default: 30000,
description: 'Interval for automatic context synchronization (milliseconds)'
}
}
}
},
required: ['agentConfig']
}
},
{
name: 'share_agent_context',
description: 'Share specific context (discovery, decision, progress, error) with other agents. Essential for coordinated problem-solving.',
inputSchema: {
type: 'object',
properties: {
agentId: {
type: 'string',
description: 'Agent ID sharing the context'
},
contextType: {
type: 'string',
enum: ['discovery', 'decision', 'progress', 'error', 'insight', 'state_change'],
description: 'Type of context being shared'
},
content: {
type: 'object',
properties: {
title: {
type: 'string',
description: 'Brief title for the context'
},
description: {
type: 'string',
description: 'Detailed description of the context'
},
data: {
type: 'object',
description: 'Additional structured data'
},
impact: {
type: 'string',
description: 'Impact or implications of this context'
},
recommendations: {
type: 'array',
items: { type: 'string' },
description: 'Recommended actions based on this context'
}
},
required: ['title', 'description']
},
priority: {
type: 'string',
enum: ['critical', 'high', 'medium', 'low'],
default: 'medium',
description: 'Priority level of this context'
},
sessionId: {
type: 'string',
description: 'Associated session ID'
},
framework: {
type: 'string',
description: 'Associated framework or technology'
},
toolsInvolved: {
type: 'array',
items: { type: 'string' },
description: 'Tools involved in this context'
}
},
required: ['agentId', 'contextType', 'content']
}
},
{
name: 'request_agent_context',
description: 'Request specific context from other agents. Use when you need information that other agents might have discovered.',
inputSchema: {
type: 'object',
properties: {
requestingAgentId: {
type: 'string',
description: 'Agent ID making the request'
},
contextType: {
type: 'string',
enum: ['discovery', 'decision', 'progress', 'error', 'insight', 'state_change'],
description: 'Type of context needed'
},
criteria: {
type: 'object',
properties: {
priority: {
type: 'string',
enum: ['critical', 'high', 'medium', 'low'],
description: 'Minimum priority level'
},
maxAge: {
type: 'number',
description: 'Maximum age of context in milliseconds'
},
requiredFor: {
type: 'string',
description: 'What this context is required for'
}
},
required: ['requiredFor']
}
},
required: ['requestingAgentId', 'contextType', 'criteria']
}
},
{
name: 'get_context_sharing_status',
description: 'Get comprehensive status of context sharing system, including agent awareness, sharing metrics, and critical gaps.',
inputSchema: {
type: 'object',
properties: {
includeDetailedMetrics: {
type: 'boolean',
default: true,
description: 'Include detailed sharing metrics'
},
includeAgentAwareness: {
type: 'boolean',
default: true,
description: 'Include individual agent awareness status'
}
}
}
},
{
name: 'emphasize_context_sharing_importance',
description: 'Get specific guidance on why context sharing is critical for a given scenario. Use to understand and communicate the importance of bidirectional context sharing.',
inputSchema: {
type: 'object',
properties: {
agentId: {
type: 'string',
description: 'Agent ID to get importance guidance for'
},
scenario: {
type: 'string',
description: 'Current scenario or context (e.g., "debugging", "refactoring", "testing")'
}
},
required: ['agentId', 'scenario']
}
},
{
name: 'force_context_synchronization',
description: 'Force immediate synchronization of context between agents. Use when critical context may be out of sync.',
inputSchema: {
type: 'object',
properties: {
agentId: {
type: 'string',
description: 'Agent ID to synchronize (optional, syncs all if not provided)'
},
urgency: {
type: 'string',
enum: ['immediate', 'high', 'normal'],
default: 'normal',
description: 'Urgency level of synchronization'
}
}
}
},
{
name: 'update_shared_context',
description: 'Collaboratively update existing shared context with new insights. Enables bidirectional refinement of shared understanding.',
inputSchema: {
type: 'object',
properties: {
contextId: {
type: 'string',
description: 'ID of the context to update'
},
updatingAgentId: {
type: 'string',
description: 'Agent making the update'
},
updates: {
type: 'object',
properties: {
content: {
type: 'object',
description: 'Content updates'
},
contextual: {
type: 'object',
description: 'Contextual information updates'
},
additionalInsights: {
type: 'array',
items: { type: 'string' },
description: 'Additional insights to add'
}
}
}
},
required: ['contextId', 'updatingAgentId', 'updates']
}
}
];
}
async handle(toolName, args, sessions) {
switch (toolName) {
case 'enable_bidirectional_context_sharing':
return this.enableBidirectionalContextSharing(args);
case 'share_agent_context':
return this.shareAgentContext(args);
case 'request_agent_context':
return this.requestAgentContext(args);
case 'get_context_sharing_status':
return this.getContextSharingStatus(args);
case 'emphasize_context_sharing_importance':
return this.emphasizeContextSharingImportance(args);
case 'force_context_synchronization':
return this.forceContextSynchronization(args);
case 'update_shared_context':
return this.updateSharedContext(args);
default:
throw new Error(`Unknown tool: ${toolName}`);
}
}
/**
* Enable bidirectional context sharing for an agent
*/
async enableBidirectionalContextSharing(args) {
const { agentConfig, behaviorConfig = {} } = args;
// Create context-aware agent wrapper
const agentWrapper = new ContextAwareAgentWrapper(this.contextManager, agentConfig, behaviorConfig);
this.agentWrappers.set(agentConfig.agentId, agentWrapper);
// Get importance guidance
const importance = this.contextManager.emphasizeContextSharingImportance(agentConfig.agentId, 'agent_setup');
return {
success: true,
agentId: agentConfig.agentId,
message: `Bidirectional context sharing enabled for ${agentConfig.agentType} agent`,
contextImportance: importance,
behaviorConfig: {
shareDiscoveries: behaviorConfig.shareDiscoveries !== false,
shareDecisions: behaviorConfig.shareDecisions !== false,
shareProgress: behaviorConfig.shareProgress !== false,
shareErrors: behaviorConfig.shareErrors !== false,
contextSyncInterval: behaviorConfig.contextSyncInterval || 30000
},
guidance: [
'Context sharing is CRITICAL for coordinated agent behavior',
'Share discoveries immediately to prevent duplicated work',
'Share decisions to maintain consistent approach across agents',
'Request context when encountering unfamiliar situations',
'Update shared context collaboratively as understanding evolves'
]
};
}
/**
* Share context from an agent
*/
async shareAgentContext(args) {
const { agentId, contextType, content, priority = 'medium', sessionId, framework, toolsInvolved } = args;
const agentWrapper = this.agentWrappers.get(agentId);
if (!agentWrapper) {
return {
success: false,
error: `Agent ${agentId} not registered for context sharing. Call enable_bidirectional_context_sharing first.`,
recommendation: 'Register agent with bidirectional context sharing before sharing context'
};
}
let contextId;
switch (contextType) {
case 'discovery':
contextId = await agentWrapper.shareDiscovery({
title: content.title,
description: content.description,
data: content.data,
impact: content.impact,
recommendations: content.recommendations,
priority,
sessionId,
framework,
toolsInvolved
});
break;
case 'decision':
contextId = await agentWrapper.shareDecision({
title: content.title,
description: content.description,
rationale: content.data?.rationale || content.description,
alternatives: content.data?.alternatives,
impact: content.impact,
priority,
sessionId,
toolsInvolved
});
break;
case 'progress':
contextId = await agentWrapper.shareProgress({
title: content.title,
description: content.description,
completionPercentage: content.data?.completionPercentage,
nextSteps: content.data?.nextSteps || content.recommendations,
blockers: content.data?.blockers,
sessionId
});
break;
case 'error':
contextId = await agentWrapper.shareError({
title: content.title,
description: content.description,
errorDetails: content.data,
severity: priority,
recoveryAttempts: content.data?.recoveryAttempts,
sessionId,
toolsInvolved
});
break;
default:
return {
success: false,
error: `Unknown context type: ${contextType}`,
supportedTypes: ['discovery', 'decision', 'progress', 'error']
};
}
return {
success: true,
contextId,
agentId,
contextType,
priority,
message: `Context shared successfully. Other agents will be notified based on relevance and priority.`,
sharingImportance: this.contextManager.emphasizeContextSharingImportance(agentId, contextType)
};
}
/**
* Request context from other agents
*/
async requestAgentContext(args) {
const { requestingAgentId, contextType, criteria } = args;
const agentWrapper = this.agentWrappers.get(requestingAgentId);
if (!agentWrapper) {
return {
success: false,
error: `Agent ${requestingAgentId} not registered for context sharing`,
recommendation: 'Register agent with bidirectional context sharing before requesting context'
};
}
const contexts = await agentWrapper.requestContext(contextType, criteria);
return {
success: true,
requestingAgentId,
contextType,
criteria,
contexts: contexts.map(ctx => ({
id: ctx.id,
source: ctx.source,
sourceId: ctx.sourceId,
timestamp: ctx.timestamp,
priority: ctx.priority,
title: ctx.content.title,
description: ctx.content.description,
data: ctx.content.data,
impact: ctx.content.impact,
recommendations: ctx.content.recommendations
})),
foundCount: contexts.length,
message: contexts.length > 0
? `Found ${contexts.length} relevant context entries`
: `No context found matching criteria. Consider broadening search or requesting from specific agents.`
};
}
/**
* Get context sharing status
*/
async getContextSharingStatus(args) {
const { includeDetailedMetrics = true, includeAgentAwareness = true } = args;
const status = this.contextManager.getContextSharingStatus();
const result = {
success: true,
overview: {
totalContexts: status.totalContexts,
activeAgents: status.activeAgents,
recentActivity: status.recentActivity.length,
criticalGaps: status.criticalGaps.length
}
};
if (includeDetailedMetrics) {
result.metrics = status.sharingMetrics;
result.recentActivity = status.recentActivity.map(ctx => ({
id: ctx.id,
type: ctx.type,
source: ctx.source,
priority: ctx.priority,
title: ctx.content.title,
timestamp: ctx.timestamp
}));
}
if (includeAgentAwareness) {
result.agents = Array.from(this.agentWrappers.entries()).map(([agentId, wrapper]) => {
const awareness = wrapper.getContextAwarenessStatus();
return {
agentId,
importance: awareness.importance,
sharingMetrics: awareness.sharingMetrics,
bufferSize: awareness.buffer.length
};
});
}
if (status.criticalGaps.length > 0) {
result.criticalGaps = status.criticalGaps;
result.recommendations = [
'Address critical context gaps immediately',
'Ensure all agents are regularly sharing and syncing context',
'Check network connectivity between agents',
'Verify agent registration and configuration'
];
}
return result;
}
/**
* Emphasize context sharing importance
*/
async emphasizeContextSharingImportance(args) {
const { agentId, scenario } = args;
const importance = this.contextManager.emphasizeContextSharingImportance(agentId, scenario);
return {
success: true,
agentId,
scenario,
importance: importance.importance,
reasoning: importance.reasoning,
recommendations: importance.recommendations,
keyMessage: `Context sharing is ${importance.importance.toUpperCase()} for effective agent coordination. ${importance.reasoning}`,
actionableSteps: [
'Share all discoveries and decisions immediately',
'Request context when facing unfamiliar situations',
'Acknowledge receipt of critical context',
'Update shared context when new insights emerge',
'Monitor context sync status regularly'
]
};
}
/**
* Force context synchronization
*/
async forceContextSynchronization(args) {
const { agentId, urgency = 'normal' } = args;
if (agentId) {
// Sync specific agent
const agentWrapper = this.agentWrappers.get(agentId);
if (!agentWrapper) {
return {
success: false,
error: `Agent ${agentId} not registered for context sharing`
};
}
await agentWrapper.forceContextSync();
return {
success: true,
agentId,
urgency,
message: `Context synchronization completed for agent ${agentId}`,
recommendation: 'Verify that critical context is now available and up-to-date'
};
}
else {
// Sync all agents
const syncResults = [];
for (const [agentId, wrapper] of this.agentWrappers.entries()) {
try {
await wrapper.forceContextSync();
syncResults.push({ agentId, status: 'success' });
}
catch (error) {
syncResults.push({ agentId, status: 'error', error: error instanceof Error ? error.message : String(error) });
}
}
const successCount = syncResults.filter(r => r.status === 'success').length;
const errorCount = syncResults.filter(r => r.status === 'error').length;
return {
success: true,
urgency,
syncResults,
summary: {
totalAgents: syncResults.length,
successful: successCount,
errors: errorCount
},
message: `Context synchronization completed for ${successCount} agents`,
criticalMessage: errorCount > 0
? `${errorCount} agents failed to sync - this could lead to coordination issues`
: 'All agents successfully synchronized'
};
}
}
/**
* Update shared context collaboratively
*/
async updateSharedContext(args) {
const { contextId, updatingAgentId, updates } = args;
const success = await this.contextManager.updateContext(contextId, updatingAgentId, updates);
if (!success) {
return {
success: false,
error: `Context ${contextId} not found or could not be updated`
};
}
return {
success: true,
contextId,
updatingAgentId,
message: 'Context updated successfully and shared with relevant agents',
collaborativeNote: 'Bidirectional context sharing enables collaborative refinement of shared understanding',
reminder: 'Other agents have been notified of this update and can build upon these insights'
};
}
/**
* Setup global context monitoring
*/
setupGlobalContextMonitoring() {
// Monitor for critical context gaps
this.contextManager.on('agent_context_stale', (event) => {
console.warn(`⚠️ CONTEXT SHARING ALERT: Agent ${event.agentId} has stale context (${Math.round(event.timeSinceSync / 60000)} minutes since last sync)`);
});
// Monitor for missed critical context
this.contextManager.on('acknowledgment_timeout', (event) => {
console.error(`🚨 CRITICAL: Context ${event.contextId} requiring acknowledgment was not acknowledged by agents: ${event.targetAgents.join(', ')}`);
});
// Monitor successful sharing
this.contextManager.on('context_shared', (event) => {
if (event.contextEntry.priority === 'critical') {
console.log(`✅ CRITICAL context shared: ${event.contextEntry.content.title} -> ${event.targetAgents.length} agents`);
}
});
}
}
//# sourceMappingURL=context-sharing-handler.js.map