Skip to main content
Glama

optimize_prompt

Refine your AI prompts by scoring and rewriting them across four dimensions. Injects codebase context for design, database, API, auth, testing, and state management to improve accuracy before sending to AI.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
raw_promptYes
modeNocompact
projectRootNo

Implementation Reference

  • Core handler function for the optimize_prompt tool. Applies context-aware rewriting (project docs discovery, context injection), then runs clarity, specificity, completeness, efficiency rules via rewrite(), computes scores, token savings, and returns compact or verbose output.
    export async function optimizePrompt(rawPrompt: string, mode: "compact" | "verbose" = "compact", projectRoot?: string) {
      const root = projectRoot || cwd();
      let contextEnhancedPrompt = rawPrompt;
      let contextRules: RuleResult[] = [];
    
      // Try to discover and extract project context
      try {
        const docFiles = await discoverProjectDocs(root);
        if (docFiles.length > 0) {
          const { promises: fs } = await import("fs");
          let allContextTokens = {};
          for (const file of docFiles) {
            const content = await fs.readFile(file, "utf-8");
            const tokens = await extractContextTokens(content);
            allContextTokens = { ...allContextTokens, ...tokens };
          }
    
          // Apply context rules to enhance the prompt
          const contextResult = applyContextRules(rawPrompt, allContextTokens);
          contextEnhancedPrompt = contextResult.text;
          contextRules = contextResult.results;
        }
      } catch {
        // If context discovery fails, continue with original prompt
      }
    
      const { optimized, rules } = rewrite(contextEnhancedPrompt);
      const rulesBeforeOptimization = [
        ...contextRules,
        ...applyEfficiencyRules(rawPrompt).results,
        ...applyClarityRules(rawPrompt).results,
        ...applySpecificityRules(rawPrompt).results,
        ...applyCompletenessRules(rawPrompt).results,
      ];
      const scoresBefore = computeScore(rulesBeforeOptimization);
      const scoresAfter = computeScore([...contextRules, ...rules]);
      const tokensBefore = countTokens(rawPrompt);
      const tokensAfter = countTokens(optimized);
      const tokensSaved = tokensBefore - tokensAfter;
      const costSaved = estimateCostSaved(Math.max(0, tokensSaved));
    
    const summary = `✦ Prompt optimized · Score ${scoresBefore.total} → ${scoresAfter.total} · ${Math.max(0, tokensSaved)} tokens saved\n\n${optimized}`;
      if (mode === "compact") return { content: summary, raw: { optimized, scoreBefore: scoresBefore.total, scoreAfter: scoresAfter.total, tokensBefore, tokensAfter, tokensSaved, costSaved } };
    
      const changelog = rules.map((r: RuleResult) => `  ${r.severity === "critical" ? "🔴" : r.severity === "warn" ? "⚠" : "✦"} [${r.id}] ${r.message}`).join("\n");
      const verbose = `✦ Score ${scoresBefore.total} → ${scoresAfter.total} · ${Math.max(0, tokensSaved)} tokens saved · ~$${costSaved}\n\nChanges:\n${changelog}\n\n${optimized}`;
    
      return { content: verbose, raw: { optimized, scoreBefore: scoresBefore.total, scoreAfter: scoresAfter.total, tokensBefore, tokensAfter, tokensSaved, costSaved, rules } };
    }
  • src/http.ts:14-20 (registration)
    Registration of the optimize_prompt tool in the HTTP server (Express + StreamableHTTP). Uses Zod schema for raw_prompt (string), mode (compact/verbose), and optional projectRoot.
    server.tool("optimize_prompt",
      { raw_prompt: z.string(), mode: z.enum(["compact", "verbose"]).default("compact"), projectRoot: z.string().optional() },
      async ({ raw_prompt, mode, projectRoot }) => {
        const result = await optimizePrompt(raw_prompt, mode, projectRoot);
        return { content: [{ type: "text", text: result.content }] };
      }
    );
  • src/index.ts:9-15 (registration)
    Registration of the optimize_prompt tool in the stdio-based MCP server. Same Zod schema and handler logic, used for CLI/stdio transport.
    server.tool("optimize_prompt",
      { raw_prompt: z.string(), mode: z.enum(["compact", "verbose"]).default("compact"), projectRoot: z.string().optional() },
      async ({ raw_prompt, mode, projectRoot }) => {
        const result = await optimizePrompt(raw_prompt, mode, projectRoot);
        return { content: [{ type: "text", text: result.content }] };
      }
    );
  • Helper that chains all four rule engines (efficiency, clarity, specificity, completeness) sequentially to rewrite/optimize the prompt text.
    export function rewrite(prompt: string): { optimized: string; rules: RuleResult[] } {
      const allRules: RuleResult[] = [];
      let text = prompt.trim();
    
      let r1 = applyEfficiencyRules(text); text = r1.text; allRules.push(...r1.results);
      let r2 = applyClarityRules(text);    text = r2.text; allRules.push(...r2.results);
      let r3 = applySpecificityRules(text); text = r3.text; allRules.push(...r3.results);
      let r4 = applyCompletenessRules(text); text = r4.text; allRules.push(...r4.results);
    
      return { optimized: text.trim(), rules: allRules };
    }
  • Token counting (using tiktoken cl100k_base) and cost estimation used by optimizePrompt to report tokens saved and estimated cost savings.
    export function countTokens(text: string): number {
      return enc.encode(text).length;
    }
    
    export function estimateCostSaved(tokensSaved: number): number {
      return parseFloat(((tokensSaved / 1_000_000) * 2).toFixed(6));
    }
Behavior1/5

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

Tool has no description.

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

Conciseness1/5

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

Tool has no description.

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

Completeness1/5

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

Tool has no description.

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

Parameters1/5

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

Tool has no description.

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

Purpose1/5

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

Tool has no description.

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

Usage Guidelines1/5

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

Tool has no description.

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/saurabhjambure-pixel/vibe-prompt-mcp'

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