### Start Cursor Agent Source: https://cursor.com/docs/cli/installation Initializes and starts the Cursor Agent after installation and PATH configuration. ```bash agent ``` -------------------------------- ### Install and authenticate CLI Source: https://cursor.com/docs/cli/headless Installation commands for different operating systems and setting the API key for headless execution. ```bash # Install Cursor CLI (macOS, Linux, WSL) curl https://cursor.com/install -fsS | bash # Install Cursor CLI (Windows PowerShell) irm 'https://cursor.com/install?win32=true' | iex # Set API key for scripts export CURSOR_API_KEY=your_api_key_here agent -p "Analyze this code" ``` -------------------------------- ### Install Cursor CLI (macOS, Linux, WSL) Source: https://cursor.com/docs/cli/installation Installs the Cursor CLI using a curl command. This is the primary installation method for Unix-like systems. ```bash curl https://cursor.com/install -fsS | bash ``` -------------------------------- ### Install Cursor CLI (Windows Native) Source: https://cursor.com/docs/cli/installation Installs the Cursor CLI on native Windows environments using PowerShell. It fetches and executes the installation script. ```powershell irm 'https://cursor.com/install?win32=true' | iex ``` -------------------------------- ### Install and Run Cursor CLI Source: https://cursor.com/docs/cli/overview Commands to install the CLI on various operating systems and initiate an interactive session. ```bash # Install (macOS, Linux, WSL) curl https://cursor.com/install -fsS | bash # Install (Windows PowerShell) irm 'https://cursor.com/install?win32=true' | iex # Run interactive session agent ``` -------------------------------- ### Install and Run Cursor CLI in GitHub Actions Source: https://cursor.com/docs/cli/github-actions Installs the Cursor CLI and sets up the agent to run with a prompt. Ensure CURSOR_API_KEY is configured as a secret. ```yaml - name: Install Cursor CLI run: | curl https://cursor.com/install -fsS | bash echo "$HOME/.cursor/bin" >> $GITHUB_PATH - name: Run Cursor Agent env: CURSOR_API_KEY: ${{ secrets.CURSOR_API_KEY }} run: | agent -p "Your prompt here" --model gpt-5 ``` -------------------------------- ### Combine File Paths and Text Instructions for Agent Source: https://cursor.com/docs/cli/headless This example shows how to combine file path references with textual instructions for the agent. It's useful for tasks that require analyzing code and design mockups simultaneously. ```bash # Combine file paths with text instructions agent -p "Review the code in src/app.ts and the design mockup in designs/homepage.png. Suggest improvements to match the design." ``` -------------------------------- ### Stream progress tracking Source: https://cursor.com/docs/cli/headless Initial setup for tracking CLI progress in real-time using streaming output formats. ```bash #!/bin/bash # stream-progress.sh - Track progress in real-time echo "šŸš€ Starting stream processing..." ``` -------------------------------- ### Start ACP Server Source: https://cursor.com/docs/cli/acp Starts the Cursor CLI in ACP mode, enabling communication with custom clients. ```APIDOC ## Start ACP Server Start Cursor CLI in ACP mode: ```bash agent acp ``` ``` -------------------------------- ### Verify Cursor CLI Installation Source: https://cursor.com/docs/cli/installation Checks if the Cursor CLI has been installed correctly by displaying its version information. ```bash agent --version ``` -------------------------------- ### Using MCP Servers with Agent Source: https://cursor.com/docs/cli/mcp Examples demonstrating how to interact with MCP servers and use their tools with the agent. The agent automatically discovers and uses available tools. ```bash # Check what MCP servers are available agent mcp list ``` ```bash # See what tools a specific server provides agent mcp list-tools playwright ``` ```bash # Use agent - it automatically uses MCP tools when helpful agent -p "Navigate to google.com and take a screenshot of the search page" ``` ```bash # Auto-approve all MCP servers (skip approval prompts) agent --approve-mcps "query my database for recent errors" ``` -------------------------------- ### Example Text Output Source: https://cursor.com/docs/cli/reference/output-format Demonstrates the clean output of the 'text' format, showing only the final assistant message without any intermediate steps. ```text The command to move this branch onto main is `git rebase --onto main HEAD~3`. ``` -------------------------------- ### Start Interactive Sessions Source: https://cursor.com/docs/cli/overview Initiate conversational sessions with the agent, optionally providing an initial prompt. ```bash # Start interactive session agent # Start with initial prompt agent "refactor the auth module to use JWT tokens" ``` -------------------------------- ### Select CLI Model Source: https://cursor.com/docs/cli/reference/configuration Examples of using the /model slash command to select a language model for the CLI. ```bash /model auto ``` ```bash /model gpt-5 ``` ```bash /model sonnet-4-thinking ``` -------------------------------- ### CLI Configuration Permissions Source: https://cursor.com/docs/cli/reference/permissions Example JSON configuration for setting allow and deny lists for various permission types in the CLI configuration file. ```json { "permissions": { "allow": [ "Shell(ls)", "Shell(git)", "Read(src/**/*.ts)", "Write(package.json)", "WebFetch(docs.github.com)", "WebFetch(*.github.com)", "Mcp(datadog:*)" ], "deny": [ "Shell(rm)", "Read(.env*)", "Write(**/*.key)", "WebFetch(malicious-site.com)" ] } } ``` -------------------------------- ### Start ACP Server Source: https://cursor.com/docs/cli/acp Start the Cursor CLI in ACP mode to enable agent client protocol communication. ```bash agent acp ``` -------------------------------- ### Cursor Extension: Ask Question Request Example Source: https://cursor.com/docs/cli/acp Example JSON-RPC request for the `cursor/ask_question` extension method, used to present multiple-choice questions to the user. ```json { "toolCallId": "call_123", "title": "Need input", "questions": [ { "id": "q1", "prompt": "Which mode should I use?", "options": [ { "id": "agent", "label": "Agent" }, { "id": "plan", "label": "Plan" } ], "allowMultiple": false } ] } ``` -------------------------------- ### Tool Call Started Event Source: https://cursor.com/docs/cli/reference/output-format Tracks the start of a tool call, including the call ID and arguments. ```json { "type": "tool_call", "subtype": "started", "call_id": "", "tool_call": { "readToolCall": { "args": { "path": "file.txt" } } }, "session_id": "" } ``` -------------------------------- ### Write Tool Call Started Event Source: https://cursor.com/docs/cli/reference/output-format Specific structure for the start of a write tool call, including path, text content, and tool call ID. ```json { "type": "tool_call", "subtype": "started", "call_id": "", "tool_call": { "writeToolCall": { "args": { "path": "file.txt", "fileText": "content...", "toolCallId": "id" } } } , "session_id": "" } ``` -------------------------------- ### Example NDJSON Sequence Source: https://cursor.com/docs/cli/reference/output-format This NDJSON sequence illustrates a typical interaction flow, including system initialization, user messages, tool calls (read and write), and assistant responses. It's useful for understanding the sequence of events in a session. ```json {"type":"system","subtype":"init","apiKeySource":"login","cwd":"/Users/user/project","session_id":"c6b62c6f-7ead-4fd6-9922-e952131177ff","model":"Claude 4 Sonnet","permissionMode":"default"} {"type":"user","message":{"role":"user","content":[{"type":"text","text":"Read README.md and create a summary"}]},"session_id":"c6b62c6f-7ead-4fd6-9922-e952131177ff"} {"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"I'll read the README.md file"}]},"session_id":"c6b62c6f-7ead-4fd6-9922-e952131177ff"} {"type":"tool_call","subtype":"started","call_id":"toolu_vrtx_01NnjaR886UcE8whekg2MGJd","tool_call":{"readToolCall":{"args":{"path":"README.md"}}},"session_id":"c6b62c6f-7ead-4fd6-9922-e952131177ff"} {"type":"tool_call","subtype":"completed","call_id":"toolu_vrtx_01NnjaR886UcE8whekg2MGJd","tool_call":{"readToolCall":{"args":{"path":"README.md"},"result":{"success":{"content":"# Project\n\nThis is a sample project...","isEmpty":false,"exceededLimit":false,"totalLines":54,"totalChars":1254}}}},"session_id":"c6b62c6f-7ead-4fd6-9922-e952131177ff"} {"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"Based on the README, I'll create a summary"}]},"session_id":"c6b62c6f-7ead-4fd6-9922-e952131177ff"} {"type":"tool_call","subtype":"started","call_id":"toolu_vrtx_01Q3VHVnWFSKygaRPT7WDxrv","tool_call":{"writeToolCall":{"args":{"path":"summary.txt","fileText":"# README Summary\n\nThis project contains...","toolCallId":"toolu_vrtx_01Q3VHVnWFSKygaRPT7WDxrv"}}},"session_id":"c6b62c6f-7ead-4fd6-9922-e952131177ff"} {"type":"tool_call","subtype":"completed","call_id":"toolu_vrtx_01Q3VHVnWFSKygaRPT7WDxrv","tool_call":{"writeToolCall":{"args":{"path":"summary.txt","fileText":"# README Summary\n\nThis project contains...","toolCallId":"toolu_vrtx_01Q3VHVnWFSKygaRPT7WDxrv"},"result":{"success":{"path":"/Users/user/project/summary.txt","linesCreated":19,"fileSize":942}}}},"session_id":"c6b62c6f-7ead-4fd6-9922-e952131177ff"} {"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"Done! I've created the summary in summary.txt"}]},"session_id":"c6b62c6f-7ead-4fd6-9922-e952131177ff"} {"type":"result","subtype":"success","duration_ms":5234,"duration_api_ms":5234,"is_error":false,"result":"I'll read the README.md fileBased on the README, I'll create a summaryDone! I've created the summary in summary.txt","session_id":"c6b62c6f-7ead-4fd6-9922-e952131177ff","request_id":"10e11780-df2f-45dc-a1ff-4540af32e9c0"} ``` -------------------------------- ### Setup Terminal for Newlines Source: https://cursor.com/docs/cli/reference/terminal-setup Run this command if Shift+Enter does not create newlines in your terminal. It detects your terminal and provides specific instructions for configuring an alternative, such as Option+Enter. ```bash /setup-terminal ``` -------------------------------- ### Automated code review script Source: https://cursor.com/docs/cli/headless Example of a shell script performing a code review and outputting results to a file. ```bash #!/bin/bash # simple-code-review.sh - Basic code review script echo "Starting code review..." # Review recent changes agent -p --force --output-format text \ "Review the recent code changes and provide feedback on: - Code quality and readability - Potential bugs or issues - Security considerations - Best practices compliance Provide specific suggestions for improvement and write to review.txt" if [ $? -eq 0 ]; then echo "āœ… Code review completed successfully" else echo "āŒ Code review failed" exit 1 fi ``` -------------------------------- ### Minimal Configuration Source: https://cursor.com/docs/cli/reference/configuration Sets up the basic CLI configuration with default editor settings and empty permissions. ```json { "version": 1, "editor": { "vimMode": false }, "permissions": { "allow": ["Shell(ls)"], "deny": [] } } ``` -------------------------------- ### System Initialization Event Source: https://cursor.com/docs/cli/reference/output-format Emitted once at the beginning of each session. Contains session and model information. ```json { "type": "system", "subtype": "init", "apiKeySource": "env|flag|login", "cwd": "/absolute/path", "session_id": "", "model": "", "permissionMode": "default" } ``` -------------------------------- ### Authentication Options for ACP Source: https://cursor.com/docs/cli/acp Authenticate before startup using existing CLI auth paths or pass endpoint and TLS options directly. ```bash agent --api-key "$CURSOR_API_KEY" acp ``` ```bash agent -e https://api2.cursor.sh acp ``` ```bash agent -k acp ``` -------------------------------- ### Enable Vim Mode Source: https://cursor.com/docs/cli/reference/configuration Configures the CLI to enable Vim keybindings in the editor. ```json { "version": 1, "editor": { "vimMode": true }, "permissions": { "allow": ["Shell(ls)"], "deny": [] } } ``` -------------------------------- ### Search codebase with CLI Source: https://cursor.com/docs/cli/headless Basic usage of the CLI to query a codebase using the default text output format. ```bash #!/bin/bash # Simple codebase question - uses text format by default agent -p "What does this codebase do?" ``` -------------------------------- ### Enable an MCP Server Source: https://cursor.com/docs/cli/mcp Add an MCP server to the local approved list, allowing it to load and be used. Replace `` with the server's identifier. ```bash agent mcp enable ``` -------------------------------- ### cursor/create_plan Source: https://cursor.com/docs/cli/acp Requests plan approval from the user. The agent blocks until the client accepts or rejects the plan. ```APIDOC ## cursor/create_plan ### Description Requests plan approval from the user. The agent blocks until the client accepts or rejects the plan. ### Method POST ### Endpoint /cursor/create_plan ### Request Body - **toolCallId** (string) - Required - Unique identifier for the tool call. - **name** (string) - Optional - The name of the plan. - **overview** (string) - Optional - A brief overview of the plan. - **plan** (string) - Required - A markdown string describing the full plan. - **todos** (Array) - Required - A list of todos with id, content, and status. - **id** (string) - Required - Unique identifier for the todo. - **content** (string) - Required - The content of the todo. - **status** ("pending" | "in_progress" | "completed" | "cancelled") - Required - The current status of the todo. - **isProject** (boolean) - Optional - Indicates if this plan is a project. - **phases** (Array) - Optional - Grouping of todos into named phases. - **name** (string) - Required - The name of the phase. - **todos** (Array) - Required - A list of todos within the phase. - **id** (string) - Required - Unique identifier for the todo. - **content** (string) - Required - The content of the todo. - **status** ("pending" | "in_progress" | "completed" | "cancelled") - Required - The current status of the todo. ### Request Example ```json { "toolCallId": "call_124", "name": "Refactor tabs layout", "overview": "Tighten layout behavior and preserve existing UX.", "plan": "1. Inspect current tab sizing logic.\n2. Update layout calculations.\n3. Verify editor behavior.", "todos": [ { "id": "todo-1", "content": "Inspect current tab sizing logic", "status": "completed" }, { "id": "todo-2", "content": "Update layout calculations", "status": "in_progress" }, { "id": "todo-3", "content": "Verify editor behavior", "status": "pending" } ], "isProject": false } ``` ### Response #### Success Response (200) - **outcome** (object) - The result of the plan approval. - **outcome**: "accepted" | "rejected" | "cancelled" - **planUri** (string) - Optional - The URI of the accepted plan, if outcome is "accepted". - **reason** (string) - Optional - The reason for rejection, if outcome is "rejected". #### Response Example ```json { "outcome": { "outcome": "accepted", "planUri": "/plans/refactor-tabs" } } ``` ``` -------------------------------- ### Configure Kitty for Option+Enter Newline Source: https://cursor.com/docs/cli/reference/terminal-setup Add this configuration to your `kitty.conf` file to map Alt+Enter to send the escape sequence for a newline, recognized by Cursor CLI. ```kitty map alt+enter send_text all \x1b\r ``` -------------------------------- ### List Tools from an MCP Server Source: https://cursor.com/docs/cli/mcp View the tools provided by a specific MCP server, including their descriptions and parameters. Replace `` with the server's identifier. ```bash agent mcp list-tools ``` -------------------------------- ### Configure Vim Mode in Settings Source: https://cursor.com/docs/cli/reference/terminal-setup Add this configuration to your `~/.cursor/cli-config.json` file to persistently enable Vim mode. ```json { "version": 1, "editor": { "vimMode": true }, "permissions": { "allow": [], "deny": [] } } ``` -------------------------------- ### Troubleshooting Login Issues Source: https://cursor.com/docs/cli/reference/authentication Commands to resolve common authentication problems. Use `agent login` to re-authenticate or set the API key if facing 'Not authenticated' errors. For browser issues, use `NO_OPEN_BROWSER=1` to manually open the login URL. ```bash # Re-authenticate via browser flow agent login # Log in and get URL without opening browser NO_OPEN_BROWSER=1 agent login ``` -------------------------------- ### API Key Authentication with Command Line Flag Source: https://cursor.com/docs/cli/reference/authentication Provide the API key directly via the --api-key flag for specific command executions. This is an alternative to using environment variables. ```bash agent --api-key your_api_key_here "implement user authentication" ``` -------------------------------- ### Neovim (avante.nvim) ACP Configuration Source: https://cursor.com/docs/cli/acp Configuration for the avante.nvim plugin to integrate with Cursor's agent via ACP. Ensure you have run `agent login` first. ```lua return { { "yetone/avante.nvim", event = "VeryLazy", version = false, build = "make", opts = { provider = "cursor", mode = "agentic", acp_providers = { cursor = { command = os.getenv("HOME") .. "/.local/bin/agent", args = { "acp" }, auth_method = "cursor_login", env = { HOME = os.getenv("HOME"), PATH = os.getenv("PATH"), }, }, }, }, dependencies = { "nvim-lua/plenary.nvim", "MunifTanjim/nui.nvim", "nvim-tree/nvim-web-devicons", { "MeanderingProgrammer/render-markdown.nvim", opts = { file_types = { "markdown", "Avante" }, }, ft = { "markdown", "Avante" }, }, }, }, } ``` -------------------------------- ### Compare Multiple Media Files with Agent CLI Source: https://cursor.com/docs/cli/headless This command allows you to provide multiple image file paths for comparison. The agent will process them based on the instructions in the prompt. ```bash # Process multiple media files agent -p "Compare these two images and identify differences: ./before.png ./after.png" ``` -------------------------------- ### List Configured MCP Servers Source: https://cursor.com/docs/cli/mcp View all configured MCP servers and their current status. This command opens an interactive menu for managing servers. ```bash agent mcp list ``` -------------------------------- ### Real-time Project Analysis and Summary Generation Source: https://cursor.com/docs/cli/headless This script streams analysis results from the agent, accumulates text output, and tracks tool usage. It's useful for monitoring long-running analysis tasks and generating summary reports. ```bash accumulated_text="" tool_count=0 start_time=$(date +%s) agent -p --force --output-format stream-json --stream-partial-output \ "Analyze this project structure and create a summary report in analysis.txt" | \ while IFS= read -r line; do type=$(echo "$line" | jq -r '.type // empty') subtype=$(echo "$line" | jq -r '.subtype // empty') case "$type" in "system") if [ "$subtype" = "init" ]; then model=$(echo "$line" | jq -r '.model // "unknown"') echo "šŸ¤– Using model: $model" fi ;; "assistant") # Only process streaming deltas (timestamp_ms present, no model_call_id). # Skip buffered flushes before tool calls and at end of turn. has_ts=$(echo "$line" | jq 'has("timestamp_ms")') has_mc=$(echo "$line" | jq 'has("model_call_id")') if [ "$has_ts" = "true" ] && [ "$has_mc" = "false" ]; then content=$(echo "$line" | jq -r '.message.content[0].text // empty') accumulated_text="$accumulated_text$content" printf "\ršŸ“ Generating: %d chars" ${#accumulated_text} fi ;; "tool_call") if [ "$subtype" = "started" ]; then tool_count=$((tool_count + 1)) # Extract tool information if echo "$line" | jq -e '.tool_call.writeToolCall' > /dev/null 2>&1; then path=$(echo "$line" | jq -r '.tool_call.writeToolCall.args.path // "unknown"') echo -e "\nšŸ”§ Tool #$tool_count: Creating $path" elif echo "$line" | jq -e '.tool_call.readToolCall' > /dev/null 2>&1; then path=$(echo "$line" | jq -r '.tool_call.readToolCall.args.path // "unknown"') echo -e "\nšŸ“– Tool #$tool_count: Reading $path" fi elif [ "$subtype" = "completed" ]; then # Extract and show tool results if echo "$line" | jq -e '.tool_call.writeToolCall.result.success' > /dev/null 2>&1; then lines=$(echo "$line" | jq -r '.tool_call.writeToolCall.result.success.linesCreated // 0') size=$(echo "$line" | jq -r '.tool_call.writeToolCall.result.success.fileSize // 0') echo " āœ… Created $lines lines ($size bytes)" elif echo "$line" | jq -e '.tool_call.readToolCall.result.success' > /dev/null 2>&1; then lines=$(echo "$line" | jq -r '.tool_call.readToolCall.result.success.totalLines // 0') echo " āœ… Read $lines lines" fi fi ;; "result") duration=$(echo "$line" | jq -r '.duration_ms // 0') end_time=$(date +%s) total_time=$((end_time - start_time)) echo -e "\n\nšŸŽÆ Completed in ${duration}ms (${total_time}s total)" echo "šŸ“Š Final stats: $tool_count tools, ${#accumulated_text} chars generated" ;; esac done ``` -------------------------------- ### Login to an MCP Server Source: https://cursor.com/docs/cli/mcp Authenticate with an MCP server configured in your `mcp.json`. The CLI handles the login flow and grants the agent immediate access. ```bash agent mcp login ``` -------------------------------- ### Troubleshoot Config Errors Source: https://cursor.com/docs/cli/reference/configuration Command to move the configuration file aside for troubleshooting. ```bash mv ~/.cursor/cli-config.json ~/.cursor/cli-config.json.bad ``` -------------------------------- ### Batch Media Processing Script Source: https://cursor.com/docs/cli/headless This script iterates through all PNG images in the 'images/' directory, sends each to the agent for description, and saves the output to a corresponding '.description.txt' file. Ensure files are accessible. ```bash # process-media.sh - Process multiple media files for image in images/*.png; do echo "Processing $image..." agent -p --output-format text \ "Describe what's in this image: $image" > "${image%.png}.description.txt" done ``` -------------------------------- ### Verify Terminal Key Detection with showkey Source: https://cursor.com/docs/cli/reference/terminal-setup Alternatively, use the `showkey` command to verify terminal key detection. This command provides more detailed information about key codes being sent. ```bash showkey ``` -------------------------------- ### Create Plan Request for Cursor Source: https://cursor.com/docs/cli/acp Use this to request plan approval from the user. The agent blocks until the client accepts or rejects the plan. ```typescript interface CursorCreatePlanRequest { toolCallId: string; name?: string; overview?: string; plan: string; todos: Array<{ id: string; content: string; status: "pending" | "in_progress" | "completed" | "cancelled"; }>; isProject?: boolean; phases?: Array<{ name: string; todos: Array<{ id: string; content: string; status: "pending" | "in_progress" | "completed" | "cancelled"; }>; }>; } ``` ```json { "toolCallId": "call_124", "name": "Refactor tabs layout", "overview": "Tighten layout behavior and preserve existing UX.", "plan": "1. Inspect current tab sizing logic.\n2. Update layout calculations.\n3. Verify editor behavior.", "todos": [ { "id": "todo-1", "content": "Inspect current tab sizing logic", "status": "completed" }, { "id": "todo-2", "content": "Update layout calculations", "status": "in_progress" }, { "id": "todo-3", "content": "Verify editor behavior", "status": "pending" } ], "isProject": false } ``` -------------------------------- ### API Key Authentication with Environment Variable Source: https://cursor.com/docs/cli/reference/authentication Set the API key using the CURSOR_API_KEY environment variable for automated or script-based authentication. This is the recommended method for CI/CD environments. ```bash export CURSOR_API_KEY=your_api_key_here agent "implement user authentication" ``` -------------------------------- ### Analyze an Image with Agent CLI Source: https://cursor.com/docs/cli/headless Use this command to send an image file to the agent for analysis. The agent can process various media types by referencing their file paths in the prompt. ```bash # Analyze an image agent -p "Analyze this image and describe what you see: ./screenshot.png" ``` -------------------------------- ### Configure Proxy Environment Variables Source: https://cursor.com/docs/cli/reference/configuration Sets environment variables for HTTP and HTTPS proxy configuration. ```bash export HTTP_PROXY=http://your-proxy:port ``` ```bash export HTTPS_PROXY=http://your-proxy:port ``` ```bash export NODE_USE_ENV_PROXY=1 ``` -------------------------------- ### Enable HTTP/1.1 for Proxy Source: https://cursor.com/docs/cli/reference/configuration Configures the CLI to use HTTP/1.1 for agent connections, useful for proxies that do not support HTTP/2. ```json { "version": 1, "editor": { "vimMode": false }, "permissions": { "allow": [], "deny": [] }, "network": { "useHttp1ForAgent": true } } ``` -------------------------------- ### Handoff Tasks to Cloud Agent Source: https://cursor.com/docs/cli/overview Use the ampersand prefix to delegate tasks to a Cloud Agent for background processing. ```bash # Send a task to Cloud Agent mid-conversation & refactor the auth module and add comprehensive tests ``` -------------------------------- ### Configure Permissions Source: https://cursor.com/docs/cli/reference/configuration Sets specific permissions for shell commands, allowing 'ls' and 'echo' while denying 'rm'. ```json { "version": 1, "editor": { "vimMode": false }, "permissions": { "allow": ["Shell(ls)", "Shell(echo)"], "deny": ["Shell(rm)"] } } ``` -------------------------------- ### Browser Authentication Commands Source: https://cursor.com/docs/cli/reference/authentication Use these commands for browser-based authentication. The login command initiates an interactive browser session. Status checks current authentication, and logout clears stored credentials. ```bash # Log in using browser flow agent login # Check authentication status agent status # Log out and clear stored authentication agent logout ``` -------------------------------- ### Check Authentication Status Source: https://cursor.com/docs/cli/reference/authentication Verify the current authentication status, account information, and endpoint configuration. ```bash agent status ``` -------------------------------- ### Execute Chained Shell Commands Source: https://cursor.com/docs/cli/shell-mode Demonstrates how to chain multiple shell commands to execute sequentially, including changing directories. This is useful for tasks requiring multiple steps within a specific directory. Commands are executed in the user's login shell with the CLI's environment. ```bash cd subdir && npm test ``` -------------------------------- ### cursor/ask_question Source: https://cursor.com/docs/cli/acp Handles blocking extension method for asking users multiple-choice questions. The agent waits for a response. ```APIDOC ## cursor/ask_question Present multiple-choice questions to the user. The agent blocks until the client responds. **Request:** ```ts interface CursorAskQuestionRequest { toolCallId: string; title?: string; questions: Array<{ id: string; prompt: string; options: Array<{ id: string; label: string }>; allowMultiple?: boolean; }>; } ``` **Response:** ```ts interface CursorAskQuestionResponse { outcome: | { outcome: "answered"; answers: Array<{ questionId: string; selectedOptionIds: string[]; }>; } | { outcome: "skipped"; reason?: string } | { outcome: "cancelled" }; } ``` **Example request:** ```json { "toolCallId": "call_123", "title": "Need input", "questions": [ { "id": "q1", "prompt": "Which mode should I use?", "options": [ { "id": "agent", "label": "Agent" }, { "id": "plan", "label": "Plan" } ], "allowMultiple": false } ] } ``` ``` -------------------------------- ### Add ~/.local/bin to PATH (Zsh) Source: https://cursor.com/docs/cli/installation Appends the Cursor CLI's binary directory to the system's PATH environment variable for Zsh users, enabling command execution from anywhere. ```zsh echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc source ~/.zshrc ``` -------------------------------- ### Modify files in scripts Source: https://cursor.com/docs/cli/headless Demonstrates using --force to apply changes automatically and batch processing files. ```bash # Enable file modifications in print mode agent -p --force "Refactor this code to use modern ES6+ syntax" # Without --force, changes are only proposed, not applied agent -p "Add JSDoc comments to this file" # Won't modify files # Batch processing with actual file changes find src/ -name "*.js" | while read file; do agent -p --force "Add comprehensive JSDoc comments to $file" done ``` -------------------------------- ### Configure Permissions for Cursor CLI Source: https://cursor.com/docs/cli/github-actions Defines granular permissions for the agent, specifying allowed and denied operations for file access and shell commands. Use this to enforce restrictions at the CLI level. ```json { "permissions": { "allow": [ "Read(**/*.md)", "Write(docs/**/*)", "Shell(grep)", "Shell(find)" ], "deny": ["Shell(git)", "Shell(gh)", "Write(.env*)", "Write(package.json)"] } } ``` -------------------------------- ### Configure tmux for Color Detection Source: https://cursor.com/docs/cli/reference/terminal-setup For tmux users, these settings in `.tmux.conf` help ensure correct color scheme reporting and pass-through for Cursor CLI. ```tmux set -g default-terminal "tmux-256color" set -ag terminal-overrides ",xterm-256color:RGB" ``` -------------------------------- ### Manage Conversation Sessions Source: https://cursor.com/docs/cli/overview Commands to list, resume, or continue previous AI agent conversations. ```bash # Open previous chats and resume one agent ls # Resume latest conversation agent resume # Continue the previous session agent --continue # Resume specific conversation agent --resume="chat-id-here" ``` -------------------------------- ### ACP Sessions, Modes, and Permissions Source: https://cursor.com/docs/cli/acp Details on managing ACP sessions, supported modes, and handling permission requests. ```APIDOC ## Sessions, modes, and permissions ### Sessions - Create a session with `session/new` - Resume an existing conversation with `session/load` ### Modes ACP sessions support the same core modes as CLI: - `agent` (full tool access) - `plan` (planning, read-only behavior) - `ask` (Q&A/read-only behavior) ### Permissions When tools need approval, Cursor sends `session/request_permission`. Clients should return one of: - `allow-once` - `allow-always` - `reject-once` If your client does not answer permission requests, tool execution can block. ``` -------------------------------- ### Configure Alacritty for Option+Enter Newline Source: https://cursor.com/docs/cli/reference/terminal-setup Add this configuration to your `alacritty.toml` file to map Option+Enter to send the escape sequence for a newline, recognized by Cursor CLI. ```toml [keyboard] bindings = [ { key = "Return", mods = "Alt", chars = "\u001b\r" } ] ``` -------------------------------- ### Add ~/.local/bin to PATH (Bash) Source: https://cursor.com/docs/cli/installation Appends the Cursor CLI's binary directory to the system's PATH environment variable for Bash users, enabling command execution from anywhere. ```bash echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc source ~/.bashrc ``` -------------------------------- ### MCP Tool Permissions Source: https://cursor.com/docs/cli/reference/permissions Specify which MCP tools can be run by the agent. Use server and tool names, with wildcards for broader access. ```plaintext Mcp(datadog:*) ``` ```plaintext Mcp(*:search) ``` ```plaintext Mcp(*:*) ``` -------------------------------- ### Force Light Terminal Theme Source: https://cursor.com/docs/cli/reference/terminal-setup Use this environment variable to force the Cursor CLI to use a light theme, overriding automatic detection. Add it to your shell profile for persistence. ```bash # Force light theme export COLORFGBG="0;15" ``` -------------------------------- ### Image Analysis Script using Agent CLI Source: https://cursor.com/docs/cli/headless This bash script automates image analysis by passing an image path to the agent CLI and capturing the JSON output. It then extracts the analysis result using jq. ```bash # analyze-image.sh - Analyze images using the headless CLI IMAGE_PATH="./screenshots/ui-mockup.png" agent -p --output-format json \ "Analyze this image and provide a detailed description: $IMAGE_PATH" | \ jq -r '.result' ``` -------------------------------- ### Minimal Node.js ACP Client Source: https://cursor.com/docs/cli/acp This Node.js script demonstrates the basic control flow for a custom ACP client, including sending requests and handling responses. ```javascript import { spawn } from "node:child_process"; import readline from "node:readline"; const agent = spawn("agent", ["acp"], { stdio: ["pipe", "pipe", "inherit"] }); let nextId = 1; const pending = new Map(); function send(method, params) { const id = nextId++; agent.stdin.write(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n"); return new Promise((resolve, reject) => pending.set(id, { resolve, reject })); } function respond(id, result) { agent.stdin.write(JSON.stringify({ jsonrpc: "2.0", id, result }) + "\n"); } const rl = readline.createInterface({ input: agent.stdout }); rl.on("line", line => { const msg = JSON.parse(line); if (msg.id && (msg.result || msg.error)) { const waiter = pending.get(msg.id); if (!waiter) return; pending.delete(msg.id); msg.error ? waiter.reject(msg.error) : waiter.resolve(msg.result); return; } if (msg.method === "session/update") { const update = msg.params?.update; if (update?.sessionUpdate === "agent_message_chunk" && update.content?.text) { process.stdout.write(update.content.text); } return; } if (msg.method === "session/request_permission") { respond(msg.id, { outcome: { outcome: "selected", optionId: "allow-once" } }); } }); const init = async () => { await send("initialize", { protocolVersion: 1, clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false }, clientInfo: { name: "acp-minimal-client", version: "0.1.0" } }); await send("authenticate", { methodId: "cursor_login" }); const { sessionId } = await send("session/new", { cwd: process.cwd(), mcpServers: [] }); const result = await send("session/prompt", { sessionId, prompt: [{ type: "text", text: "Say hello in one sentence." }] }); console.log(`\n\n[stopReason=${result.stopReason}]`); }; init().finally(() => { agent.stdin.end(); agent.kill(); }); ``` -------------------------------- ### File Write Permissions Source: https://cursor.com/docs/cli/reference/permissions Define write access to files and directories with glob patterns. Supports print mode for controlled writes and can deny sensitive files. ```plaintext Write(src/**) ``` ```plaintext Write(package.json) ``` ```plaintext Write(**/*.key) ``` ```plaintext Write(**/.env*) ```