#!/usr/bin/env node
/**
* Debug Script: Ask-Multiple-Choice Tool
*
* Simulates ask-multiple-choice MCP tool behavior for UI development.
* Starts a mock server, sends realistic multiple-choice questions with options,
* waits for response, then outputs the formatted result that would be sent to the LLM.
*/
import { MockServer } from './shared/mock-server.js';
import { ResponseSimulator } from './shared/response-simulator.js';
import { mockAskMultipleChoiceData, mockResponses } from './shared/mock-data.js';
async function runDebugAskMultipleChoice(): Promise<void> {
const server = new MockServer(3000);
const simulator = new ResponseSimulator(server, {
responseDelay: 4000, // 4 seconds for more complex responses
simulateTyping: false
});
try {
// Start the mock server
await server.start();
console.error('[Debug] Ask-Multiple-Choice debug server started');
console.error('[Debug] Open http://localhost:3000 in your browser to see the UI');
console.error('[Debug] Waiting for UI connection...');
// Wait a moment for potential UI connection
await new Promise(resolve => setTimeout(resolve, 2000));
// Create the mock request
const requestId = `ask-multiple-choice-${Date.now()}`;
const mockRequest = {
id: requestId,
type: 'ask-multiple-choice',
data: {
...mockAskMultipleChoiceData,
timestamp: new Date().toISOString(),
context: {
debugMode: true,
session: 'debug-session'
}
},
timestamp: new Date().toISOString()
};
// Add the request (this triggers SSE to UI)
server.addRequest(mockRequest);
console.error(`[Debug] Sent ask-multiple-choice request: ${requestId}`);
console.error(`[Debug] Questions: ${mockAskMultipleChoiceData.questions.length} questions with multiple options each`);
// Set up response handler
const responsePromise = new Promise<any>((resolve) => {
server.once('response', (data) => {
resolve(data.response);
});
});
// Auto-simulate response after delay if no UI response
const autoResponsePromise = new Promise<any>(async (resolve) => {
await new Promise(r => setTimeout(r, 10000)); // Wait 10 seconds for complex questions
if (server.hasPendingRequests()) {
console.error('[Debug] No UI response received, using mock response');
const mockResponse = await simulator.simulateResponse(mockRequest);
resolve(mockResponse);
}
});
// Wait for either UI response or auto-response
const humanResponse = await Promise.race([responsePromise, autoResponsePromise]);
// Format the final result as it would be sent to LLM
const llmResult = formatAskMultipleChoiceResult(mockRequest, humanResponse);
// Output the result to stdout (this is what the LLM would receive)
console.log('='.repeat(80));
console.log('FORMATTED RESULT FOR LLM:');
console.log('='.repeat(80));
console.log(llmResult);
console.log('='.repeat(80));
} catch (error) {
console.error('[Debug] Error:', error);
process.exit(1);
} finally {
await server.stop();
console.error('[Debug] Ask-Multiple-Choice debug session completed');
process.exit(0);
}
}
/**
* Format the ask-multiple-choice result as it would be returned to the LLM
*/
function formatAskMultipleChoiceResult(request: any, response: any): string {
const questions = request.data.questions || [];
const responses = response.responses || [];
const completionStatus = response.completionStatus || 'done';
const generalComment = response.generalComment || '';
let result = `# Human Response to Multiple Choice Questions\n\n`;
// Add each question and its responses
questions.forEach((question: any, index: number) => {
result += `## Question ${index + 1}: ${question.text}\n\n`;
result += `**Available Options:** ${question.options.join(', ')}\n\n`;
const questionResponse = responses.find((r: any) => r.questionIndex === index);
if (questionResponse && questionResponse.selections) {
const selectedItems = questionResponse.selections.filter((s: any) => s.selected);
const unselectedItems = questionResponse.selections.filter((s: any) => !s.selected);
if (selectedItems.length > 0) {
result += `### ✅ Selected Options:\n\n`;
selectedItems.forEach((item: any) => {
const priorityEmoji = getPriorityEmoji(item.priority);
result += `- **${item.text}** ${priorityEmoji}\n`;
if (item.comment) {
result += ` - *${item.comment}*\n`;
}
});
result += `\n`;
}
if (unselectedItems.length > 0) {
result += `### ❌ Not Selected:\n\n`;
unselectedItems.forEach((item: any) => {
result += `- ${item.text}`;
if (item.comment) {
result += ` - *${item.comment}*`;
}
result += `\n`;
});
result += `\n`;
}
} else {
result += `*No response provided for this question*\n\n`;
}
});
// Add completion status and general comments
if (generalComment) {
result += `## General Comments\n\n${generalComment}\n\n`;
}
result += `## Completion Status\n\n`;
switch (completionStatus) {
case 'done':
result += `✅ **Complete** - Do not ask additional questions. Proceed with the selected options.\n\n`;
break;
case 'drill-deeper':
result += `🔍 **Needs More Detail** - The human wants to explore these topics further. Consider asking follow-up questions or use ask-one-question for deeper insights.\n\n`;
break;
case 'abort':
result += `⛔ **Aborted** - The human has decided not to proceed with these options. Consider alternative approaches.\n\n`;
break;
}
result += `## Summary\n\n`;
const totalSelected = responses.reduce((acc: number, r: any) =>
acc + (r.selections?.filter((s: any) => s.selected)?.length || 0), 0);
const totalQuestions = questions.length;
result += `- **Questions Asked:** ${totalQuestions}\n`;
result += `- **Total Selections:** ${totalSelected}\n`;
result += `- **Response Type:** Multiple choice with priorities and comments\n`;
result += `- **Session:** demo\n`;
result += `- **Timestamp:** ${new Date().toISOString()}\n\n`;
result += `---\n\n`;
result += `**Note:** Use the selected options and their priorities to guide your implementation decisions. High-priority items should be addressed first.`;
return result;
}
/**
* Get emoji representation for priority level
*/
function getPriorityEmoji(priority: string): string {
switch (priority?.toLowerCase()) {
case 'high': return '🔴 HIGH';
case 'medium': return '🟡 MEDIUM';
case 'low': return '🟢 LOW';
default: return '';
}
}
// CLI execution
if (require.main === module) {
console.error('[Debug] Starting Ask-Multiple-Choice debug session...');
runDebugAskMultipleChoice().catch(error => {
console.error('[Debug] Fatal error:', error);
process.exit(1);
});
}
export { runDebugAskMultipleChoice, formatAskMultipleChoiceResult };