import { activeSessions, sessionMcpServers, } from "../../hub.js";
import { toolAttachedResources } from "../../installResourcesFeature.js";
import { consolidateWorkflowEntry, MemoryConsolidationContext } from "../../memoryUtils.js";
export async function triggerAttachedResources(sessionId: string, toolName: string, toolArgs: any, toolResult: any, success: boolean) {
const toolContext = {
toolName,
arguments: toolArgs,
result: toolResult,
timestamp: Date.now(),
success
};
console.error(`Triggering resources for tool: ${toolName}, session: ${sessionId}`);
// Find resources attached to this tool
const attachedResources = toolAttachedResources.filter(resource =>
resource.attachedToTools.includes("*") ||
resource.attachedToTools.includes(toolName)
);
console.error(`Found ${attachedResources.length} resources attached to ${toolName}`);
// Get the fresh session data after tool completion
const currentSession = activeSessions.get(sessionId);
if (!currentSession) {
console.error(`No session found for ${sessionId} during resource trigger`);
return;
}
// Update each attached resource and notify clients
for (const resource of attachedResources) {
try {
console.error(`Updating resource: ${resource.resourceName} for tool: ${toolName}`);
// Execute the resource handler with fresh session data and tool context
await resource.handler(sessionId, toolContext);
// Send resource updated notification to all connected sessions
for (const [, mcpServer] of sessionMcpServers) {
try {
await mcpServer.server.sendResourceUpdated({ uri: resource.uri });
console.error(`Sent resource update notification for ${resource.uri}`);
} catch (notifyError) {
console.error(`Failed to send resource update notification for ${resource.uri}:`, notifyError);
}
}
} catch (error) {
console.error(`Failed to update resource ${resource.resourceName}:`, error);
}
}
// Final consolidation step: ensure no duplicates in workflow history
// This happens AFTER all resources have been processed
const session = activeSessions.get(sessionId);
if (session?.memory?.insights) {
const consolidationContext: MemoryConsolidationContext = {
toolName,
success,
timestamp: toolContext.timestamp,
arguments: toolArgs
};
// Use the enhanced consolidation to prevent duplicates and add unique IDs
consolidateWorkflowEntry(session.memory.insights, consolidationContext);
console.error(`Post-consolidation: ${toolName} processed for session ${sessionId}`);
}
}