mcp-prompt-optimizer
Version:
Local MCP server for AI-Enhanced Prompt Optimizer API with context awareness and parameter preservation
294 lines (229 loc) • 7.65 kB
Markdown
# API Reference
This document describes the API endpoints used by the MCP Prompt Optimizer package to communicate with the backend.
## Base URL
The default backend URL is: `https://your-app.code.run`
*Note: Replace with your actual Northflank backend URL*
## Authentication
All API requests require an API key in the `X-API-Key` header:
```
X-API-Key: sk-opt-your-api-key-here
```
API keys can be generated from the [Prompt Optimizer Dashboard](https://promptoptimizer-blog.vercel.app/dashboard).
## Endpoints
### POST /api/v1/validate-key
Validate an API key and get user information.
**Headers:**
```
X-API-Key: sk-opt-your-api-key
Content-Type: application/json
```
**Response (200 OK):**
```json
{
"valid": true,
"user_id": "uuid-string",
"tier": "creator",
"quota_limit": 200,
"quota_used": 15,
"subscription_status": "active"
}
```
**Error Responses:**
- `401 Unauthorized`: Invalid or expired API key
- `403 Forbidden`: Subscription inactive
### POST /api/v1/mcp/optimize
Optimize a prompt using the MCP protocol format.
**Headers:**
```
X-API-Key: sk-opt-your-api-key
Content-Type: application/json
```
**Parameters:**
- `config` (query parameter): Base64-encoded JSON containing prompt and goals
**Config JSON Format (before base64 encoding):**
```json
{
"prompt": "Your prompt text to optimize",
"goals": ["clarity", "conciseness", "specificity"]
}
```
**Example Request:**
```bash
# Create base64 config
echo '{"prompt":"write code","goals":["clarity","technical_accuracy"]}' | base64
# Make request
curl -X POST "https://your-app.code.run/api/v1/mcp/optimize?config=eyJwcm9tcHQiOiJ3cml0ZSBjb2RlIiwiZ29hbHMiOlsiY2xhcml0eSIsInRlY2huaWNhbF9hY2N1cmFjeSJdfQ==" \
-H "X-API-Key: sk-opt-your-key"
```
**Response (200 OK):**
```json
{
"optimized_prompt": "Create a secure and efficient authentication system...",
"confidence_score": 0.87,
"metadata": {
"user_tier": "creator",
"quota_remaining": 185,
"source": "LLM",
"model_optimized_with": "gpt-4o-mini",
"duration_sec": 2.3
}
}
```
**Error Responses:**
- `400 Bad Request`: Invalid config parameter or malformed JSON
- `401 Unauthorized`: Invalid or missing API key
- `429 Too Many Requests`: Quota exceeded
- `500 Internal Server Error`: Optimization failed
### GET /api/v1/mcp/health
Check the health status of the MCP service.
**Response (200 OK):**
```json
{
"status": "healthy",
"service": "mcp-prompt-optimizer",
"version": "1.0.0",
"endpoints": ["/mcp/optimize"]
}
```
## Optimization Goals
The following optimization goals are supported:
| Goal | Description |
|------|-------------|
| `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 |
## Rate Limits
Rate limits are based on your subscription tier:
| Tier | Monthly Quota | API Keys |
|------|---------------|----------|
| Explorer | 20 optimizations | 0 (Web UI only) |
| Creator | 200 optimizations | 1 |
| Innovator | 450 optimizations | Up to 10 |
## Error Handling
### Error Response Format
```json
{
"detail": "Error message description",
"error_type": "QUOTA_EXCEEDED",
"metadata": {
"quota_limit": 200,
"quota_used": 200
}
}
```
### Common Error Types
- `INVALID_API_KEY`: API key is invalid or expired
- `QUOTA_EXCEEDED`: Monthly optimization limit reached
- `SUBSCRIPTION_INACTIVE`: User subscription is not active
- `INVALID_REQUEST`: Malformed request or missing parameters
- `OPTIMIZATION_FAILED`: Backend optimization process failed
- `RATE_LIMITED`: Too many requests in a short time period
## Usage Examples
### Node.js Example
```javascript
const axios = require('axios');
async function optimizePrompt(apiKey, prompt, goals = ['clarity']) {
// Encode config as base64
const config = JSON.stringify({ prompt, goals });
const configB64 = Buffer.from(config).toString('base64');
try {
const response = await axios.post(
`https://your-app.code.run/api/v1/mcp/optimize?config=${encodeURIComponent(configB64)}`,
{},
{
headers: {
'X-API-Key': apiKey,
'Content-Type': 'application/json'
}
}
);
return response.data;
} catch (error) {
if (error.response?.status === 429) {
throw new Error('Quota exceeded');
}
throw error;
}
}
// Usage
optimizePrompt('sk-opt-your-key', 'write code', ['clarity', 'specificity'])
.then(result => console.log(result.optimized_prompt))
.catch(error => console.error(error.message));
```
### Python Example
```python
import requests
import base64
import json
def optimize_prompt(api_key, prompt, goals=['clarity']):
# Encode config as base64
config = json.dumps({"prompt": prompt, "goals": goals})
config_b64 = base64.b64encode(config.encode()).decode()
response = requests.post(
f"https://your-app.code.run/api/v1/mcp/optimize?config={config_b64}",
headers={
"X-API-Key": api_key,
"Content-Type": "application/json"
}
)
if response.status_code == 429:
raise Exception("Quota exceeded")
response.raise_for_status()
return response.json()
# Usage
result = optimize_prompt('sk-opt-your-key', 'write code', ['clarity', 'specificity'])
print(result['optimized_prompt'])
```
### cURL Example
```bash
#!/bin/bash
API_KEY="sk-opt-your-key"
PROMPT="write code for login"
GOALS='["clarity","technical_accuracy"]'
# Create config and encode as base64
CONFIG=$(echo "{\"prompt\":\"$PROMPT\",\"goals\":$GOALS}" | base64 -w 0)
# Make request
curl -X POST \
"https://your-app.code.run/api/v1/mcp/optimize?config=$CONFIG" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
| jq '.optimized_prompt'
```
## SDK Integration
The MCP package (`mcp-prompt-optimizer`) handles all of these API calls automatically. Users don't need to interact with the API directly unless building custom integrations.
### MCP Package API
```javascript
const PromptOptimizerApiClient = require('mcp-prompt-optimizer/lib/api-client');
const client = new PromptOptimizerApiClient('sk-opt-your-key');
// Validate key
const userData = await client.validateKey();
// Optimize prompt
const result = await client.optimize('write code', ['clarity', 'specificity']);
// Check health
const health = await client.getHealthStatus();
```
## Security Considerations
1. **API Key Storage**: Store API keys securely, never in version control
2. **HTTPS Only**: All requests must use HTTPS
3. **Key Rotation**: Regenerate API keys periodically
4. **Rate Limiting**: Respect rate limits to avoid temporary blocks
5. **Error Handling**: Don't expose API keys in error logs
## Support
For API-related issues:
1. Check your API key validity in the [dashboard](https://promptoptimizer-blog.vercel.app/dashboard)
2. Verify your subscription is active
3. Review the error response details
4. Contact support through the website
## Changelog
### v1.0.0
- Initial API release
- Support for 10 optimization goals
- Subscription tier integration
- Rate limiting and quota management