#!/usr/bin/env node
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { CallToolRequestSchema, ListToolsRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
import { ProjectAnalysisSchema, ImplementationPlanSchema } from './types.js';
import * as net from 'net';
class AgentMCPServer {
    server;
    analysisResults = new Map();
    agentInteractions = new Map();
    tcpClient = null;
    agentPort;
    constructor() {
        // Agent TCP port from environment variable or default
        this.agentPort = parseInt(process.env.AGENT_TCP_PORT || '8549');
        this.server = new Server({
            name: 'task-shepherd-agent-mcp',
            version: '1.0.0',
        }, {
            capabilities: {
                tools: {},
            },
        });
        this.setupToolHandlers();
        this.setupErrorHandling();
    }
    setupToolHandlers() {
        this.server.setRequestHandler(ListToolsRequestSchema, async () => ({
            tools: [
                {
                    name: 'submit_project_analysis',
                    description: 'Submit structured project analysis results from Claude',
                    inputSchema: {
                        type: 'object',
                        properties: {
                            project_id: {
                                type: 'string',
                                description: 'Unique identifier for the project being analyzed'
                            },
                            analysis_type: {
                                type: 'string',
                                enum: ['project_review', 'development_plan', 'story_implementation'],
                                description: 'Type of analysis being performed'
                            },
                            executive_summary: {
                                type: 'string',
                                description: 'High-level summary of the analysis findings'
                            },
                            analysis: {
                                type: 'object',
                                properties: {
                                    strengths: {
                                        type: 'array',
                                        items: {
                                            type: 'object',
                                            properties: {
                                                title: { type: 'string' },
                                                description: { type: 'string' },
                                                impact: { type: 'string', enum: ['low', 'medium', 'high'] },
                                                evidence: { type: 'array', items: { type: 'string' } }
                                            },
                                            required: ['title', 'description', 'impact']
                                        }
                                    },
                                    weaknesses: {
                                        type: 'array',
                                        items: {
                                            type: 'object',
                                            properties: {
                                                title: { type: 'string' },
                                                description: { type: 'string' },
                                                severity: { type: 'string', enum: ['low', 'medium', 'high'] },
                                                affected_areas: { type: 'array', items: { type: 'string' } },
                                                improvement_effort: { type: 'string', enum: ['minimal', 'moderate', 'significant'] }
                                            },
                                            required: ['title', 'description', 'severity']
                                        }
                                    },
                                    risks: {
                                        type: 'array',
                                        items: {
                                            type: 'object',
                                            properties: {
                                                title: { type: 'string' },
                                                description: { type: 'string' },
                                                probability: { type: 'string', enum: ['low', 'medium', 'high'] },
                                                impact: { type: 'string', enum: ['low', 'medium', 'high'] },
                                                mitigation_strategy: { type: 'string' }
                                            },
                                            required: ['title', 'description', 'probability', 'impact']
                                        }
                                    },
                                    opportunities: {
                                        type: 'array',
                                        items: {
                                            type: 'object',
                                            properties: {
                                                title: { type: 'string' },
                                                description: { type: 'string' },
                                                potential_value: { type: 'string', enum: ['low', 'medium', 'high'] },
                                                implementation_complexity: { type: 'string', enum: ['simple', 'moderate', 'complex'] }
                                            },
                                            required: ['title', 'description', 'potential_value']
                                        }
                                    }
                                },
                                required: ['strengths', 'weaknesses', 'risks', 'opportunities']
                            },
                            scores: {
                                type: 'object',
                                properties: {
                                    completeness: {
                                        type: 'object',
                                        properties: {
                                            score: { type: 'number', minimum: 0, maximum: 100 },
                                            reasoning: { type: 'string' }
                                        },
                                        required: ['score', 'reasoning']
                                    },
                                    clarity: {
                                        type: 'object',
                                        properties: {
                                            score: { type: 'number', minimum: 0, maximum: 100 },
                                            reasoning: { type: 'string' }
                                        },
                                        required: ['score', 'reasoning']
                                    },
                                    feasibility: {
                                        type: 'object',
                                        properties: {
                                            score: { type: 'number', minimum: 0, maximum: 100 },
                                            reasoning: { type: 'string' }
                                        },
                                        required: ['score', 'reasoning']
                                    },
                                    overall: {
                                        type: 'object',
                                        properties: {
                                            score: { type: 'number', minimum: 0, maximum: 100 },
                                            reasoning: { type: 'string' }
                                        },
                                        required: ['score', 'reasoning']
                                    }
                                },
                                required: ['completeness', 'clarity', 'feasibility', 'overall']
                            },
                            recommendations: {
                                type: 'array',
                                items: {
                                    type: 'object',
                                    properties: {
                                        id: { type: 'string' },
                                        category: {
                                            type: 'string',
                                            enum: ['requirements', 'architecture', 'security', 'performance', 'maintainability', 'testing']
                                        },
                                        title: { type: 'string' },
                                        description: { type: 'string' },
                                        implementation_guide: { type: 'string' },
                                        priority: { type: 'string', enum: ['low', 'medium', 'high', 'critical'] },
                                        estimated_effort: { type: 'string' },
                                        business_impact: { type: 'string' },
                                        technical_complexity: { type: 'string', enum: ['simple', 'moderate', 'complex'] }
                                    },
                                    required: ['id', 'category', 'title', 'description', 'priority']
                                }
                            },
                            timeline: {
                                type: 'object',
                                properties: {
                                    total_duration_weeks: { type: 'number' },
                                    phases: {
                                        type: 'array',
                                        items: {
                                            type: 'object',
                                            properties: {
                                                id: { type: 'string' },
                                                name: { type: 'string' },
                                                description: { type: 'string' },
                                                duration_weeks: { type: 'number' },
                                                start_week: { type: 'number' },
                                                dependencies: {
                                                    type: 'array',
                                                    items: { type: 'string' }
                                                },
                                                deliverables: {
                                                    type: 'array',
                                                    items: { type: 'string' }
                                                },
                                                key_milestones: {
                                                    type: 'array',
                                                    items: { type: 'string' }
                                                },
                                                resources_required: {
                                                    type: 'array',
                                                    items: { type: 'string' }
                                                },
                                                risks: {
                                                    type: 'array',
                                                    items: { type: 'string' }
                                                }
                                            },
                                            required: ['id', 'name', 'description', 'duration_weeks', 'start_week']
                                        }
                                    }
                                },
                                required: ['total_duration_weeks', 'phases']
                            },
                            suggested_product_requirements: {
                                type: 'object',
                                properties: {
                                    explicit_requirements: {
                                        type: 'array',
                                        items: {
                                            type: 'object',
                                            properties: {
                                                requirement: { type: 'string' },
                                                source_text: { type: 'string' },
                                                confidence: { type: 'string', enum: ['high', 'medium', 'low'] }
                                            },
                                            required: ['requirement', 'source_text', 'confidence']
                                        }
                                    },
                                    inferred_functional_requirements: {
                                        type: 'array',
                                        items: {
                                            type: 'object',
                                            properties: {
                                                requirement: { type: 'string' },
                                                rationale: { type: 'string' },
                                                domain_pattern: { type: 'string' },
                                                priority: { type: 'string', enum: ['critical', 'high', 'medium', 'low'] }
                                            },
                                            required: ['requirement', 'rationale', 'domain_pattern', 'priority']
                                        }
                                    },
                                    suggested_non_functional_requirements: {
                                        type: 'array',
                                        items: {
                                            type: 'object',
                                            properties: {
                                                category: { type: 'string' },
                                                requirement: { type: 'string' },
                                                industry_standard: { type: 'boolean' },
                                                customization_needed: { type: 'boolean' }
                                            },
                                            required: ['category', 'requirement', 'industry_standard', 'customization_needed']
                                        }
                                    },
                                    requirements_clarification_questions: {
                                        type: 'array',
                                        items: {
                                            type: 'object',
                                            properties: {
                                                category: { type: 'string' },
                                                question: { type: 'string' },
                                                impact_if_unclear: { type: 'string' },
                                                suggested_default: { type: 'string' }
                                            },
                                            required: ['category', 'question', 'impact_if_unclear', 'suggested_default']
                                        }
                                    }
                                },
                                required: ['explicit_requirements', 'inferred_functional_requirements', 'suggested_non_functional_requirements', 'requirements_clarification_questions']
                            },
                            metadata: {
                                type: 'object',
                                properties: {
                                    analysis_duration_seconds: { type: 'number' },
                                    claude_model: { type: 'string' },
                                    confidence_level: { type: 'number', minimum: 0, maximum: 1 },
                                    analysis_timestamp: { type: 'string' },
                                    reviewer_notes: { type: 'string' }
                                },
                                required: ['analysis_duration_seconds', 'claude_model', 'confidence_level', 'analysis_timestamp']
                            }
                        },
                        required: ['project_id', 'analysis_type', 'executive_summary', 'analysis', 'scores', 'recommendations', 'timeline', 'suggested_product_requirements', 'metadata']
                    }
                },
                {
                    name: 'get_analysis_result',
                    description: 'Retrieve a previously submitted analysis result',
                    inputSchema: {
                        type: 'object',
                        properties: {
                            project_id: {
                                type: 'string',
                                description: 'Unique identifier for the project'
                            }
                        },
                        required: ['project_id']
                    }
                },
                {
                    name: 'submit_implementation_plan',
                    description: 'Submit structured implementation plan analysis results from Claude',
                    inputSchema: {
                        type: 'object',
                        properties: {
                            project_id: {
                                type: 'string',
                                description: 'Unique identifier for the project being analyzed'
                            },
                            analysis_type: {
                                type: 'string',
                                enum: ['implementation_plan'],
                                description: 'Type of analysis being performed'
                            },
                            executive_summary: {
                                type: 'string',
                                description: 'High-level summary of the implementation plan findings'
                            },
                            analysis: {
                                type: 'object',
                                properties: {
                                    strengths: {
                                        type: 'array',
                                        items: {
                                            type: 'object',
                                            properties: {
                                                title: { type: 'string' },
                                                description: { type: 'string' },
                                                impact: { type: 'string', enum: ['low', 'medium', 'high'] },
                                                evidence: { type: 'array', items: { type: 'string' } }
                                            },
                                            required: ['title', 'description', 'impact']
                                        }
                                    },
                                    weaknesses: {
                                        type: 'array',
                                        items: {
                                            type: 'object',
                                            properties: {
                                                title: { type: 'string' },
                                                description: { type: 'string' },
                                                severity: { type: 'string', enum: ['low', 'medium', 'high'] },
                                                affected_areas: { type: 'array', items: { type: 'string' } },
                                                improvement_effort: { type: 'string', enum: ['minimal', 'moderate', 'significant'] }
                                            },
                                            required: ['title', 'description', 'severity']
                                        }
                                    },
                                    risks: {
                                        type: 'array',
                                        items: {
                                            type: 'object',
                                            properties: {
                                                title: { type: 'string' },
                                                description: { type: 'string' },
                                                probability: { type: 'string', enum: ['low', 'medium', 'high'] },
                                                impact: { type: 'string', enum: ['low', 'medium', 'high'] },
                                                mitigation_strategy: { type: 'string' }
                                            },
                                            required: ['title', 'description', 'probability', 'impact']
                                        }
                                    },
                                    opportunities: {
                                        type: 'array',
                                        items: {
                                            type: 'object',
                                            properties: {
                                                title: { type: 'string' },
                                                description: { type: 'string' },
                                                potential_value: { type: 'string', enum: ['low', 'medium', 'high'] },
                                                implementation_complexity: { type: 'string', enum: ['simple', 'moderate', 'complex'] }
                                            },
                                            required: ['title', 'description', 'potential_value']
                                        }
                                    }
                                },
                                required: ['strengths', 'weaknesses', 'risks', 'opportunities']
                            },
                            scores: {
                                type: 'object',
                                properties: {
                                    completeness: {
                                        type: 'object',
                                        properties: {
                                            score: { type: 'number', minimum: 0, maximum: 100 },
                                            reasoning: { type: 'string' }
                                        },
                                        required: ['score', 'reasoning']
                                    },
                                    clarity: {
                                        type: 'object',
                                        properties: {
                                            score: { type: 'number', minimum: 0, maximum: 100 },
                                            reasoning: { type: 'string' }
                                        },
                                        required: ['score', 'reasoning']
                                    },
                                    feasibility: {
                                        type: 'object',
                                        properties: {
                                            score: { type: 'number', minimum: 0, maximum: 100 },
                                            reasoning: { type: 'string' }
                                        },
                                        required: ['score', 'reasoning']
                                    },
                                    overall: {
                                        type: 'object',
                                        properties: {
                                            score: { type: 'number', minimum: 0, maximum: 100 },
                                            reasoning: { type: 'string' }
                                        },
                                        required: ['score', 'reasoning']
                                    }
                                },
                                required: ['completeness', 'clarity', 'feasibility', 'overall']
                            },
                            recommendations: {
                                type: 'array',
                                items: {
                                    type: 'object',
                                    properties: {
                                        id: { type: 'string' },
                                        category: { type: 'string', enum: ['requirements', 'architecture', 'security', 'performance', 'maintainability', 'testing'] },
                                        title: { type: 'string' },
                                        description: { type: 'string' },
                                        priority: { type: 'string', enum: ['low', 'medium', 'high', 'critical'] },
                                        implementation_guide: { type: 'string' },
                                        estimated_effort: { type: 'string' },
                                        business_impact: { type: 'string' },
                                        technical_complexity: { type: 'string', enum: ['simple', 'moderate', 'complex'] }
                                    },
                                    required: ['id', 'category', 'title', 'description', 'priority']
                                }
                            },
                            timeline: {
                                type: 'object',
                                properties: {
                                    total_duration_weeks: { type: 'number' },
                                    phases: {
                                        type: 'array',
                                        items: {
                                            type: 'object',
                                            properties: {
                                                id: { type: 'string' },
                                                name: { type: 'string' },
                                                description: { type: 'string' },
                                                duration_weeks: { type: 'number' },
                                                start_week: { type: 'number' },
                                                dependencies: {
                                                    type: 'array',
                                                    items: { type: 'string' }
                                                },
                                                deliverables: {
                                                    type: 'array',
                                                    items: { type: 'string' }
                                                },
                                                key_milestones: {
                                                    type: 'array',
                                                    items: { type: 'string' }
                                                },
                                                resources_required: {
                                                    type: 'array',
                                                    items: { type: 'string' }
                                                },
                                                risks: {
                                                    type: 'array',
                                                    items: { type: 'string' }
                                                }
                                            },
                                            required: ['id', 'name', 'description', 'duration_weeks', 'start_week']
                                        }
                                    }
                                },
                                required: ['total_duration_weeks', 'phases']
                            },
                            suggested_product_requirements: {
                                type: 'object',
                                properties: {
                                    explicit_requirements: {
                                        type: 'array',
                                        items: {
                                            type: 'object',
                                            properties: {
                                                requirement: { type: 'string' },
                                                source_text: { type: 'string' },
                                                confidence: { type: 'string', enum: ['high', 'medium', 'low'] }
                                            },
                                            required: ['requirement', 'source_text', 'confidence']
                                        }
                                    },
                                    inferred_functional_requirements: {
                                        type: 'array',
                                        items: {
                                            type: 'object',
                                            properties: {
                                                requirement: { type: 'string' },
                                                rationale: { type: 'string' },
                                                domain_pattern: { type: 'string' },
                                                priority: { type: 'string', enum: ['critical', 'high', 'medium', 'low'] }
                                            },
                                            required: ['requirement', 'rationale', 'domain_pattern', 'priority']
                                        }
                                    },
                                    suggested_non_functional_requirements: {
                                        type: 'array',
                                        items: {
                                            type: 'object',
                                            properties: {
                                                category: { type: 'string' },
                                                requirement: { type: 'string' },
                                                industry_standard: { type: 'boolean' },
                                                customization_needed: { type: 'boolean' }
                                            },
                                            required: ['category', 'requirement', 'industry_standard', 'customization_needed']
                                        }
                                    },
                                    requirements_clarification_questions: {
                                        type: 'array',
                                        items: {
                                            type: 'object',
                                            properties: {
                                                category: { type: 'string' },
                                                question: { type: 'string' },
                                                impact_if_unclear: { type: 'string' },
                                                suggested_default: { type: 'string' }
                                            },
                                            required: ['category', 'question', 'impact_if_unclear', 'suggested_default']
                                        }
                                    }
                                },
                                required: ['explicit_requirements', 'inferred_functional_requirements', 'suggested_non_functional_requirements', 'requirements_clarification_questions']
                            },
                            metadata: {
                                type: 'object',
                                properties: {
                                    analysis_duration_seconds: { type: 'number' },
                                    claude_model: { type: 'string' },
                                    confidence_level: { type: 'number', minimum: 0, maximum: 1 },
                                    analysis_timestamp: { type: 'string' },
                                    reviewer_notes: { type: 'string' }
                                },
                                required: ['analysis_duration_seconds', 'claude_model', 'confidence_level', 'analysis_timestamp']
                            }
                        },
                        required: ['project_id', 'analysis_type', 'executive_summary', 'analysis', 'scores', 'recommendations', 'timeline', 'suggested_product_requirements', 'metadata']
                    }
                },
                {
                    name: 'submit_task_implementation',
                    description: 'Submit structured implementation results for a task',
                    inputSchema: {
                        type: 'object',
                        properties: {
                            task_id: {
                                type: 'string',
                                description: 'Unique identifier for the task'
                            },
                            implementation_summary: {
                                type: 'string',
                                description: 'Summary of what was implemented'
                            },
                            files_modified: {
                                type: 'array',
                                items: {
                                    type: 'object',
                                    properties: {
                                        path: { type: 'string' },
                                        change_type: { type: 'string', enum: ['created', 'modified', 'deleted'] },
                                        summary: { type: 'string' }
                                    },
                                    required: ['path', 'change_type', 'summary']
                                }
                            },
                            tests_added: {
                                type: 'array',
                                items: { type: 'string' },
                                description: 'List of test files or test descriptions'
                            },
                            completion_status: {
                                type: 'string',
                                enum: ['completed', 'partial', 'blocked'],
                                description: 'Status of task completion'
                            },
                            blockers: {
                                type: 'array',
                                items: { type: 'string' },
                                description: 'Any blockers encountered'
                            }
                        },
                        required: ['task_id', 'implementation_summary', 'files_modified', 'completion_status']
                    }
                },
                {
                    name: 'submit_story_progress',
                    description: 'Submit progress update for a story implementation',
                    inputSchema: {
                        type: 'object',
                        properties: {
                            story_id: {
                                type: 'string',
                                description: 'Unique identifier for the story'
                            },
                            tasks_completed: {
                                type: 'array',
                                items: { type: 'string' },
                                description: 'IDs of completed tasks'
                            },
                            tasks_remaining: {
                                type: 'array',
                                items: { type: 'string' },
                                description: 'IDs of remaining tasks'
                            },
                            overall_progress: {
                                type: 'number',
                                minimum: 0,
                                maximum: 100,
                                description: 'Overall completion percentage'
                            },
                            status_summary: {
                                type: 'string',
                                description: 'Current status summary'
                            },
                            next_steps: {
                                type: 'array',
                                items: { type: 'string' },
                                description: 'Next steps to be taken'
                            }
                        },
                        required: ['story_id', 'overall_progress', 'status_summary']
                    }
                }
            ]
        }));
        this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
            const { name, arguments: args } = request.params;
            console.error(`[MCP] Tool called: ${name}`);
            console.error(`[MCP] Args received:`, JSON.stringify(args, null, 2));
            console.error(`[MCP] Args keys:`, Object.keys(args || {}));
            console.error(`[MCP] Args stringified length:`, JSON.stringify(args).length);
            if (name === 'submit_project_analysis') {
                try {
                    console.error(`[MCP] Starting validation of analysis data`);
                    // Validate the analysis data
                    const validatedAnalysis = ProjectAnalysisSchema.parse(args);
                    console.error(`[MCP] Validation successful, storing result`);
                    // Store the analysis result
                    this.analysisResults.set(validatedAnalysis.project_id, validatedAnalysis);
                    console.error(`[MCP] Sending to agent via TCP`);
                    // Send to agent via TCP
                    await this.sendToAgent({
                        type: 'analysis_complete',
                        projectId: validatedAnalysis.project_id,
                        analysisType: validatedAnalysis.analysis_type,
                        data: validatedAnalysis
                    });
                    console.error(`[MCP] TCP send completed, returning success response`);
                    // Return success response with summary
                    return {
                        content: [
                            {
                                type: 'text',
                                text: JSON.stringify({
                                    success: true,
                                    project_id: validatedAnalysis.project_id,
                                    analysis_type: validatedAnalysis.analysis_type,
                                    summary: {
                                        overall_score: validatedAnalysis.scores.overall.score,
                                        strengths_count: validatedAnalysis.analysis.strengths.length,
                                        weaknesses_count: validatedAnalysis.analysis.weaknesses.length,
                                        risks_count: validatedAnalysis.analysis.risks.length,
                                        recommendations_count: validatedAnalysis.recommendations.length
                                    },
                                    message: 'Analysis submitted successfully and validated.'
                                }, null, 2)
                            }
                        ]
                    };
                }
                catch (error) {
                    console.error(`[MCP] Error in submit_project_analysis:`, error);
                    return {
                        content: [
                            {
                                type: 'text',
                                text: JSON.stringify({
                                    success: false,
                                    error: 'Validation failed',
                                    details: error instanceof Error ? error.message : 'Unknown error',
                                    help: 'Please ensure all required fields are provided with correct types and values.'
                                }, null, 2)
                            }
                        ]
                    };
                }
            }
            if (name === 'submit_implementation_plan') {
                try {
                    console.error(`[MCP] Starting validation of implementation plan data`);
                    // Validate the implementation plan data using the specific schema
                    const validatedPlan = ImplementationPlanSchema.parse(args);
                    console.error(`[MCP] Validation successful, storing implementation plan result`);
                    // Store the implementation plan result with a different key pattern
                    this.analysisResults.set(`impl_plan_${validatedPlan.project_id}`, validatedPlan);
                    console.error(`[MCP] Sending implementation plan to agent via TCP`);
                    // Send to agent via TCP
                    await this.sendToAgent({
                        type: 'implementation_plan_complete',
                        projectId: validatedPlan.project_id,
                        analysisType: validatedPlan.analysis_type,
                        data: validatedPlan
                    });
                    console.error(`[MCP] TCP send completed, returning success response`);
                    // Return success response with summary
                    return {
                        content: [
                            {
                                type: 'text',
                                text: JSON.stringify({
                                    success: true,
                                    project_id: validatedPlan.project_id,
                                    analysis_type: validatedPlan.analysis_type,
                                    summary: {
                                        executive_summary_length: validatedPlan.executive_summary.length,
                                        strengths_count: validatedPlan.analysis.strengths.length,
                                        weaknesses_count: validatedPlan.analysis.weaknesses.length,
                                        risks_count: validatedPlan.analysis.risks.length,
                                        recommendations_count: validatedPlan.recommendations.length,
                                        timeline_phases: validatedPlan.timeline.phases.length,
                                        overall_score: validatedPlan.scores.overall.score
                                    },
                                    message: 'Implementation plan submitted successfully and validated.'
                                }, null, 2)
                            }
                        ]
                    };
                }
                catch (error) {
                    console.error(`[MCP] Error in submit_implementation_plan:`, error);
                    return {
                        content: [
                            {
                                type: 'text',
                                text: JSON.stringify({
                                    success: false,
                                    error: 'Validation failed',
                                    details: error instanceof Error ? error.message : 'Unknown error',
                                    help: 'Please ensure all required fields are provided with correct types and values for the implementation plan.'
                                }, null, 2)
                            }
                        ]
                    };
                }
            }
            if (name === 'get_analysis_result') {
                const projectId = args?.project_id;
                const analysis = this.analysisResults.get(projectId);
                if (!analysis) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: JSON.stringify({
                                    success: false,
                                    error: 'Analysis not found',
                                    project_id: projectId
                                }, null, 2)
                            }
                        ]
                    };
                }
                return {
                    content: [
                        {
                            type: 'text',
                            text: JSON.stringify({
                                success: true,
                                analysis: analysis
                            }, null, 2)
                        }
                    ]
                };
            }
            if (name === 'submit_task_implementation') {
                try {
                    // Store task implementation data
                    this.agentInteractions.set(`task_${args?.task_id}`, args);
                    return {
                        content: [
                            {
                                type: 'text',
                                text: JSON.stringify({
                                    success: true,
                                    task_id: args?.task_id,
                                    completion_status: args?.completion_status,
                                    files_modified_count: args?.files_modified?.length || 0,
                                    message: 'Task implementation details submitted successfully.'
                                }, null, 2)
                            }
                        ]
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: JSON.stringify({
                                    success: false,
                                    error: 'Failed to submit task implementation',
                                    details: error instanceof Error ? error.message : 'Unknown error'
                                }, null, 2)
                            }
                        ]
                    };
                }
            }
            if (name === 'submit_story_progress') {
                try {
                    // Store story progress data
                    this.agentInteractions.set(`story_${args?.story_id}`, args);
                    return {
                        content: [
                            {
                                type: 'text',
                                text: JSON.stringify({
                                    success: true,
                                    story_id: args?.story_id,
                                    overall_progress: args?.overall_progress,
                                    tasks_completed: args?.tasks_completed?.length || 0,
                                    tasks_remaining: args?.tasks_remaining?.length || 0,
                                    message: 'Story progress submitted successfully.'
                                }, null, 2)
                            }
                        ]
                    };
                }
                catch (error) {
                    return {
                        content: [
                            {
                                type: 'text',
                                text: JSON.stringify({
                                    success: false,
                                    error: 'Failed to submit story progress',
                                    details: error instanceof Error ? error.message : 'Unknown error'
                                }, null, 2)
                            }
                        ]
                    };
                }
            }
            throw new Error(`Unknown tool: ${name}`);
        });
    }
    async connectToAgent() {
        return new Promise((resolve, reject) => {
            console.error(`Attempting to connect to agent TCP server on localhost:${this.agentPort}`);
            this.tcpClient = net.connect(this.agentPort, 'localhost', () => {
                console.error(`✓ Successfully connected to agent TCP server on port ${this.agentPort}`);
                resolve();
            });
            this.tcpClient.on('error', (error) => {
                console.error(`✗ TCP connection error to localhost:${this.agentPort}:`, error.message);
                this.tcpClient = null;
                reject(error);
            });
            this.tcpClient.on('close', () => {
                console.error(`TCP connection to agent closed`);
                this.tcpClient = null;
            });
            // Add connection timeout
            setTimeout(() => {
                if (this.tcpClient && !this.tcpClient.connecting && !this.tcpClient.readyState) {
                    console.error(`TCP connection timeout after 5 seconds`);
                    this.tcpClient.destroy();
                    reject(new Error('TCP connection timeout'));
                }
            }, 5000);
        });
    }
    async sendToAgent(message) {
        console.error(`Sending message to agent:`, { type: message.type, projectId: message.projectId });
        if (!this.tcpClient) {
            try {
                await this.connectToAgent();
            }
            catch (error) {
                console.error('Failed to connect to agent:', error);
                throw error; // Propagate error instead of silently returning
            }
        }
        if (this.tcpClient) {
            const messageStr = JSON.stringify(message) + '\n';
            console.error(`Writing message to TCP socket: ${messageStr.substring(0, 100)}...`);
            this.tcpClient.write(messageStr);
            console.error(`✓ Message sent to agent successfully`);
        }
        else {
            throw new Error('No TCP connection available to agent');
        }
    }
    setupErrorHandling() {
        this.server.onerror = (error) => {
            console.error('[MCP Error]', error);
        };
        process.on('SIGINT', async () => {
            if (this.tcpClient) {
                this.tcpClient.destroy();
            }
            await this.server.close();
            process.exit(0);
        });
    }
    async run() {
        const transport = new StdioServerTransport();
        await this.server.connect(transport);
        console.error('Task Shepherd Agent MCP Server running on stdio');
    }
}
const server = new AgentMCPServer();
server.run().catch(console.error);
