Skip to content

SohhamS/cursoir-cli-agent

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

2 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Cursor CLI Agent API

A scalable, template-based API for executing cursor-agent commands with various prompt templates.

πŸ—οΈ Architecture

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

πŸš€ Features

  • βœ… 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

πŸ“‹ Prerequisites

  • Python 3.8+
  • cursor-agent binary installed
  • Required Python packages (see Installation)

πŸ”§ Installation

  1. Clone the repository
  2. Install dependencies:
pip install fastapi uvicorn pydantic requests
  1. 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 use

🎯 Usage

Starting the Server

python main.py

The API will be available at http://localhost:8170

API Documentation

Available Endpoints

1. Health Check

GET /health

2. List Templates

GET /templates

Returns all available templates with their metadata.

3. Test Endpoint

POST /test-cursor

Simple test to verify cursor-agent is working.

4. Generate RCA (Legacy)

POST /generate-rca
Content-Type: application/json

{
  "ticket_name": "ENG-12345",
  "api_key": "optional_override",
  "custom_prompt": "optional_custom_prompt"
}

5. Execute with Template (Generic)

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
}

6. Execute and Store in Database

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 New Templates

Adding a new template is simple! Follow these steps:

Step 1: Create Your Template Class

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:

  1. Code quality assessment
  2. Potential bugs or issues
  3. Performance considerations
  4. Best practice recommendations
  5. 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

Step 3: Use Your Template

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.

🎨 Template Examples

Example 1: Bug Analysis Template

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
"""

Example 2: Performance Audit Template

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
"""

πŸ” Configuration

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)

πŸ“Š Database Integration (Placeholder)

The store_agent_result_in_db() function in services.py is a placeholder for PostgreSQL integration. To implement:

  1. Install PostgreSQL driver: pip install asyncpg
  2. Update services.py with actual database logic
  3. Set DATABASE_URL environment variable
  4. Use /agent/execute-and-store endpoint

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()

πŸ§ͺ Testing

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"}
  }'

πŸ“š Best Practices

  1. Template Naming: Use lowercase with underscores (e.g., code_review, bug_analysis)
  2. Parameter Validation: Always validate required parameters in your templates
  3. Error Handling: Templates should raise ValueError for validation errors
  4. Documentation: Add clear docstrings to your templates
  5. Versioning: Update template version when making changes
  6. Testing: Test your templates before deploying

πŸ› Troubleshooting

cursor-agent not found

# Install cursor-cli-agent
# Follow installation instructions from cursor-cli-agent documentation

Template not found

# 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

Database connection errors

# For now, database is a placeholder
# Set DATABASE_URL when implementing actual database integration

πŸ“„ License

[Your License Here]

πŸ‘₯ Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Add your template or feature
  4. Submit a pull request

πŸ“ž Support

For issues or questions, please open an issue on the repository.


Version: 2.0.0
Last Updated: 2025-10-01

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages