Command Palette

Search for a command to run...

UnylyUnyly
Весь каталог

Context-Aware Prompt Optimizer

БесплатноНе проверен

MCP server middleware for intelligent prompt rewriting and optimization for GitHub Copilot and other AI assistants.

GitHubEmbed

Описание

MCP server middleware for intelligent prompt rewriting and optimization for GitHub Copilot and other AI assistants.

README

An MCP (Model Context Protocol) server that acts as an intelligent middleware between users and GitHub Copilot. It rewrites vague prompts into clear, structured, context-rich prompts that produce better AI-generated code, explanations, and debugging help.

Features

  • Prompt rewriting — Rewrites vague prompts into clear, actionable ones with role framing and expected output format
  • Weighted intent detection — Heuristic detection with weighted scoring, position boosting, and ranked score breakdown
  • Multi-factor quality scoring — Scores prompts on clarity, specificity, completeness, and actionability
  • Context injection — Selective injection of file name, language, selected code, and project conventions
  • Rewrite modes — Light, standard, and aggressive modes for different levels of prompt enhancement
  • Transformation explanation — Step-by-step explanation of how and why each prompt was transformed
  • Before/after quality scores — Shows quality improvement from the rewrite
  • Structured output — Returns JSON with the rewritten prompt, intent, confidence, quality scores, and changes made
  • Multi-language support — Intent detection in English, German, Spanish, French, Portuguese, Japanese, and Chinese
  • Optional LLM enhancement — Optionally enhance rewrites with an OpenAI-compatible API for semantic understanding
  • Short prompt guidance — Automatically adds comprehensive output guidance for very brief prompts
  • Validated configuration — All config validated with Zod at startup; invalid values fail fast

Quick Start

With Docker Hub (fastest)

# Pull and run directly from Docker Hub
docker run -i --rm dash18/mcp-context-aware-prompt-optimizer:latest

Build locally with Docker

# Install, build, and test in one step
docker compose run --rm dev

# Build the production image
docker compose build server

Without Docker

npm install
npm run build
npm run dev   # development
npm start     # production

VS Code / Copilot Integration

Add to your .vscode/mcp.json (or VS Code settings.json):

Using Docker (recommended):

{
  "servers": {
    "prompt-optimizer": {
      "type": "stdio",
      "command": "docker",
      "args": ["run", "-i", "--rm", "dash18/mcp-context-aware-prompt-optimizer:latest"]
    }
  }
}

Using Node.js directly (via npx):

{
  "servers": {
    "prompt-optimizer": {
      "type": "stdio",
      "command": "npx",
      "args": ["tsx", "/absolute/path/to/src/server.ts"]
    }
  }
}

Using built output:

{
  "mcp": {
    "servers": {
      "prompt-optimizer": {
        "type": "stdio",
        "command": "node",
        "args": ["/absolute/path/to/dist/server.js"]
      }
    }
  }
}

MCP Tools

rewrite_prompt

Rewrite a raw prompt into an optimized version with intent detection, role framing, and context injection.

Example 1 — vague bug fix prompt:

// Input
{
  "prompt": "fix this bug",
  "mode": "standard",
  "context": {
    "fileName": "parser.ts",
    "language": "typescript",
    "selectedCode": "function parse(input: string) { return JSON.parse(input); }"
  }
}
// Output
{
  "originalPrompt": "fix this bug",
  "rewrittenPrompt": "You are a senior debugging assistant. Fix this bug in parser.ts. Analyze the code, identify the likely bug or error, explain the root cause, and provide a minimal fix. Preserve existing behavior except for the bug fix. The code is written in typescript. ...",
  "intent": "debug",
  "rewriteMode": "standard",
  "contextUsed": {
    "language": "typescript",
    "fileName": "parser.ts",
    "hasSelection": true,
    "hasNearbyCode": false
  },
  "confidence": 0.87,
  "changes": [
    "Added role framing",
    "Expanded task instruction from intent template",
    "Injected project context"
  ],
  "explanation": {
    "steps": [
      "Set assistant role to \"You are a senior debugging assistant.\" based on detected intent \"debug\"",
      "Combined original prompt with intent-specific instruction template for detailed guidance",
      "Appended file/language/code context for grounding"
    ],
    "summary": "Transformed \"fix this bug\" → improved prompt with 3 enhancements: Set assistant role..., Combined original prompt..., Appended file/language/code context...."
  },
  "qualityBefore": 0.37,
  "qualityAfter": 0.72
}

Example 2 — test generation:

// Input
{ "prompt": "write tests", "mode": "aggressive", "context": { "language": "python", "fileName": "auth.py" } }
// Output (abridged)
{
  "originalPrompt": "write tests",
  "rewrittenPrompt": "You are a senior QA engineer and test author. Write tests in auth.py. Write focused unit tests covering normal cases, edge cases, and error handling. ... Structure tests using describe/it blocks. Use idiomatic python patterns. Be concise. Prioritize actionable output. ...",
  "intent": "test",
  "rewriteMode": "aggressive",
  "confidence": 0.83,
  "qualityBefore": 0.32,
  "qualityAfter": 0.68
}

analyze_prompt

Analyze a prompt's quality across multiple factors without rewriting it.

// Input
{ "prompt": "optimize this" }
// Output
{
  "prompt": "optimize this",
  "intent": "optimize",
  "confidence": 0.83,
  "quality": {
    "overall": 0.38,
    "factors": [
      { "name": "clarity", "score": 0.4, "feedback": "Short prompt — could use more detail" },
      { "name": "specificity", "score": 0.25, "feedback": "Uses vague references ('this', 'it') without enough context" },
      { "name": "completeness", "score": 0.3, "feedback": "Missing constraints or expected output" },
      { "name": "actionability", "score": 0.9, "feedback": "Contains a clear, strong action verb" }
    ],
    "issues": [
      "Short prompt — could use more detail",
      "Uses vague references ('this', 'it') without enough context",
      "Missing constraints or expected output"
    ],
    "strengths": [
      "Contains a clear, strong action verb"
    ]
  }
}

suggest_prompt_improvements

Get concrete improvement suggestions and a sample rewrite.

// Input
{ "prompt": "fix it" }
// Output
{
  "prompt": "fix it",
  "suggestions": [
    "Very short prompt — likely too vague to produce good results",
    "Uses vague references ('this', 'it') without enough context",
    "No clear action verb detected",
    "Specify the programming language for more targeted help",
    "Include the relevant code selection for context"
  ],
  "exampleRewrite": "You are a senior debugging assistant. Fix it. Analyze the code, identify the likely bug or error, explain the root cause, and provide a minimal fix. Preserve existing behavior except for the bug fix.",
  "intent": "debug"
}

Rewrite Modes

Mode Behavior
light Minimal cleanup: capitalization, punctuation, optional language tag
standard Role framing + intent template + context injection
aggressive Everything in standard + format hints + language idiom + conciseness

Quality Factors

Factor Weight What it measures
clarity 30% Prompt length and readability
specificity 30% Named entities, language references, avoidance of vague refs
completeness 20% Constraints, expected output format, scope
actionability 20% Presence and strength of action verbs

Configuration

All configuration via environment variables with sensible defaults. Validated with Zod at startup — invalid values will cause a clear error immediately.

Variable Default Description
PROMPT_OPT_DEFAULT_MODE standard Default rewrite mode
PROMPT_OPT_MAX_LENGTH 2000 Max rewritten prompt length
PROMPT_OPT_ROLE_FRAMING true Enable role framing in rewrites
PROMPT_OPT_CONTEXT_INJECTION true Enable automatic context injection
PROMPT_OPT_MAX_CODE_LINES 60 Max lines of code context
PROMPT_OPT_SERVER_NAME context-aware-prompt-optimizer Server name in MCP
PROMPT_OPT_SERVER_VERSION 1.0.0 Server version
PROMPT_OPT_LLM_ENDPOINT (none) OpenAI-compatible API URL (optional)
PROMPT_OPT_LLM_API_KEY (none) API key for LLM endpoint (optional)
PROMPT_OPT_LLM_MODEL gpt-4o-mini LLM model name

Optional LLM Enhancement

When PROMPT_OPT_LLM_ENDPOINT and PROMPT_OPT_LLM_API_KEY are set, the rewrite_prompt tool will call an OpenAI-compatible API to produce a semantically richer rewrite. If the LLM call fails, it falls back to the heuristic rewrite silently.

# Example: Use OpenAI
docker run -i --rm \
  -e PROMPT_OPT_LLM_ENDPOINT=https://api.openai.com/v1/chat/completions \
  -e PROMPT_OPT_LLM_API_KEY=sk-... \
  -e PROMPT_OPT_LLM_MODEL=gpt-4o-mini \
  dash18/mcp-context-aware-prompt-optimizer:latest

Project Structure

src/
├── server.ts                    # MCP server entry point
├── config.ts                    # Zod-validated environment configuration
├── types.ts                     # Zod schemas and TypeScript types
├── tools/
│   ├── rewritePrompt.ts         # rewrite_prompt tool handler (+ LLM integration)
│   ├── analyzePrompt.ts         # analyze_prompt tool handler
│   └── suggestImprovements.ts   # suggest_prompt_improvements handler
└── services/
    ├── intentDetector.ts        # Weighted heuristic intent detection (multi-language)
    ├── contextCollector.ts      # Context string builder
    ├── llmRewriter.ts           # Optional LLM-backed rewrite service
    └── promptRewriter.ts        # Core rewriting + quality scoring engine
tests/
├── intentDetector.test.ts       # Intent detection tests (incl. multi-language)
├── promptRewriter.test.ts       # Rewriting + quality scoring tests
├── contextCollector.test.ts     # Context builder tests
└── toolHandlers.test.ts         # End-to-end tool handler + zod validation tests

Testing

# Via Docker
docker compose run --rm dev

# Without Docker
npm test

Docker Hub

Pre-built images available at dash18/mcp-context-aware-prompt-optimizer.

docker pull dash18/mcp-context-aware-prompt-optimizer:latest
docker pull dash18/mcp-context-aware-prompt-optimizer:1.0.0

License

MIT

from github.com/dashrathmundkar/mcp-context-aware-prompt-optimizer

Установка Context-Aware Prompt Optimizer

У этого сервера нет опубликованного пакета — он собирается из исходников. Открой репозиторий и следуй инструкции в README.

▸ github.com/dashrathmundkar/mcp-context-aware-prompt-optimizer

FAQ

Context-Aware Prompt Optimizer MCP бесплатный?

Да, Context-Aware Prompt Optimizer MCP бесплатный — установка в пару кликов через Unyly без оплаты.

Нужен ли API-ключ для Context-Aware Prompt Optimizer?

Нет, Context-Aware Prompt Optimizer работает без API-ключей и переменных окружения.

Context-Aware Prompt Optimizer — hosted или self-hosted?

Self-hosted: сервер запускается локально на твоей машине командой из раздела установки.

Как установить Context-Aware Prompt Optimizer в Claude Desktop, Claude Code или Cursor?

Открой Context-Aware Prompt Optimizer на unyly.org, выбери вкладку своего клиента (Claude Desktop, Claude Code, Cursor) и нажми Install — конфиг сгенерируется автоматически, без правки JSON.

Похожие MCP

Compare Context-Aware Prompt Optimizer with

Не уверен что выбрать?

Найди свой стек за 60 секунд

Автор?

Embed-бейдж для README

Похожее

Все в категории development