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
| Name | Required | Description | Default |
|---|---|---|---|
| raw_prompt | Yes | ||
| mode | No | compact | |
| projectRoot | No |
Implementation Reference
- src/tools/optimize.ts:13-61 (handler)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 }] }; } ); - src/lib/rewriter.ts:7-17 (helper)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 }; } - src/lib/tokenizer.ts:5-11 (helper)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)); }