# Cursor CLI Integration

> Integrate Cursor's CLI for headless code automation

Source: https://praison.ai/docs/code/cursor-cli/
# Cursor CLI Integration

PraisonAI provides integration with Cursor's CLI (cursor-agent) for headless code automation, file modifications, and streaming output.

## Installation

Download and install Cursor from [cursor.com](https://cursor.com), which includes the CLI.

```bash
# Verify installation
cursor-agent --version
```

## Quick Start

```python
from praisonai.integrations import CursorCLIIntegration

# Create integration
cursor = CursorCLIIntegration(
    workspace="/path/to/project",
    force=True  # Allow file modifications
)

# Execute a coding task
result = await cursor.execute("Fix the authentication bug")
print(result)
```

## Configuration Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `workspace` | str | "." | Working directory for CLI execution |
| `timeout` | int | 300 | Timeout in seconds |
| `output_format` | str | "json" | Output format: "json", "text", "stream-json" |
| `force` | bool | False | Allow file modifications |
| `model` | str | None | Model to use (e.g., "gpt-5") |
| `stream_partial` | bool | False | Stream partial output |
| `resume_session` | str | None | Session ID to resume |

## Examples

### Basic Execution

```python
from praisonai.integrations import CursorCLIIntegration

cursor = CursorCLIIntegration(workspace="/project")

result = await cursor.execute("Explain the main.py file")
print(result)
```

### Force Mode (File Modifications)

```python
cursor = CursorCLIIntegration(
    workspace="/project",
    force=True  # Enable file modifications
)

result = await cursor.execute("Refactor the utils module")
```

### Model Selection

```python
cursor = CursorCLIIntegration(
    workspace="/project",
    model="gpt-5"  # Use GPT-5
)

result = await cursor.execute("Complex refactoring task")
```

### Session Resume

```python
cursor = CursorCLIIntegration(workspace="/project")

# First task
result1 = await cursor.execute("Analyze the codebase")

# Resume with a specific session
cursor_resume = CursorCLIIntegration(
    workspace="/project",
    resume_session="session-abc123"
)

result2 = await cursor_resume.execute("Continue the analysis")
```

### Streaming Output

```python
cursor = CursorCLIIntegration(
    workspace="/project",
    stream_partial=True
)

async for event in cursor.stream("Add comprehensive tests"):
    event_type = event.get("type")
    content = event.get("content", "")
    
    if event_type == "text":
        print(content, end="", flush=True)
    elif event_type == "tool_use":
        print(f"\n[Tool: {event.get('name')}]")
    elif event_type == "result":
        print(f"\nResult: {content}")
```

### As Agent Tool

```python
from praisonai import Agent
from praisonai.integrations import CursorCLIIntegration

cursor = CursorCLIIntegration(
    workspace="/project",
    force=True
)

# Create tool
tool = cursor.as_tool()

# Use with agent
agent = Agent(
    name="Code Assistant",
    role="Software Developer",
    goal="Help with coding tasks",
    tools=[tool]
)

result = agent.start("Add error handling to all functions")
```

### As a native async agent tool

Preferred when the agent runs on `agent.astart(...)` (or any async entrypoint) — the tool is awaited directly on the running loop with no thread hop.

```python
from praisonaiagents import Agent
from praisonai.integrations import CursorCLIIntegration

cursor = CursorCLIIntegration(workspace="/project", force=True)

agent = Agent(
    name="Code Assistant",
    role="Software Developer",
    goal="Help with coding tasks",
    tools=[cursor.as_async_tool()],   # registers as `cursor-agent_atool`
)

await agent.astart("Add error handling to all functions")
```

`as_async_tool()` was added in PraisonAI PR #4022; `as_tool()` still works and is now also safe to call from inside an async agent runtime.

## Environment Variables

```bash
# API Key (required for headless mode)
export CURSOR_API_KEY=your-key
```

## CLI Flags Used

The integration uses the following Cursor CLI flags:

| Flag | Description |
|------|-------------|
| `-p` | Print mode (headless) |
| `--force` | Allow file modifications |
| `-m` | Model selection |
| `--output-format json` | JSON output for parsing |
| `--stream-partial-output` | Stream partial results |
| `--resume` | Resume a previous session |

## Output Formats

### JSON Output

```json
{
  "result": "Task completed successfully",
  "files_modified": ["src/main.py", "src/utils.py"],
  "summary": "Refactored 3 functions"
}
```

### Stream JSON Output

```json
{"type": "start", "session_id": "abc123"}
{"type": "text", "content": "Analyzing..."}
{"type": "tool_use", "name": "read_file", "path": "main.py"}
{"type": "text", "content": "Found issues..."}
{"type": "result", "content": "Completed"}
```

## Error Handling

```python
from praisonai.integrations import CursorCLIIntegration

cursor = CursorCLIIntegration(timeout=120)

try:
    result = await cursor.execute("Complex task")
except TimeoutError:
    print("Task timed out")
except Exception as e:
    print(f"Error: {e}")
```

## Authentication

Cursor CLI supports two authentication methods:

### Browser-Based Login (Recommended)

```bash
# Log in using browser flow
cursor-agent login

# Check authentication status
cursor-agent status

# Log out
cursor-agent logout
```

### API Key

```bash
export CURSOR_API_KEY=your-key
```

## Best Practices

1. **Use force=True** only when file modifications are needed
2. **Set appropriate model** based on task complexity
3. **Use session resume** for multi-step tasks
4. **Enable streaming** for long-running tasks
5. **Set timeouts** appropriate for task complexity
6. **Use JSON output** for programmatic processing
