auto_optimize
Transform natural language into optimized Claude Code prompts by analyzing and refining conversational text. Enables interactive questioning for clarity and context-specific improvements.
Instructions
Automatically detects and optimizes natural language text for Claude Code. Use this when the user is writing conversational text that should be translated into an optimized prompt.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| context | No | Any additional context about the current project or situation | |
| interactive | No | Whether to enable interactive questioning if the prompt is unclear or needs more info (default: auto-detect based on complexity) | |
| text | Yes | The natural language text to analyze and potentially optimize |
Implementation Reference
- index.ts:472-553 (handler)Core handler function that executes the auto_optimize tool logic: analyzes text, detects if optimization is needed, handles interactive questioning or direct optimization.async function autoOptimizeText( text: string, context?: string, forceInteractive?: boolean ): Promise<{ shouldOptimize: boolean; optimizedPrompt?: string; analysis: any; needsQuestions?: boolean; questions?: string[]; sessionId?: string; }> { const analysis = shouldAutoOptimize(text); if (!analysis.shouldOptimize) { return { shouldOptimize: false, analysis }; } const detectedInfo = await detectLanguageAndTaskType(text); // Check if we should ask questions (either forced or auto-detected) const shouldAskQuestions = forceInteractive || analysis.needsQuestions; if (shouldAskQuestions) { try { const questions = await generateClarifyingQuestions(text, detectedInfo.language, context); const sessionId = generateSessionId(); // Store session for later use activeSessions.set(sessionId, { originalPrompt: text, context: context ? [context] : [], refinements: [], language: detectedInfo.language, complexity: detectedInfo.complexity as any, taskType: detectedInfo.taskType as any }); return { shouldOptimize: true, analysis: { ...analysis, detectedLanguage: detectedInfo.language, taskType: detectedInfo.taskType, complexity: detectedInfo.complexity }, needsQuestions: true, questions, sessionId }; } catch (error) { // If question generation fails, fall back to direct optimization console.error('Question generation failed, falling back to direct optimization:', error); } } // Direct optimization (no questions needed or questions failed) try { const optimizedPrompt = await engineerPrompt(text, detectedInfo.language, context); return { shouldOptimize: true, optimizedPrompt, analysis: { ...analysis, detectedLanguage: detectedInfo.language, taskType: detectedInfo.taskType, complexity: detectedInfo.complexity, method: 'built-in' } }; } catch (error) { // If optimization fails, still return the analysis return { shouldOptimize: true, analysis: { ...analysis, error: error instanceof Error ? error.message : String(error) } }; } }
- index.ts:97-119 (schema)Tool schema definition with name, description, input schema for arguments validation (text required, context and interactive optional).const AUTO_OPTIMIZE_TOOL: Tool = { name: "auto_optimize", description: "Automatically detects and optimizes natural language text for Claude Code. Use this when the user is writing conversational text that should be translated into an optimized prompt.", inputSchema: { type: "object", properties: { text: { type: "string", description: "The natural language text to analyze and potentially optimize" }, context: { type: "string", description: "Any additional context about the current project or situation" }, interactive: { type: "boolean", description: "Whether to enable interactive questioning if the prompt is unclear or needs more info (default: auto-detect based on complexity)" }, }, required: ["text"], title: "auto_optimizeArguments" } };
- index.ts:570-572 (registration)Registration of available tools including AUTO_OPTIMIZE_TOOL in the ListToolsRequestSchema handler.server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: [ENGINEER_PROMPT_TOOL, ASK_CLARIFICATION_TOOL, ANSWER_QUESTIONS_TOOL, AUTO_OPTIMIZE_TOOL], }));
- index.ts:675-723 (handler)Dispatch handler in CallToolRequestSchema that validates arguments, calls autoOptimizeText, and formats the response based on the result.case "auto_optimize": { if (!isAutoOptimizeArgs(args)) { throw new Error("Invalid arguments for auto_optimize"); } const { text, context, interactive } = args; const result = await autoOptimizeText(text, context, interactive); if (!result.shouldOptimize) { return { content: [{ type: "text", text: `**Analysis:** This text doesn't appear to need optimization.\n\nReason: ${result.analysis.reason}\nConfidence: ${(result.analysis.confidence * 100).toFixed(1)}%\n\n**Original text:** "${text}"` }], isError: false, }; } // If questions are needed, start interactive session if (result.needsQuestions && result.questions && result.sessionId) { return { content: [{ type: "text", text: `**๐ค I need more information to optimize this effectively!**\n\n**Analysis:** ${result.analysis.questioningReason || 'Request needs clarification'}\n\n**Questions to help me create the best prompt:**\n\n${result.questions.map((q, i) => `${i + 1}. ${q}`).join('\n')}\n\n**Next Step:** Use the answer_questions tool with session ID "${result.sessionId}" to provide your answers.\n\n---\n**Detected:** ${result.analysis.detectedLanguage || 'General'} | ${result.analysis.taskType} | ${result.analysis.complexity}` }], isError: false, }; } // Direct optimization result if (result.optimizedPrompt) { const analysis = result.analysis; return { content: [{ type: "text", text: `**๐ Auto-Optimized Prompt for Claude Code:**\n\n${result.optimizedPrompt}\n\n**Are you ready to use this prompt?**` }], isError: false, }; } else { return { content: [{ type: "text", text: `**Analysis:** This text appears to be a prompt that should be optimized, but optimization failed.\n\nReason: ${result.analysis.reason}\nError: ${result.analysis.error || 'Unknown error'}\n\n**Original text:** "${text}"` }], isError: false, }; } }
- index.ts:214-253 (helper)Key helper function that analyzes input text to determine if it should be auto-optimized, calculates confidence, and decides if interactive questions are needed.function shouldAutoOptimize(text: string): { shouldOptimize: boolean; confidence: number; reason: string; needsQuestions: boolean; questioningReason?: string; } { if (text.length < 10) { return { shouldOptimize: false, confidence: 0, reason: "Text too short", needsQuestions: false }; } // Don't optimize if it's already a well-structured prompt if (text.includes('**') || text.includes('1.') || text.includes('- ')) { return { shouldOptimize: false, confidence: 0.1, reason: "Already structured", needsQuestions: false }; } // Don't optimize if it's clearly just conversation const conversationPatterns = /\b(thanks|thank you|yes|no|ok|okay|sure|got it|makes sense)\b/i; if (conversationPatterns.test(text) && text.length < 50) { return { shouldOptimize: false, confidence: 0.2, reason: "Simple conversation", needsQuestions: false }; } if (isNaturalLanguagePrompt(text)) { const confidence = Math.min(0.9, text.length / 100 + 0.3); // Determine if questions are needed const needsQuestions = shouldAskQuestions(text); const questioningReason = needsQuestions ? getQuestioningReason(text) : undefined; return { shouldOptimize: true, confidence, reason: "Natural language prompt detected", needsQuestions, questioningReason }; } return { shouldOptimize: false, confidence: 0.1, reason: "Not a prompt", needsQuestions: false }; }