MCP Prompt Optimizer

MCP Prompt Optimizer

Automatically analyzes and optimizes AI prompts by calculating clarity scores, detecting risks, asking clarifying questions, and adding domain-specific requirements to improve AI interaction quality.

Category
访问服务器

README

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

🚀 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

🔗 Related

⭐ 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

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选