Skip to main content
Glama
grandinh

MCP Prompt Optimizer

by grandinh

MCP Prompt Optimizer

An MCP server that automatically analyzes and optimizes AI prompts using the OTA (Optimize-Then-Answer) Framework

License: MIT TypeScript MCP

šŸŽÆ What It Does

This MCP server provides an optimize_prompt tool that:

  • šŸ“Š Analyzes prompts - Calculates clarity score (0-100%) and identifies domain

  • šŸ” Detects risks - Flags security, privacy, policy, safety, and compliance concerns

  • ā“ Asks smart questions - Generates 1-3 targeted questions when clarity < 60%

  • ✨ Enhances prompts - Adds domain-specific requirements (tests for code, accessibility for UX, etc.)

  • šŸ“‹ Provides structure - Returns optimized prompts ready for AI processing

Related MCP server: PromptForge MCP Server

šŸš€ Quick Start

Installation

For Claude Code:

# Clone the repository
git clone https://github.com/grandinh/mcp-prompt-optimizer.git
cd mcp-prompt-optimizer

# Install dependencies
npm install

# Build
npm run build

Add to .mcp.json:

{
  "mcpServers": {
    "prompt-optimizer": {
      "command": "node",
      "args": ["/path/to/mcp-prompt-optimizer/dist/index.js"],
      "description": "Optimizes prompts using the OTA Framework"
    }
  }
}

Restart your MCP client (Claude Code, Cursor, etc.)

Usage

Option 1: Use the MCP tool directly

Once installed, use the optimize_prompt tool:

Use the optimize_prompt tool to analyze: "build a dashboard"

Option 2: Use the /ori slash command (Claude Code)

The /ori (Optimize-Research-Implement) command provides an autonomous workflow with intelligent multi-model selection:

/ori add JWT authentication to the Express API

This will: 0. Strategy (Opus) - Design optimal research plan and select best models

  1. Research (Dynamic) - Automatically search docs, best practices, and codebase

  2. Verify (Sonnet) - Cross-validate findings and check for risks

  3. Implement (Sonnet/Haiku) - Apply changes with error handling

  4. Document (Haiku) - Update README, CHANGELOG, and other docs

Multi-Model Benefits:

  • 40% cost reduction vs. all-Opus

  • 30% faster execution

  • Each model used in its optimal zone

See /ori command documentation for details.

Output:

[OPTIMIZED] Domain: code | Clarity: 30% | Risks: none

āš ļø Clarification Needed (Clarity: 30%)

Please answer these questions before I proceed:
1. What programming language or framework are you using?
2. What specific features or components are you building?
3. Do you need tests, validation, or specific security considerations?

After answering:

Use optimize_prompt tool: "build a React dashboard with user analytics,
chart visualizations using Chart.js, and real-time data updates.
Need responsive design and accessibility compliance."

Output:

[OPTIMIZED] Domain: code | Clarity: 85% | Risks: none

āœ“ Ready to Process (Clarity: 85%)

[Shows enhanced prompt with code-specific requirements including
security, testing, accessibility, and structured output format]

šŸ“Š Features

Domain Detection

Automatically identifies the domain of your request:

  • code - Programming, APIs, debugging

  • UX - UI design, interfaces, accessibility

  • data - Analytics, statistics, calculations

  • writing - Content, documentation, articles

  • research - Studies, investigations, analysis

  • finance - ROI, budgets, pricing

  • product - Features, roadmaps, strategy

Clarity Scoring

Calculates a 0-1 clarity score based on:

Factor

Weight

Measures

Goal clarity

30%

Is objective explicit and measurable?

Context completeness

25%

Are inputs/constraints provided?

Format specification

15%

Is output format defined?

Success criteria

20%

Are acceptance criteria stated?

Technical detail

10%

Stack, versions, specifics included?

Risk Detection

Flags potential concerns:

  • security - auth, passwords, tokens, vulnerabilities

  • privacy - PII, email, phone, GDPR

  • policy - fake, bypass, illegal activities

  • safety - harm, dangerous content

  • compliance - medical/legal/financial advice

Smart Questions

When clarity < 60%, generates targeted questions:

Code domain:

  • What programming language or framework?

  • What specific feature/component?

  • Testing/security needs?

UX domain:

  • Who are the target users?

  • What platform (web/mobile)?

Data domain:

  • What's the data structure?

  • What specific metrics?

Domain-Specific Enhancement

Adds requirements based on domain:

Code:

- Include code summary and complexity notes
- Add security considerations
- Provide test plan and example I/O
- Include error handling

UX:

- Evaluate against usability heuristics
- Include accessibility checklist (WCAG 2.1 AA)
- Consider mobile responsiveness
- Address error and loading states

Data:

- Describe dataset shape and structure
- Show calculation steps explicitly
- Validate data and identify edge cases
- Make results reproducible

šŸ“– Examples

Example 1: Vague Request

Input:

optimize_prompt: "help me with my app"

Output:

[OPTIMIZED] Domain: code | Clarity: 25% | Risks: none

āš ļø Clarification Needed

1. What programming language or framework are you using?
2. What specific feature or component are you building?

Example 2: Clear Request with Security

Input:

optimize_prompt: "Create a REST API for user authentication in Express.js.
Need endpoints for register, login, logout. Use JWT tokens with refresh
token rotation. Store passwords with bcrypt."

Output:

[OPTIMIZED] Domain: code | Clarity: 90% | Risks: security

āœ“ Ready to Process

**Domain:** code

**Requirements:**
- Include code summary and complexity notes
- **CRITICAL:** Address security concerns (auth, validation, token storage)
- Provide test plan and example I/O
- Include error handling

**Risk Flags:** security
Please address these concerns in your response.

Example 3: UX Request

Input:

optimize_prompt: "Review my checkout flow for usability issues"

Output:

[OPTIMIZED] Domain: UX | Clarity: 70% | Risks: none

āœ“ Ready to Process

**Requirements:**
- Evaluate against usability heuristics
- Include accessibility checklist (WCAG 2.1 AA)
- Consider mobile responsiveness
- Address error and loading states

šŸ”§ Configuration

Adjust Clarity Threshold

Edit src/index.ts:

const needsClarification = clarityScore < 0.6; // Change to 0.7 for stricter

Change Question Limit

In generateQuestions():

return questions.slice(0, 3); // Change to 2 for fewer questions

Add Custom Domain

Add to detectDomain():

if (/(your|custom|keywords)/i.test(prompt)) {
  return 'your_domain';
}

Then add handling in generateQuestions() and createOptimizedPrompt().

šŸ—ļø Development

Build

npm run build

Watch Mode

npm run dev

Project Structure

mcp-prompt-optimizer/
ā”œā”€ā”€ src/
│   └── index.ts          # Main server code
ā”œā”€ā”€ dist/                 # Built output (git-ignored)
ā”œā”€ā”€ package.json
ā”œā”€ā”€ tsconfig.json
ā”œā”€ā”€ README.md
ā”œā”€ā”€ LICENSE
└── .gitignore

šŸŽ“ How It Works

The OTA (Optimize-Then-Answer) Loop

1. Parse & Classify
   ā”œā”€ā”€ Detect domain
   ā”œā”€ā”€ Calculate clarity score
   └── Identify risk flags

2. Generate Questions (if clarity < 60%)
   └── Max 3 targeted questions

3. Create Optimized Prompt
   ā”œā”€ā”€ Add domain-specific requirements
   ā”œā”€ā”€ Include risk warnings
   └── Specify output format

4. Return Analysis
   ā”œā”€ā”€ Optimization header
   ā”œā”€ā”€ Questions (if needed)
   └── Enhanced prompt (if ready)

Keyword-Based Detection

The server uses keyword matching for:

  • Domain classification - Fast, deterministic

  • Clarity scoring - Heuristic-based

  • Risk detection - Pattern matching

Note: This is intentionally simple and fast. No ML models, no API calls, works offline.

šŸ¤ Contributing

Contributions welcome! Areas for improvement:

  • ML-based domain classification

  • Multi-language support

  • Learning from user feedback

  • Integration with custom knowledge bases

  • Automatic prompt rewriting (not just enhancement)

šŸ“„ License

MIT License - see LICENSE file for details

⭐ Support

If this tool helps you get better AI responses, give it a star!

šŸ“ Changelog

v1.1.0 (2025-11-08)

  • Added /ori slash command for autonomous research-implement workflow

  • Intelligent multi-model selection (Opus → Sonnet → Haiku)

    • Phase 0: Opus creates research strategy

    • Phase 1: Dynamic model selection based on complexity

    • Phase 2-4: Optimized model per phase (40% cost savings)

  • Integrated OODA framework with OTA Loop in optimized_prompts.md

  • Added automatic web search and documentation research

  • Implemented error handling and rollback mechanisms

  • Added automatic documentation updates (README, CHANGELOG)

  • Created configurable workflow via .claude/ori-config.json

v1.0.0 (2025-11-08)

  • Initial release

  • Domain detection (7 domains)

  • Clarity scoring (0-1 scale)

  • Risk detection (5 categories)

  • Smart question generation (max 3)

  • Domain-specific prompt enhancement


Made with ā¤ļø for better AI interactions

Available Tools

1 tool
optimize_promptB

Analyze and optimize a user prompt using the OTA (Optimize-Then-Answer) Framework. Returns clarity score, domain classification, risk flags, targeted questions (if needed), and an enhanced prompt ready for AI processing.

ParametersJSON Schema
NameRequiredDescriptionDefault
promptYesThe user prompt to optimize
contextNoOptional additional context about the request

TDQS

B3.2/5.0
Behavior3/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. It mentions that the tool returns 'clarity score, domain classification, risk flags, targeted questions (if needed), and an enhanced prompt,' which gives some insight into outputs. However, it doesn't disclose critical behavioral traits like whether this is a read-only operation, potential side effects, performance characteristics, or error handling.

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

Conciseness4/5

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

The description is concise and well-structured in a single sentence that efficiently conveys the core functionality and outputs. Every part of the sentence serves a purpose, with no redundant information. It could be slightly improved by front-loading the purpose more explicitly, but it's already quite efficient.

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

Completeness3/5

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

Given the tool's moderate complexity (analyzing and optimizing prompts), no annotations, and no output schema, the description is somewhat incomplete. It lists output components but doesn't explain their format or significance. For a tool that returns multiple structured outputs, more detail on what each component means would be helpful for an AI agent to interpret results effectively.

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 schema description coverage is 100%, so the input schema already documents both parameters thoroughly. The description doesn't add any meaningful semantic context beyond what's in the schema (e.g., it doesn't explain how 'context' influences optimization or provide examples). This meets the baseline for 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: 'Analyze and optimize a user prompt using the OTA Framework.' It specifies the verb (analyze and optimize) and resource (user prompt), and mentions the framework used. However, with no sibling tools, there's no explicit differentiation needed, so it doesn't achieve the highest score for sibling distinction.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention any prerequisites, constraints, or scenarios where this optimization is particularly beneficial. The lack of sibling tools means there's no need to differentiate, but general usage context is still missing.

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

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections. Dates show when Glama detected each change.

  1. 1 tool update
    • First observedoptimize_prompt

TDQS

B3.3/5.0
Disambiguation5/5

With only one tool, there is no possibility of ambiguity or overlap between tools. The tool's purpose is clearly defined and distinct by default.

Naming Consistency5/5

A single tool inherently has perfect naming consistency, as there are no other tools to compare it against for patterns or conventions.

Tool Count2/5

One tool is too few for a server named 'MCP Prompt Optimizer', which suggests a broader scope for prompt optimization tasks. A single tool limits functionality and may not cover related operations like prompt analysis, versioning, or comparison.

Completeness2/5

The tool surface is severely incomplete for the domain of prompt optimization. It lacks essential operations such as analyzing prompts without optimization, comparing multiple prompts, managing prompt history, or handling different optimization strategies, which are typical in this domain.

Maintenance

ActivityInactive
ResponsivenessSyncing

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    C
    maintenance
    Intelligently optimizes and enhances user prompts before execution using pattern matching, domain-specific enhancements, and analytics tracking for consistent AI outputs across marketing, data analysis, tax/accounting, and code generation domains.
    23
    2
    MIT
  • A
    license
    B
    quality
    D
    maintenance
    Analyzes, refines, and optimizes prompts for AI assistants by fixing grammar, improving clarity, applying best practices like chain-of-thought and few-shot learning, and scoring prompt quality across multiple dimensions.
    3
    19
    MIT
  • F
    license
    A
    quality
    C
    maintenance
    Refines and improves AI prompts using workspace-aware context from your project's tech stack, structure, and dependencies. Includes tools to analyze prompt quality and generate well-structured prompts from raw ideas.
    4
    209
    5
    -

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/grandinh/mcp-prompt-optimizer'

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