Skip to main content
Glama

refine_prompt

Improve existing prompts by applying targeted feedback to add missing context, clarify instructions, or adapt for different AI models while preserving original structure.

Instructions

Iteratively improve an existing prompt based on specific feedback.

Use this tool when you need to: • Improve a prompt that didn't get good results • Add missing context or constraints • Make a prompt more specific or clearer • Adapt a prompt for a different AI model

The tool preserves the original structure while applying targeted improvements.

IMPORTANT: When available, pass workspace context (file structure, package.json, tech stack) to ensure refined prompts comply with the user's project scope and original request.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
promptYesThe current prompt to refine.
feedbackYesWhat should be improved. Examples: "make it more specific", "add error handling requirements", "focus on performance".
preserveStructureNoWhether to keep the original structure. Default: true.
targetModelNoTarget AI model for optimization.
workspaceContextNoProject context to ensure the refined prompt aligns with the codebase. Include: file/folder structure, package.json dependencies, tech stack (React, Node, etc.), relevant code snippets, and the original user request. This ensures the refined prompt complies with project conventions and scope.

Implementation Reference

  • The core handler function that implements the refine_prompt tool logic. It calls the PromptArchitect API if available, otherwise falls back to basic refinements, and computes metadata.
    export async function refinePrompt(input: RefinePromptInput): Promise<{
      refinedPrompt: string;
      changes: string[];
      metadata: {
        originalWordCount: number;
        refinedWordCount: number;
        structurePreserved: boolean;
      };
    }> {
      const { prompt, feedback, preserveStructure = true, targetModel, workspaceContext } = input;
      
      logger.info('Refining prompt', { 
        promptLength: prompt.length, 
        feedbackLength: feedback.length,
        preserveStructure,
        targetModel,
        hasWorkspaceContext: !!workspaceContext
      });
    
      let refinedPrompt: string = '';
      let changes: string[] = [];
    
      // Use PromptArchitect API
      if (isApiClientAvailable()) {
        try {
          const response = await apiRefinePrompt({
            prompt,
            feedback,
            preserveStructure,
            targetModel,
            workspaceContext,
          });
          refinedPrompt = response.refinedPrompt;
          changes = response.changes || ['Prompt refined based on feedback'];
          logger.info('Refined via PromptArchitect API');
        } catch (error) {
          logger.warn('API request failed, using fallback', { 
            error: error instanceof Error ? error.message : 'Unknown error' 
          });
        }
      }
    
      // Fallback basic refinement
      if (!refinedPrompt) {
        refinedPrompt = applyBasicRefinements(prompt, feedback);
        changes = ['Applied basic refinements'];
        logger.warn('Using fallback refinement');
      }
    
      // Calculate metadata
      const originalWordCount = prompt.split(/\s+/).length;
      const refinedWordCount = refinedPrompt.split(/\s+/).length;
      const originalHasStructure = /^#+\s|^\d+\.|^-\s|^\*\s/m.test(prompt);
      const refinedHasStructure = /^#+\s|^\d+\.|^-\s|^\*\s/m.test(refinedPrompt);
      const structurePreserved = !originalHasStructure || refinedHasStructure;
    
      return {
        refinedPrompt,
        changes,
        metadata: {
          originalWordCount,
          refinedWordCount,
          structurePreserved,
        },
      };
    }
  • Zod schema defining the input validation for the refine_prompt tool.
    export const refinePromptSchema = z.object({
      prompt: z.string().min(1).describe('The current prompt to refine'),
      feedback: z.string().min(1).describe('What should be improved or changed'),
      preserveStructure: z.boolean().optional().default(true).describe('Whether to preserve the original structure'),
      targetModel: z.enum(['gpt-4', 'claude', 'gemini', 'general'])
        .optional()
        .default('general')
        .describe('Target AI model to optimize for'),
      workspaceContext: z.string().optional().describe('Project context including file structure, tech stack, dependencies, and any relevant code snippets to ensure the refined prompt aligns with the project scope'),
    });
  • src/server.ts:114-154 (registration)
    MCP tool list registration for 'refine_prompt' including name, description, and input schema.
            {
              name: 'refine_prompt',
              description: `Iteratively improve an existing prompt based on specific feedback.
    
    Use this tool when you need to:
    • Improve a prompt that didn't get good results
    • Add missing context or constraints
    • Make a prompt more specific or clearer
    • Adapt a prompt for a different AI model
    
    The tool preserves the original structure while applying targeted improvements.
    
    IMPORTANT: When available, pass workspace context (file structure, package.json, tech stack) to ensure refined prompts comply with the user's project scope and original request.`,
              inputSchema: {
                type: 'object',
                properties: {
                  prompt: {
                    type: 'string',
                    description: 'The current prompt to refine.',
                  },
                  feedback: {
                    type: 'string',
                    description: 'What should be improved. Examples: "make it more specific", "add error handling requirements", "focus on performance".',
                  },
                  preserveStructure: {
                    type: 'boolean',
                    description: 'Whether to keep the original structure. Default: true.',
                  },
                  targetModel: {
                    type: 'string',
                    enum: ['gpt-4', 'claude', 'gemini', 'general'],
                    description: 'Target AI model for optimization.',
                  },
                  workspaceContext: {
                    type: 'string',
                    description: 'Project context to ensure the refined prompt aligns with the codebase. Include: file/folder structure, package.json dependencies, tech stack (React, Node, etc.), relevant code snippets, and the original user request. This ensures the refined prompt complies with project conventions and scope.',
                  },
                },
                required: ['prompt', 'feedback'],
              },
            },
  • src/server.ts:220-231 (registration)
    MCP tool call handler for 'refine_prompt' that parses input using the schema and invokes the refinePrompt handler.
    case 'refine_prompt': {
      const input = refinePromptSchema.parse(args);
      const result = await refinePrompt(input);
      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify(result, null, 2),
          },
        ],
      };
    }
  • Fallback helper function for basic prompt refinements when API is unavailable.
    function applyBasicRefinements(prompt: string, feedback: string): string {
      let refined = prompt;
      const feedbackLower = feedback.toLowerCase();
    
      // Basic transformations based on common feedback
      if (feedbackLower.includes('more specific') || feedbackLower.includes('more detail')) {
        refined += '\n\n## Additional Requirements\n- Provide specific, detailed information\n- Include concrete examples where applicable';
      }
    
      if (feedbackLower.includes('shorter') || feedbackLower.includes('concise')) {
        // Try to simplify
        refined = refined.replace(/\n\n+/g, '\n\n');
      }
    
      if (feedbackLower.includes('structure') || feedbackLower.includes('organize')) {
        if (!/^#+\s/m.test(refined)) {
          refined = '## Task\n' + refined + '\n\n## Output\nProvide a well-structured response.';
        }
      }
    
      if (feedbackLower.includes('example')) {
        refined += '\n\n## Example\nProvide a relevant example in your response.';
      }
    
      return refined;
    }
Behavior4/5

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

With no annotations provided, the description carries full burden and does well by disclosing key behavioral traits: it's an iterative improvement tool, preserves original structure by default, and requires workspace context for project compliance. However, it doesn't mention potential side effects like rate limits or authentication needs.

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 well-structured and front-loaded with the core purpose, followed by usage guidelines and important context. Every sentence earns its place: the first states the purpose, the bulleted list provides clear usage scenarios, and the IMPORTANT section adds necessary project-specific guidance without redundancy.

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

Completeness4/5

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

For a 5-parameter tool with no annotations and no output schema, the description provides good contextual completeness with clear purpose, usage guidelines, and behavioral context. It could be improved by mentioning what the refined prompt output looks like or any limitations, but covers most essential aspects well.

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?

Schema description coverage is 100%, so the baseline is 3. The description adds some value by explaining workspace context usage ('ensure refined prompts comply with project scope') and mentioning structure preservation, but doesn't provide significant additional parameter semantics beyond what's already documented in the schema.

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

Purpose5/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 with specific verbs ('iteratively improve', 'refine') and resources ('existing prompt'), distinguishing it from siblings like analyze_prompt (analysis) and generate_prompt (creation). It explicitly mentions applying targeted improvements based on feedback.

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

Usage Guidelines5/5

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

The description provides explicit when-to-use guidance with four bulleted scenarios (e.g., 'Improve a prompt that didn't get good results', 'Adapt a prompt for a different AI model'), clearly differentiating from sibling tools. It also includes an IMPORTANT section about when to pass workspace context.

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/MerabyLabs/promptarchitect-mcp'

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