// MCP Tools for Multi-Agent Production Management
import { productionOrchestrator } from '../agents/orchestrator.js';
import { agentRegistry } from '../agents/agent-registry.js';
const agentManagementTools = {
// Tool 1: Run complete automated production workflow
run_automated_production: {
name: "run_automated_production",
description: "Execute complete automated puppet production with multi-agent oversight, quality control, and documentation.",
inputSchema: {
type: "object",
properties: {
name: {
type: "string",
description: "Name of the production project"
},
description: {
type: "string",
description: "Description of the production"
},
character_image_path: {
type: "string",
description: "Path to character image file to process"
},
character_name: {
type: "string",
description: "Name of the character"
},
storyline_id: {
type: "integer",
description: "Optional: Link to existing storyline ID"
},
production_type: {
type: "string",
description: "Type of production: full_production, character_only, script_only",
default: "full_production"
},
duration_target: {
type: "string",
description: "Target duration for final production",
default: "30-60 seconds"
},
style: {
type: "string",
description: "Production style preference",
default: "Puppet animation"
},
quality_level: {
type: "string",
description: "Quality control strictness: standard, high, maximum",
default: "standard"
}
},
required: ["name", "description", "character_image_path", "character_name"]
},
handler: async (args) => {
try {
console.log('🎬 Starting automated production workflow with multi-agent oversight...');
// Initialize orchestrator
await productionOrchestrator.initialize();
// Create workflow specification
const workflowSpec = {
name: args.name,
description: args.description,
characterName: args.character_name,
characterImagePath: args.character_image_path,
storylineId: args.storyline_id,
type: args.production_type || 'full_production',
durationTarget: args.duration_target || '30-60 seconds',
style: args.style || 'Puppet animation',
qualityLevel: args.quality_level || 'standard'
};
// Run the complete production workflow
const result = await productionOrchestrator.runProductionWorkflow(workflowSpec);
if (result.success) {
return {
success: true,
workflow_id: result.workflow.id,
workflow_name: result.workflow.name,
production_results: result.results,
final_approval: result.finalApproval,
message: `✅ Automated production "${args.name}" completed successfully with full agent oversight!`,
next_steps: [
"Review final production documentation",
"Execute FFmpeg commands for video assembly",
"Perform final quality review",
"Deliver completed production"
],
statistics: {
completed_tasks: result.results.completedTasks.length,
generated_artifacts: result.results.artifacts.length,
total_approvals: result.results.approvals.length,
errors_encountered: result.results.errors.length,
success_rate: result.results.completedTasks.length > 0 ?
((result.results.completedTasks.length /
(result.results.completedTasks.length + result.results.errors.length)) * 100).toFixed(1) : 0
}
};
} else {
return {
success: false,
workflow_id: result.workflow?.id || null,
error: result.error,
errors: result.errors || [],
message: `❌ Automated production "${args.name}" failed: ${result.error}`,
next_steps: [
"Review error details and resolve issues",
"Check agent configurations and API keys",
"Retry production with corrected parameters"
]
};
}
} catch (error) {
return {
success: false,
error: error.message,
message: `❌ Production orchestrator failed: ${error.message}`
};
}
}
},
// Tool 2: Get production workflow status
get_production_status: {
name: "get_production_status",
description: "Get detailed status of a production workflow including agent activities, approvals, and progress.",
inputSchema: {
type: "object",
properties: {
workflow_id: {
type: "integer",
description: "ID of the workflow to check status for"
}
},
required: ["workflow_id"]
},
handler: async (args) => {
try {
const { Pool } = await import('pg');
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
// Get comprehensive workflow status
const statusQuery = `
SELECT w.*,
(SELECT COUNT(*) FROM tasks WHERE workflow_id = w.id) as total_tasks,
(SELECT COUNT(*) FROM tasks WHERE workflow_id = w.id AND status = 'approved') as approved_tasks,
(SELECT COUNT(*) FROM tasks WHERE workflow_id = w.id AND status = 'failed') as failed_tasks,
(SELECT COUNT(*) FROM artifacts a JOIN tasks t ON a.task_id = t.id WHERE t.workflow_id = w.id) as total_artifacts,
(SELECT COUNT(*) FROM approvals ap JOIN tasks t ON ap.task_id = t.id WHERE t.workflow_id = w.id) as total_approvals
FROM workflows w
WHERE w.id = $1
`;
const workflowResult = await pool.query(statusQuery, [args.workflow_id]);
if (workflowResult.rows.length === 0) {
return {
success: false,
error: "Workflow not found",
message: `❌ Workflow with ID ${args.workflow_id} not found`
};
}
const workflow = workflowResult.rows[0];
// Get task details
const tasksQuery = `
SELECT t.*,
(SELECT COUNT(*) FROM approvals WHERE task_id = t.id) as approval_count,
(SELECT COUNT(*) FROM artifacts WHERE task_id = t.id) as artifact_count,
a.name as assigned_agent_name
FROM tasks t
LEFT JOIN agents a ON t.assigned_agent_id = a.id
WHERE t.workflow_id = $1
ORDER BY t.created_at
`;
const tasksResult = await pool.query(tasksQuery, [args.workflow_id]);
// Get recent agent activity
const activityQuery = `
SELECT te.*, t.step as task_step, a.name as agent_name
FROM task_events te
JOIN tasks t ON te.task_id = t.id
JOIN agents a ON te.agent_id = a.id
WHERE t.workflow_id = $1
ORDER BY te.created_at DESC
LIMIT 10
`;
const activityResult = await pool.query(activityQuery, [args.workflow_id]);
await pool.end();
const progressPercentage = workflow.total_tasks > 0 ?
((workflow.approved_tasks / workflow.total_tasks) * 100).toFixed(1) : 0;
return {
success: true,
workflow: {
id: workflow.id,
name: workflow.name,
description: workflow.description,
status: workflow.status,
created_at: workflow.created_at,
completed_at: workflow.completed_at
},
progress: {
total_tasks: workflow.total_tasks,
approved_tasks: workflow.approved_tasks,
failed_tasks: workflow.failed_tasks,
progress_percentage: progressPercentage,
total_artifacts: workflow.total_artifacts,
total_approvals: workflow.total_approvals
},
tasks: tasksResult.rows,
recent_activity: activityResult.rows,
message: `📊 Workflow "${workflow.name}" is ${workflow.status} (${progressPercentage}% complete)`
};
} catch (error) {
return {
success: false,
error: error.message,
message: `❌ Failed to get production status: ${error.message}`
};
}
}
},
// Tool 3: Get agent performance and resource usage
get_agent_status: {
name: "get_agent_status",
description: "Get status and performance metrics for all agents in the production system.",
inputSchema: {
type: "object",
properties: {
agent_name: {
type: "string",
description: "Optional: specific agent name to get detailed status for"
}
}
},
handler: async (args) => {
try {
// Initialize agent registry
await agentRegistry.initialize();
if (args.agent_name) {
// Get specific agent details
const agent = agentRegistry.getAgent(args.agent_name);
const resourceUsage = agentRegistry.getResourceUsage(args.agent_name);
const capabilities = agentRegistry.getAgentCapabilities(args.agent_name);
return {
success: true,
agent: {
name: agent.name,
role: agent.role,
provider: agent.provider,
status: 'active',
capabilities: capabilities,
resource_usage: resourceUsage
},
message: `🤖 Agent "${args.agent_name}" status retrieved`
};
} else {
// Get all agents overview
const allAgents = agentRegistry.getAllAgents();
const agentStatus = allAgents.map(agent => {
const resourceUsage = agentRegistry.getResourceUsage(agent.name);
return {
name: agent.name,
role: agent.role,
provider: agent.provider,
status: 'active',
resource_usage: resourceUsage,
capabilities_count: agent.capabilities.length
};
});
// Get system statistics
const { Pool } = await import('pg');
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const statsQuery = `
SELECT
(SELECT COUNT(*) FROM workflows WHERE status = 'completed') as completed_workflows,
(SELECT COUNT(*) FROM workflows WHERE status IN ('draft', 'pending')) as active_workflows,
(SELECT COUNT(*) FROM tasks WHERE status = 'approved') as approved_tasks,
(SELECT COUNT(*) FROM tasks WHERE status = 'failed') as failed_tasks,
(SELECT COUNT(*) FROM approvals WHERE status = 'approved') as total_approvals
`;
const statsResult = await pool.query(statsQuery);
const stats = statsResult.rows[0];
await pool.end();
return {
success: true,
agents: agentStatus,
system_statistics: {
total_agents: allAgents.length,
completed_workflows: parseInt(stats.completed_workflows),
active_workflows: parseInt(stats.active_workflows),
approved_tasks: parseInt(stats.approved_tasks),
failed_tasks: parseInt(stats.failed_tasks),
total_approvals: parseInt(stats.total_approvals)
},
message: `🤖 Retrieved status for ${allAgents.length} agents`
};
}
} catch (error) {
return {
success: false,
error: error.message,
message: `❌ Failed to get agent status: ${error.message}`
};
}
}
},
// Tool 4: Review and approve production manually
manual_production_review: {
name: "manual_production_review",
description: "Manually trigger review process for a specific production task with human oversight.",
inputSchema: {
type: "object",
properties: {
task_id: {
type: "integer",
description: "ID of the task to review"
},
review_stage: {
type: "string",
description: "Review stage: creative, brand, qa, final",
default: "creative"
},
override_decision: {
type: "string",
description: "Override decision: approve, reject, needs_revision"
},
review_notes: {
type: "string",
description: "Additional notes for the review"
}
},
required: ["task_id"]
},
handler: async (args) => {
try {
await productionOrchestrator.initialize();
// Get task details
const { Pool } = await import('pg');
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const taskQuery = `SELECT * FROM tasks WHERE id = $1`;
const taskResult = await pool.query(taskQuery, [args.task_id]);
if (taskResult.rows.length === 0) {
return {
success: false,
error: "Task not found",
message: `❌ Task with ID ${args.task_id} not found`
};
}
const task = taskResult.rows[0];
// Get task artifacts
const artifactsQuery = `SELECT * FROM artifacts WHERE task_id = $1`;
const artifactsResult = await pool.query(artifactsQuery, [args.task_id]);
await pool.end();
// Simulate artifact for review
const mockArtifact = {
id: artifactsResult.rows[0]?.id || 1,
task_id: task.id,
artifact_type: 'manual_review',
metadata: task.payload
};
let reviewResult;
// Perform appropriate review based on stage
switch (args.review_stage) {
case 'creative':
reviewResult = await productionOrchestrator.reviewBoard.creativeReview(
task,
mockArtifact,
task.payload
);
break;
case 'brand':
reviewResult = await productionOrchestrator.reviewBoard.brandReview(
task,
mockArtifact,
{ approved: true, feedback: "Previous review passed" }
);
break;
case 'qa':
reviewResult = await productionOrchestrator.reviewBoard.qaReview(
task,
mockArtifact,
{}
);
break;
case 'final':
// Get workflow for final review
const workflow = {
id: task.workflow_id,
name: `Workflow ${task.workflow_id}`,
description: "Manual review workflow"
};
const results = {
completedTasks: [task],
artifacts: artifactsResult.rows,
approvals: [],
errors: []
};
reviewResult = await productionOrchestrator.reviewBoard.finalReview(workflow, results);
break;
default:
throw new Error(`Unknown review stage: ${args.review_stage}`);
}
// Apply manual override if specified
if (args.override_decision) {
reviewResult.approved = args.override_decision === 'approve';
reviewResult.manual_override = true;
reviewResult.override_notes = args.review_notes;
}
// Record the review
await productionOrchestrator.docControl.recordApproval(task, {
[args.review_stage]: reviewResult
});
return {
success: true,
task_id: args.task_id,
review_stage: args.review_stage,
review_result: reviewResult,
override_applied: !!args.override_decision,
message: `🔍 ${args.review_stage} review completed for task ${args.task_id}: ${reviewResult.approved ? 'APPROVED' : 'NEEDS REVISION'}`
};
} catch (error) {
return {
success: false,
error: error.message,
message: `❌ Manual review failed: ${error.message}`
};
}
}
}
};
// Export tool definitions for MCP server registration
export const getAgentManagementToolDefinitions = () => {
return Object.values(agentManagementTools).map(tool => ({
name: tool.name,
description: tool.description,
inputSchema: tool.inputSchema
}));
};
// Export tool handlers for MCP server execution
export const getAgentManagementToolHandlers = () => {
const handlers = {};
Object.values(agentManagementTools).forEach(tool => {
handlers[tool.name] = tool.handler;
});
return handlers;
};
export default agentManagementTools;