A scalable, template-based API for executing cursor-agent commands with various prompt templates.
The application follows a clean, modular architecture with clear separation of concerns:
cursor_cli_agent_usage/
βββ main.py # FastAPI entry point
βββ config.py # Configuration & environment variables
βββ models.py # Pydantic request/response models
βββ services.py # Core business logic & cursor-agent integration
βββ routes.py # API route definitions
βββ templates/ # Template system
β βββ __init__.py # Template registry
β βββ base.py # Base template class
β βββ rca_template.py # RCA & test templates
β βββ [your_template].py # Add more templates here!
βββ html_format.txt # HTML formatting instructions
βββ README.md # This file
- β Template-Based System: Easily add new prompt templates
- β Type-Safe: Full Pydantic validation for requests/responses
- β Scalable: Registry pattern for managing templates
- β Database Ready: Placeholder for PostgreSQL integration
- β Environment-Based Config: All settings via environment variables
- β Backward Compatible: Legacy endpoints still work
- β
Well-Documented: OpenAPI/Swagger docs at
/docs
- Python 3.8+
cursor-agentbinary installed- Required Python packages (see Installation)
- Clone the repository
- Install dependencies:
pip install fastapi uvicorn pydantic requests- Set environment variables (optional):
export CURSOR_API_KEY="your_api_key_here"
export CURSOR_MODEL="grok" # or claude-sonnet-4, etc.
export API_PORT="8170"
export DATABASE_URL="postgresql://user:pass@localhost/db" # For future usepython main.pyThe API will be available at http://localhost:8170
- Swagger UI: http://localhost:8170/docs
- ReDoc: http://localhost:8170/redoc
GET /healthGET /templatesReturns all available templates with their metadata.
POST /test-cursorSimple test to verify cursor-agent is working.
POST /generate-rca
Content-Type: application/json
{
"ticket_name": "ENG-12345",
"api_key": "optional_override",
"custom_prompt": "optional_custom_prompt"
}POST /agent/execute
Content-Type: application/json
{
"template_name": "rca",
"parameters": {
"incident_id": "ENG-12345",
"custom_instructions": "Focus on database issues"
},
"api_key": "optional_override",
"include_html_format": true
}POST /agent/execute-and-store
Content-Type: application/json
{
"template_name": "rca",
"parameters": {
"incident_id": "ENG-12345"
},
"store_in_db": true,
"metadata": {
"user": "john.doe",
"priority": "high"
}
}Adding a new template is simple! Follow these steps:
Create a new file in templates/ directory (e.g., templates/code_review_template.py):
from templates.base import BaseTemplate, TemplateMetadata
class CodeReviewTemplate(BaseTemplate):
"""Template for code review requests"""
@property
def metadata(self) -> TemplateMetadata:
return TemplateMetadata(
name="code_review",
description="Review code and provide feedback",
required_params=["code", "language"],
optional_params=["focus_areas"],
version="1.0.0",
author="Your Name"
)
def render(self, **kwargs) -> str:
# Validate parameters
is_valid, error = self.validate_params(**kwargs)
if not is_valid:
raise ValueError(error)
code = kwargs["code"]
language = kwargs["language"]
focus_areas = self.get_param(kwargs, "focus_areas", "general best practices")
prompt = f"""
# Code Review Request
**Language**: {language}
**Code**:
```{language}
{code}Focus Areas: {focus_areas}
Please review this code and provide:
- Code quality assessment
- Potential bugs or issues
- Performance considerations
- Best practice recommendations
- Security concerns (if any) """ return prompt
### Step 2: Register Your Template
Edit `templates/__init__.py` and add your template:
```python
from templates.code_review_template import CodeReviewTemplate
class TemplateRegistry:
def _register_default_templates(self):
self.register(RCATemplate())
self.register(SimpleTestTemplate())
self.register(CodeReviewTemplate()) # Add this line
POST /agent/execute
Content-Type: application/json
{
"template_name": "code_review",
"parameters": {
"code": "def hello():\n print('world')",
"language": "python",
"focus_areas": "error handling"
}
}That's it! Your template is now available throughout the API.
class BugAnalysisTemplate(BaseTemplate):
@property
def metadata(self) -> TemplateMetadata:
return TemplateMetadata(
name="bug_analysis",
description="Analyze a bug report",
required_params=["bug_id", "description"],
optional_params=["logs", "steps_to_reproduce"]
)
def render(self, **kwargs) -> str:
is_valid, error = self.validate_params(**kwargs)
if not is_valid:
raise ValueError(error)
bug_id = kwargs["bug_id"]
description = kwargs["description"]
logs = self.get_param(kwargs, "logs", "No logs provided")
return f"""
Analyze bug {bug_id}:
Description: {description}
Logs: {logs}
Please provide:
1. Root cause analysis
2. Affected components
3. Potential fix
4. Prevention strategy
"""class PerformanceAuditTemplate(BaseTemplate):
@property
def metadata(self) -> TemplateMetadata:
return TemplateMetadata(
name="performance_audit",
description="Audit system performance",
required_params=["service_name", "metrics"],
optional_params=["time_range"]
)
def render(self, **kwargs) -> str:
is_valid, error = self.validate_params(**kwargs)
if not is_valid:
raise ValueError(error)
service = kwargs["service_name"]
metrics = kwargs["metrics"]
time_range = self.get_param(kwargs, "time_range", "last 24 hours")
return f"""
Performance Audit for {service}
Time Range: {time_range}
Metrics: {metrics}
Analyze and provide:
1. Performance bottlenecks
2. Resource utilization
3. Optimization opportunities
4. Recommendations
"""All configuration is managed through environment variables with sensible defaults:
| Variable | Default | Description |
|---|---|---|
CURSOR_API_KEY |
(hardcoded) | API key for cursor-agent |
CURSOR_MODEL |
grok |
Model to use |
API_HOST |
0.0.0.0 |
API server host |
API_PORT |
8170 |
API server port |
LOG_FILE |
rca_app.log |
Log file path |
CURSOR_AGENT_TIMEOUT |
300 |
Timeout in seconds |
DATABASE_URL |
None |
PostgreSQL connection string (future) |
The store_agent_result_in_db() function in services.py is a placeholder for PostgreSQL integration. To implement:
- Install PostgreSQL driver:
pip install asyncpg - Update
services.pywith actual database logic - Set
DATABASE_URLenvironment variable - Use
/agent/execute-and-storeendpoint
Example implementation:
async def store_agent_result_in_db(template_name, prompt, result, metadata):
import asyncpg
conn = await asyncpg.connect(DATABASE_URL)
try:
query = """
INSERT INTO agent_results
(template_name, prompt, result, metadata, created_at)
VALUES ($1, $2, $3, $4, NOW())
RETURNING id
"""
record_id = await conn.fetchval(
query,
template_name,
prompt,
json.dumps(result),
json.dumps(metadata)
)
return record_id
finally:
await conn.close()Test the API with curl:
# Health check
curl http://localhost:8170/health
# List templates
curl http://localhost:8170/templates
# Execute RCA
curl -X POST http://localhost:8170/generate-rca \
-H "Content-Type: application/json" \
-d '{"ticket_name": "ENG-12345"}'
# Execute with template
curl -X POST http://localhost:8170/agent/execute \
-H "Content-Type: application/json" \
-d '{
"template_name": "rca",
"parameters": {"incident_id": "ENG-12345"}
}'- Template Naming: Use lowercase with underscores (e.g.,
code_review,bug_analysis) - Parameter Validation: Always validate required parameters in your templates
- Error Handling: Templates should raise
ValueErrorfor validation errors - Documentation: Add clear docstrings to your templates
- Versioning: Update template version when making changes
- Testing: Test your templates before deploying
# Install cursor-cli-agent
# Follow installation instructions from cursor-cli-agent documentation# Check if template is registered in templates/__init__.py
# Verify template name matches exactly (case-sensitive)
curl http://localhost:8170/templates # List all available templates# For now, database is a placeholder
# Set DATABASE_URL when implementing actual database integration[Your License Here]
- Fork the repository
- Create a feature branch
- Add your template or feature
- Submit a pull request
For issues or questions, please open an issue on the repository.
Version: 2.0.0
Last Updated: 2025-10-01