# MCP Prompt Optimizer

Local MCP server for accessing the AI-Enhanced Prompt Optimizer API from Claude Desktop, Cursor, Windsurf, and other MCP-compatible clients.

## ✨ New in v1.1.0: AI Context Detection & Enhanced Optimization

- 🧠 **Automatic AI Context Detection** - Automatically detects image generation, LLM interaction, and technical automation prompts
- 🛡️ **Parameter Preservation** - Preserves technical parameters like Midjourney `--ar 16:9`, `--v 5.2` during optimization
- 🎯 **Enhanced AI Goals** - New optimization goals specifically designed for AI model interactions
- 🤖 **Smart Goal Enhancement** - Automatically adds relevant goals based on detected AI context
- 🔧 **Target AI Model Support** - Optimize specifically for Midjourney, ChatGPT, Claude, and more

## Features

- 🤖 **Universal MCP Support** - Works with Claude Desktop, Cursor, Windsurf, and any MCP-compatible client
- 🔐 **Secure API Key Authentication** - Uses your personal API key for secure access
- 🧠 **AI Context Awareness** - Automatically detects and optimizes for different AI use cases
- 🎯 **Advanced Optimization Goals** - Support for clarity, conciseness, technical accuracy, and AI-specific enhancements
- 📊 **Real-time Quota Tracking** - See your usage and remaining quota
- 💾 **Automatic Template Saving** - All optimizations saved with rich metadata for future reference
- 🚀 **Easy Setup** - Simple configuration process
- ⚡ **Production Backend** - Powered by enterprise-grade FastAPI deployment on Northflank

## Installation

### Global Installation (Recommended)

```bash
npm install -g mcp-prompt-optimizer
```

### Local Installation

```bash
npm install mcp-prompt-optimizer
```

## Quick Start

### 1. Get Your API Key

1. Visit [Prompt Optimizer Dashboard](https://promptoptimizer-blog.vercel.app/dashboard)
2. Subscribe to Explorer ($2.99/month), Creator ($25.99/month), or Innovator ($69.99/month) plan
3. Generate your API key from the dashboard

### 2. Setup

```bash
mcp-prompt-optimizer --setup
```

Enter your API key when prompted. The package will automatically connect to the production backend at `https://p01--project-optimizer--fvrdk8m9k9j.code.run`.

### 3. Configure Your MCP Client

#### Claude Desktop

Add to `~/.claude/claude_desktop_config.json`:

```json
{
  "mcpServers": {
    "prompt-optimizer": {
      "command": "npx",
      "args": ["mcp-prompt-optimizer"]
    }
  }
}
```

#### Cursor

Add to `~/.cursor/mcp.json`:

```json
{
  "mcpServers": {
    "prompt-optimizer": {
      "command": "npx",
      "args": ["mcp-prompt-optimizer"]
    }
  }
}
```

#### Windsurf

Add via Windsurf settings or configuration file:

```json
{
  "mcpServers": {
    "prompt-optimizer": {
      "command": "npx",
      "args": ["mcp-prompt-optimizer"]
    }
  }
}
```

### 4. Use the AI-Enhanced Tool

Once configured, the `optimize_prompt` tool will be available with AI context detection:

**Required Parameters:**
- **prompt**: The prompt you want to optimize

**Optional AI Enhancement Parameters:**
- **goals**: Array of optimization goals (auto-enhanced based on AI context)
- **ai_context**: Manual AI context specification (`image_generation`, `llm_interaction`, `technical_automation`, `human_communication`)
- **preserve_formatting**: Whether to preserve technical parameters (default: true)
- **target_ai_model**: Target AI model (`midjourney`, `chatgpt`, `claude`, etc.)
- **optimization_level**: Optimization intensity (`conservative`, `balanced`, `aggressive`)

## AI Context Detection

The tool automatically detects and optimizes for different AI use cases:

### 🎨 Image Generation
**Automatically detected for:**
- Midjourney prompts (`--ar 16:9`, `--v 5.2`, `--stylize 100`)
- DALL-E prompts with photography/art terms
- Stable Diffusion prompts with quality indicators

**AI Enhancements Applied:**
- Preserves technical parameters (`--ar`, `--v`, `--s`, `--q`)
- Adds quality keywords (`award-winning`, `professional`, `masterpiece`)
- Optimizes keyword density for better AI model response
- Enhances technical precision

### 🤖 LLM Interaction  
**Automatically detected for:**
- Role-playing prompts (`Act as a...`, `You are a...`)
- Persona-based interactions
- Character behavior instructions

**AI Enhancements Applied:**
- Clarifies role definitions and expectations
- Improves context specificity
- Optimizes token efficiency
- Enhances actionability and response clarity

### ⚙️ Technical Automation
**Automatically detected for:**
- Code generation requests
- API and automation scripts
- Technical documentation prompts

**AI Enhancements Applied:**
- Protects code elements from modification
- Preserves technical parameters and URLs
- Enhances technical precision
- Maintains technical accuracy

### 💬 Human Communication
**Default for:**
- General conversation prompts
- Creative writing requests
- Educational content

**AI Enhancements Applied:**
- Standard optimization rules
- Clarity and conciseness improvements
- Structural enhancements

## Enhanced Optimization Goals

### Standard Goals
- **clarity** - Make the prompt clearer and more understandable
- **conciseness** - Remove unnecessary words while preserving meaning
- **technical_accuracy** - Improve technical precision and correctness
- **contextual_relevance** - Better alignment with context and purpose
- **specificity** - Add specific details and reduce ambiguity
- **actionability** - Make the prompt more actionable and directive
- **structure** - Improve organization and logical flow
- **technical_precision** - Enhance exactness of technical terms
- **linguistic_precision** - Refine language for exact meaning
- **holistic_effectiveness** - Overall optimization for best results

### 🆕 AI-Specific Goals
- **keyword_density** - Enhanced keyword optimization for AI models
- **parameter_preservation** - Preserves technical parameters during optimization
- **token_efficiency** - Optimizes token usage for LLM interactions  
- **embedding_strength** - Enhances semantic embedding effectiveness
- **context_specificity** - Improves context relevance for AI models
- **ai_model_compatibility** - Optimizes for specific AI model requirements
- **quality_enhancement** - Adds quality indicators for better AI responses
- **role_clarity** - Enhances role-playing and persona clarity
- **code_protection** - Protects code elements during optimization

## Example Usage

### 🎨 Image Generation Example

In Claude Desktop, you might ask:

```
Please optimize this Midjourney prompt using the optimize_prompt tool:
"A beautiful sunset over mountains --ar 16:9 --v 5.2"

Use goals: ["clarity", "keyword_density"]
```

**AI-Enhanced Result:**
```
# AI-Optimized Prompt

Breathtaking golden hour sunset over majestic mountain peaks, dramatic lighting, award-winning landscape photography, professional composition, highly detailed, masterpiece quality --ar 16:9 --v 5.2

---
**Confidence Score:** 0.92
**Goals Applied:** clarity, keyword_density, parameter_preservation, quality_enhancement
**AI Context Detected:** image_generation
**Optimization Strategy:** AI_PARAMETER_PRESERVATION
**Parameters Preserved:** 2
**Goal Enhancement:** Applied
**Original Goals:** clarity, keyword_density
**Enhanced Goals:** clarity, keyword_density, parameter_preservation, quality_enhancement
**Quota Remaining:** 195/200
```

### 🤖 LLM Role-Playing Example

```
Please optimize this prompt using the optimize_prompt tool:
"Act as a copywriter and help me write"

Use goals: ["clarity", "specificity"]
```

**AI-Enhanced Result:**
```
# AI-Optimized Prompt

You are a professional copywriter with 10+ years of experience in digital marketing and persuasive writing. Please help me create compelling copy by:

1. Understanding my target audience and objectives
2. Applying proven copywriting frameworks (AIDA, PAS, etc.)
3. Crafting persuasive, conversion-focused content
4. Ensuring brand voice consistency and engagement

What specific copywriting project would you like assistance with today?

---
**Confidence Score:** 0.89
**Goals Applied:** clarity, specificity, role_clarity, context_specificity, actionability
**AI Context Detected:** llm_interaction
**Optimization Strategy:** RULES_WITH_LLM_FALLBACK
**Goal Enhancement:** Applied
**Quota Remaining:** 194/200
```

### ⚙️ Technical Automation Example

```
Please optimize this prompt using the optimize_prompt tool:
"Write Python code for API"

Use goals: ["technical_accuracy", "specificity"]
```

**AI-Enhanced Result:**
```
# AI-Optimized Prompt

Create a Python REST API implementation with the following specifications:

## Requirements:
- Use FastAPI framework for modern async API development
- Implement CRUD operations for data management
- Include proper request/response models with Pydantic validation
- Add comprehensive error handling and status codes
- Implement authentication and authorization middleware
- Include API documentation with OpenAPI/Swagger

## Deliverables:
- Main application file with API endpoints
- Data models and validation schemas
- Database integration layer
- Authentication system
- Unit tests for all endpoints
- Documentation and usage examples

Please specify the API's purpose and data entities for customized implementation.

---
**Confidence Score:** 0.86
**Goals Applied:** technical_accuracy, specificity, code_protection, technical_precision, parameter_preservation
**AI Context Detected:** technical_automation
**Optimization Strategy:** CODE_PROTECTION
**Goal Enhancement:** Applied
**Quota Remaining:** 193/200
```

## Template Saving & History

Your AI-optimized prompts are automatically saved as templates with enhanced metadata:

### Automatic Template Saving
- **Every Optimization Saved**: All successful optimizations are automatically saved as structured templates
- **AI Context Metadata**: Templates include detected AI context and optimization strategies
- **Parameter Preservation Tracking**: Records which technical parameters were preserved
- **Goal Enhancement History**: Shows original vs enhanced goals
- **Model Compatibility Info**: Tracks target AI model optimizations

### Enhanced Template Structure
Each saved template now contains AI-specific information:
```json
{
  "saved_at_utc": "2025-06-21T12:00:00.000Z",
  "optimization_tier": "AI_PARAMETER_PRESERVATION",
  "confidence_score": 0.92,
  "original_prompt": "A sunset --ar 16:9 --v 5.2",
  "optimized_prompt": "Breathtaking golden hour sunset over majestic mountain peaks...",
  "optimization_goals": ["clarity", "keyword_density", "parameter_preservation", "quality_enhancement"],
  "ai_context": "image_generation",
  "optimization_strategy": "AI_PARAMETER_PRESERVATION",
  "preserved_parameters": 2,
  "goal_enhancement_applied": true,
  "original_goals": ["clarity", "keyword_density"],
  "enhanced_goals": ["clarity", "keyword_density", "parameter_preservation", "quality_enhancement"],
  "target_ai_model": "midjourney",
  "context_snapshot": {
    "domain": "Image Generation",
    "target_audience": "AI Artists"
  },
  "request_id": "unique-ai-request-identifier",
  "model_optimized_with": "AI-Aware Rules-Based"
}
```

### AI-Enhanced Template Benefits
- **AI Context Learning**: Understand how different AI contexts affect optimization
- **Parameter Preservation Tracking**: See which technical parameters are being preserved
- **Goal Enhancement Analysis**: Learn how the system enhances goals based on AI context
- **Model-Specific Optimization**: Track optimizations for specific AI models
- **Strategy Effectiveness**: Monitor which optimization strategies work best for your use cases

## Subscription Tiers

- **Explorer** ($2.99/month): 5,000 AI-enhanced optimizations + 1 API key
- **Creator** ($25.99/month): 18,000 optimizations + 3 API keys + Template history + AI analytics
- **Innovator** ($69.99/month): 75,000 optimizations + up to 10 API keys + Advanced AI features + Priority support

## Backend Infrastructure

This package connects to a production-grade AI-enhanced backend infrastructure:

- **AI-Enhanced FastAPI Backend** - High-performance Python API server with AI context detection
- **Northflank Hosting** - Enterprise cloud deployment platform with 99.9% uptime
- **Supabase Database** - PostgreSQL database with AI optimization metadata storage
- **Stripe Integration** - Secure payment processing and subscription management
- **AI Template Storage System** - Automatic optimization history with AI context metadata
- **Advanced AI Analytics** - AI context detection analytics and optimization insights

### AI-Enhanced Backend Features
- **Real-time AI Context Detection** - Automatic detection of image generation, LLM interaction, and technical prompts
- **Parameter Preservation Engine** - Intelligent preservation of technical parameters
- **Goal Enhancement System** - Automatic goal enhancement based on AI context
- **Model-Specific Optimization** - Optimization strategies tailored for specific AI models
- **AI Analytics Dashboard** - Insights into AI context detection and optimization effectiveness

## Commands

```bash
# Start the AI-enhanced MCP server (usually called by MCP client)
mcp-prompt-optimizer

# Configure API key
mcp-prompt-optimizer --setup

# Show help with AI features
mcp-prompt-optimizer --help

# Show version (now v1.1.0 with AI features)
mcp-prompt-optimizer --version

# Test AI-enhanced package functionality
npm test
```

## Troubleshooting

### API Key Issues

```bash
# Reconfigure your API key
mcp-prompt-optimizer --setup
```

### Connection Issues

1. Verify your internet connection
2. Check that your API key is valid at [the dashboard](https://promptoptimizer-blog.vercel.app/dashboard)
3. Ensure your subscription is active and supports AI features
4. Try regenerating your API key from the dashboard
5. Check backend status: `curl https://p01--project-optimizer--fvrdk8m9k9j.code.run/health`

### AI Context Detection Issues

1. Verify that your prompt contains AI-specific indicators (--ar, "act as", code blocks)
2. Try manually specifying the `ai_context` parameter
3. Check that `preserve_formatting` is set to `true` for technical prompts
4. Review the optimization response for AI context detection results

### MCP Client Configuration

1. Make sure the configuration file path is correct
2. Restart your MCP client after configuration changes
3. Check that Node.js is installed and accessible
4. Verify the package is installed globally: `npm list -g mcp-prompt-optimizer`

### Backend Connection

If you experience backend connectivity issues:

```bash
# Test AI-enhanced backend directly
curl -X GET "https://p01--project-optimizer--fvrdk8m9k9j.code.run/health"

# Test with your API key
curl -X POST "https://p01--project-optimizer--fvrdk8m9k9j.code.run/api/v1/validate-key" \
     -H "X-API-Key: your-api-key-here"
```

## Configuration File Location

Your API key is stored securely at:
- **Windows**: `%USERPROFILE%\.prompt-optimizer\config.json`
- **macOS/Linux**: `~/.prompt-optimizer\config.json`

The configuration includes:
```json
{
  "apiKey": "sk-opt-your-key-here",
  "backendUrl": "https://p01--project-optimizer--fvrdk8m9k9j.code.run",
  "updatedAt": "2025-06-21T12:00:00.000Z",
  "aiFeatures": true,
  "version": "1.1.0"
}
```

## Environment Variables

Override configuration with environment variables:

- `PROMPT_OPTIMIZER_API_KEY`: Override stored API key
- `PROMPT_OPTIMIZER_BACKEND_URL`: Override backend URL
- `NODE_ENV`: Set to 'development' for debug logging
- `AI_CONTEXT_DEBUG`: Enable AI context detection debugging

Example:
```bash
PROMPT_OPTIMIZER_API_KEY=sk-opt-your-key AI_CONTEXT_DEBUG=true mcp-prompt-optimizer
```

## API Compatibility

This package is compatible with the AI-Enhanced FastAPI backend API version 0.3.0+ and supports:

- ✅ **MCP Protocol 2024-11-05** - Latest MCP specification
- ✅ **AI Context Detection** - Automatic detection of image generation, LLM interaction, technical automation
- ✅ **Parameter Preservation** - Technical parameter preservation during optimization
- ✅ **Enhanced Goal Mapping** - Automatic goal enhancement based on AI context
- ✅ **Target AI Model Support** - Model-specific optimization strategies
- ✅ **API Key Authentication** - Secure `sk-opt-` format keys
- ✅ **Base64 Config Encoding** - MCP protocol compliance
- ✅ **Real-time Quota Tracking** - Usage monitoring with AI analytics
- ✅ **Error Handling** - Comprehensive error responses
- ✅ **Rate Limiting** - Automatic retry logic
- ✅ **AI Template Persistence** - Automatic optimization history with AI metadata

## Intellectual Property

- **Your Prompts, Your IP**: You retain full intellectual property rights over all prompts you create and optimize
- **Service Provision**: We provide AI-enhanced optimization as a service - we do not claim ownership over your content
- **AI Template Storage**: Saved templates with AI metadata are for your reference and remain your intellectual property
- **Privacy Protected**: Your prompts, AI contexts, and templates are private and accessible only to your account
- **Data Export**: You can export your AI optimization history and templates at any time

## Support

- 📚 [Documentation](https://promptoptimizer-blog.vercel.app/docs)
- 🎫 [Support Portal](https://promptoptimizer-blog.vercel.app/support)
- 🐛 [Report Issues](https://github.com/prompt-optimizer/mcp-prompt-optimizer/issues)
- 💬 [Community Discord](https://discord.gg/prompt-optimizer)
- 🤖 [AI Features Guide](https://promptoptimizer-blog.vercel.app/docs/ai-features)

## Security

- API keys are stored locally and never shared
- All communication uses HTTPS encryption with the AI-enhanced backend
- No prompt data is stored permanently beyond template history (which you control)
- AI context detection happens server-side with privacy protection
- Full audit trail of AI optimization usage available in dashboard
- Compliance with enterprise security standards
- AI template data encrypted at rest and in transit

## Development

### Testing

```bash
# Run package tests (includes AI feature tests)
npm test

# Manual server test
node test-package.js
```

### Local Development

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

# Install dependencies
npm install

# Test locally with AI features
npm test
```

## Changelog

### v1.1.0 - AI Enhancement Release 🚀
- 🧠 **NEW**: Automatic AI context detection for image generation, LLM interaction, and technical automation
- 🛡️ **NEW**: Parameter preservation for technical prompts (Midjourney parameters, code blocks, URLs)
- 🎯 **NEW**: 9 AI-specific optimization goals (keyword_density, parameter_preservation, etc.)
- 🤖 **NEW**: Smart goal enhancement based on detected AI context
- 🔧 **NEW**: Target AI model specification support
- 📊 **NEW**: Enhanced optimization response with AI context information
- ⚡ **IMPROVED**: Better optimization strategies for different AI use cases

### v1.0.3
- ✅ Fixed binary execution issue on Windows systems
- ✅ Enhanced error handling for server responses
- ✅ Improved version detection for global installations

### v1.0.2
- ✅ Fixed pricing information discrepancy in documentation
- ✅ Improved documentation consistency across all package files

### v1.0.1
- ✅ Updated backend URL to production deployment
- ✅ Enhanced error handling for server responses
- ✅ Improved repository information
- ✅ Added comprehensive backend infrastructure documentation
- ✅ Added template saving feature documentation

### v1.0.0
- 🎉 Initial release with MCP protocol support
- ✅ Claude Desktop, Cursor, and Windsurf compatibility
- ✅ API key authentication system
- ✅ Complete optimization goal support

## License

**Commercial License** - This software is licensed for commercial use. See LICENSE file for details.

**Your Content**: You retain full intellectual property rights over all prompts, templates, and content you create using this AI-enhanced service.

---

**Made with ❤️ by the Prompt Optimizer Team**  
*Empowering better AI interactions through intelligent, context-aware prompt optimization*