Skip to main content
Glama
gr3enarr0w

Claude Code Prompt Engineer

by gr3enarr0w

auto_optimize

Optimizes natural language text into Claude Code prompts by detecting and structuring conversational input for better coding results.

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
NameRequiredDescriptionDefault
textYesThe natural language text to analyze and potentially optimize
contextNoAny additional context about the current project or situation
interactiveNoWhether to enable interactive questioning if the prompt is unclear or needs more info (default: auto-detect based on complexity)

Implementation Reference

  • Main handler for the 'auto_optimize' tool in the CallToolRequestSchema handler. Validates arguments, calls autoOptimizeText, handles interactive questioning or direct optimization, and formats the response.
    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,
        };
      }
    }
  • Core implementation function that performs the auto-optimization logic: analyzes text, detects if optimization is needed, handles interactive questioning, generates optimized prompt using engineerPrompt.
    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) 
          } 
        };
      }
    }
  • Tool schema definition for 'auto_optimize', including input schema with parameters text, context, interactive.
    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 ListToolsRequest handler.
    server.setRequestHandler(ListToolsRequestSchema, async () => ({
      tools: [ENGINEER_PROMPT_TOOL, ASK_CLARIFICATION_TOOL, ANSWER_QUESTIONS_TOOL, AUTO_OPTIMIZE_TOOL],  
    }));
  • Type guard function to validate arguments for the auto_optimize tool.
    function isAutoOptimizeArgs(args: unknown): args is {
      text: string;
      context?: string;
      interactive?: boolean;
    } {
      return (
        typeof args === "object" &&
        args !== null &&
        "text" in args &&
        typeof (args as { text: string }).text === "string"
      );
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. While it mentions the tool 'automatically detects and optimizes,' it doesn't describe what optimization entails, whether it modifies the input text, what the output format is, or any limitations like rate limits or authentication requirements. This leaves significant behavioral aspects unclear.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is extremely concise and well-structured with just two sentences. The first sentence states the purpose, and the second provides usage guidance. Every word earns its place with no wasted text or redundancy.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity of an optimization tool with no annotations and no output schema, the description is insufficiently complete. It doesn't explain what 'optimized for Claude Code' means, what the output looks like, or any behavioral characteristics. For a tool that presumably transforms text, more context about the transformation process and results is needed.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema has 100% description coverage, so the schema already documents all three parameters thoroughly. The description doesn't add any additional meaning or context about the parameters beyond what's in the schema, which is acceptable but not exceptional given the high schema coverage.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'Automatically detects and optimizes natural language text for Claude Code.' It specifies both the action (detects and optimizes) and the resource (natural language text), though it doesn't explicitly differentiate from sibling tools like 'engineer_prompt' which might have overlapping functionality.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides clear usage context: 'Use this when the user is writing conversational text that should be translated into an optimized prompt.' This gives specific guidance on when to use the tool, though it doesn't explicitly mention when NOT to use it or name alternatives among the sibling tools.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/gr3enarr0w/cc_peng_mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server