### Install Cursor CLI on Windows (Native) Source: https://cursor.com/docs/cli/installation Install the Cursor CLI on native Windows environments using PowerShell. This command downloads and executes the installer. ```powershell irm 'https://cursor.com/install?win32=true' | iex ``` -------------------------------- ### Install Cursor CLI Source: https://cursor.com/docs/cli/overview Install the Cursor CLI on macOS, Linux, WSL, or Windows using the provided commands. ```bash curl https://cursor.com/install -fsS | bash ``` ```powershell irm 'https://cursor.com/install?win32=true' | iex ``` -------------------------------- ### Install and Run Cursor CLI in GitHub Actions Source: https://cursor.com/docs/cli/github-actions Installs the Cursor CLI and then runs an agent with a specified prompt and model. For Windows runners, use PowerShell. ```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.2 ``` -------------------------------- ### Verify Cursor CLI Installation Source: https://cursor.com/docs/cli/installation After installation, run this command to confirm that the Cursor CLI is installed and accessible in your PATH. ```bash agent --version ``` -------------------------------- ### Write File Tool Call Started Source: https://cursor.com/docs/cli/reference/output-format Arguments for starting a write file tool call, including the file path, content to write, and a tool call ID. ```json { "path": "file.txt", "fileText": "content...", "toolCallId": "id" } ``` -------------------------------- ### Start Cursor Agent Source: https://cursor.com/docs/cli/installation Once the PATH is configured, you can start the Cursor Agent by running this command in your terminal. ```bash agent ``` -------------------------------- ### Install Cursor CLI on macOS, Linux, and Windows (WSL) Source: https://cursor.com/docs/cli/installation Use this command to install the Cursor CLI on macOS, Linux, and Windows Subsystem for Linux. Ensure curl is installed. ```bash curl https://cursor.com/install -fsS | bash ``` -------------------------------- ### Cursor/Ask Question Request Example Source: https://cursor.com/docs/cli/acp Example JSON-RPC request for the `cursor/ask_question` 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 } ] } ``` -------------------------------- ### Using MCP Tools with Agent Source: https://cursor.com/docs/cli/mcp Examples demonstrating how to check MCP server availability, list tools, and use the agent with MCP tools for tasks like web navigation and screenshots. Auto-approving MCPs is also shown. ```bash # Check what MCP servers are available agent mcp list # See what tools a specific server provides agent mcp list-tools playwright # Use agent - it automatically uses MCP tools when helpful agent -p "Navigate to google.com and take a screenshot of the search page" # 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 An example of the 'text' output format, which provides only the final assistant message without intermediate progress updates or tool call summaries. This format is ideal for scripts needing only the agent's final response. ```text The command to move this branch onto main is `git rebase --onto main HEAD~3`. ``` -------------------------------- ### Start ACP Server Source: https://cursor.com/docs/cli/acp Run the Cursor CLI in ACP mode to start the Agent Client Protocol server. ```bash agent acp ``` -------------------------------- ### Run Terminal Setup Script Source: https://cursor.com/docs/cli/reference/terminal-setup Execute this command if Shift+Enter does not create newlines in your terminal. It guides you through configuring alternatives like Option+Enter. ```bash /setup-terminal ``` -------------------------------- ### Install Cursor CLI Source: https://cursor.com/docs/cli/headless Install the Cursor CLI using curl for macOS, Linux, and WSL, or using Invoke-WebRequest for Windows PowerShell. Ensure you have set your API key using `export CURSOR_API_KEY=your_api_key_here` before running commands. ```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" ``` -------------------------------- ### Start Interactive Session with Cursor CLI Source: https://cursor.com/docs/cli/overview Begin an interactive conversation with the AI agent to describe coding goals or provide an initial prompt. ```bash agent ``` ```bash agent "refactor the auth module to use JWT tokens" ``` -------------------------------- ### Tool Call Started JSON Source: https://cursor.com/docs/cli/reference/output-format Indicates the start of a tool call, including a unique call ID, the tool being invoked, and its arguments. Used for tracking tool execution. ```json { "type": "tool_call", "subtype": "started", "call_id": "", "tool_call": { "readToolCall": { "args": { "path": "file.txt" } } }, "session_id": "" } ``` -------------------------------- ### Example NDJSON Sequence Source: https://cursor.com/docs/cli/reference/output-format A representative NDJSON sequence showing the typical flow of events during an agent interaction, including system initialization, user messages, tool calls (started and completed), and final results. ```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"} ``` -------------------------------- ### Add ~/.local/bin to PATH for Bash Source: https://cursor.com/docs/cli/installation Configure your bash shell to include the ~/.local/bin directory in your PATH environment variable. This is necessary for the agent command to work after installation. ```bash echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc source ~/.bashrc ``` -------------------------------- ### Neovim ACP Provider Configuration Source: https://cursor.com/docs/cli/acp This Lua configuration snippet sets up the avante.nvim plugin to use Cursor's agent via ACP. Ensure you have run `agent login` and adjust the `command` path if your agent binary is installed elsewhere. ```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" }, }, }, }, } ``` -------------------------------- ### Add ~/.local/bin to PATH for Zsh Source: https://cursor.com/docs/cli/installation Configure your zsh shell to include the ~/.local/bin directory in your PATH environment variable. This is necessary for the agent command to work after installation. ```bash echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc source ~/.zshrc ``` -------------------------------- ### Combine File Paths with Text Instructions Source: https://cursor.com/docs/cli/headless This command demonstrates combining file path references with textual instructions for the agent. The agent will use tool calling to read the specified files. ```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." ``` -------------------------------- ### List Tools from an MCP Server Source: https://cursor.com/docs/cli/mcp View the tools provided by a specific MCP server, including their parameters and constraints. ```bash agent mcp list-tools ``` -------------------------------- ### Log in using Browser Flow Source: https://cursor.com/docs/cli/reference/authentication Initiates the browser-based authentication flow. This is the recommended method for interactive use. ```bash agent login ``` -------------------------------- ### Check Authentication Status Source: https://cursor.com/docs/cli/reference/authentication Displays the current authentication status, including account information and endpoint configuration. Useful for verifying login or API key setup. ```bash agent status ``` -------------------------------- ### Configure Option+Enter in Kitty Source: https://cursor.com/docs/cli/reference/terminal-setup Add this mapping to your kitty.conf to enable the Option+Enter newline shortcut. ```text map alt+enter send_text all \x1b\r ``` -------------------------------- ### Minimal CLI Configuration Source: https://cursor.com/docs/cli/reference/configuration A basic configuration file for the Cursor CLI. Ensure 'version' is set to 1 and 'permissions.allow' includes necessary operations. ```json { "version": 1, "editor": { "vimMode": false }, "permissions": { "allow": ["Shell(ls)"], "deny": [] } } ``` -------------------------------- ### 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 Request plan approval from the user. The agent blocks until the client accepts or rejects the plan. ### Request Body - `toolCallId` (string) - Required - Identifier for the tool call. - `name` (string) - Optional - Name of the plan. - `overview` (string) - Optional - Overview of the plan. - `plan` (string) - Required - A markdown string describing the full plan. - `todos` (Array) - Required - List of todos with id, content, and status. - `id` (string) - Required - Unique identifier for the todo. - `content` (string) - Required - Content of the todo. - `status` ("pending" | "in_progress" | "completed" | "cancelled") - Required - Current status of the todo. - `isProject` (boolean) - Optional - Indicates if this is a project. - `phases` (Array) - Optional - Grouping of todos into named phases. - `name` (string) - Required - Name of the phase. - `todos` (Array) - Required - List of todos within the phase. - `id` (string) - Required - Unique identifier for the todo. - `content` (string) - Required - Content of the todo. - `status` ("pending" | "in_progress" | "completed" | "cancelled") - Required - Current status of the todo. ### Response #### Success Response - `outcome` (object) - The outcome of the plan approval. - `outcome` ("accepted" | "rejected" | "cancelled") - Required - The result of the approval. - `planUri` (string) - Optional - URI of the plan if accepted. - `reason` (string) - Optional - Reason for rejection if rejected. ### 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 } ``` ``` -------------------------------- ### Create Cursor Plan Request 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. The `plan` field is a markdown string describing the full plan, and `phases` can be used for optional grouping of todos. ```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 } ``` -------------------------------- ### List Configured MCP Servers Source: https://cursor.com/docs/cli/mcp View all configured MCP servers and their status. This command opens an interactive menu for management. ```bash agent mcp list ``` -------------------------------- ### Enable an MCP Server Source: https://cursor.com/docs/cli/mcp Enable a specific MCP server for use. This can also be done via the `/mcp enable ` slash command in interactive mode. ```bash agent mcp enable ``` -------------------------------- ### Real-time Progress Tracking with Streaming JSON Source: https://cursor.com/docs/cli/headless This script demonstrates real-time progress tracking during stream processing. It uses `--output-format stream-json` for message-level progress or `--stream-partial-output` for incremental streaming of deltas. ```bash #!/bin/bash # stream-progress.sh - Track progress in real-time echo "šŸš€ Starting stream processing..." ``` -------------------------------- ### Stream JSON Format: System Initialization Event Source: https://cursor.com/docs/cli/reference/output-format This event is emitted once at the beginning of each session when using the `stream-json` output format. It provides initialization details such as the API key source, current working directory, session ID, and model information. Future fields may be added to this event. ```json { "type": "system", "subtype": "init", "apiKeySource": "env|flag|login", "cwd": "/absolute/path", "session_id": "", "model": "", "permissionMode": "default" } ``` -------------------------------- ### Configure Vim Mode in Settings Source: https://cursor.com/docs/cli/reference/terminal-setup Add this JSON configuration to your `~/.cursor/cli-config.json` file to enable Vim mode persistently. Ensure the file structure is correct. ```json { "version": 1, "editor": { "vimMode": true }, "permissions": { "allow": [], "deny": [] } } ``` -------------------------------- ### Configure CLI Permissions Source: https://cursor.com/docs/cli/reference/permissions Define allowed and denied actions within the permissions object 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)" ] } } ``` -------------------------------- ### Configure tmux for color support Source: https://cursor.com/docs/cli/reference/terminal-setup Add these settings to your .tmux.conf to ensure proper color detection and true color support. ```text set -g default-terminal "tmux-256color" set -ag terminal-overrides ",xterm-256color:RGB" ``` -------------------------------- ### Configure CLI Permissions Source: https://cursor.com/docs/cli/reference/configuration Set specific permissions for the Cursor CLI, defining allowed and denied operations. Use exact strings for permission types as listed in the documentation. ```json { "version": 1, "editor": { "vimMode": false }, "permissions": { "allow": ["Shell(ls)", "Shell(echo)"], "deny": ["Shell(rm)"] } } ``` -------------------------------- ### Automated Code Review with JSON Output Source: https://cursor.com/docs/cli/headless This script performs a basic code review using the agent. It utilizes `--output-format text` for feedback and writes the results to `review.txt`. Error handling is included to check the exit status of the agent command. ```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 ``` -------------------------------- ### Enable HTTP/1.1 for Agent Connections Source: https://cursor.com/docs/cli/reference/configuration Configure the Cursor CLI to use HTTP/1.1 instead of HTTP/2 for agent connections. This is useful for enterprise proxies that do not support HTTP/2 bidirectional streaming. ```json { "version": 1, "editor": { "vimMode": false }, "permissions": { "allow": [], "deny": [] }, "network": { "useHttp1ForAgent": true } } ``` -------------------------------- ### Stream Project Analysis with Real-time Progress Source: https://cursor.com/docs/cli/headless This script streams JSON output from the agent, processes different message types (system, assistant, tool_call, result), and accumulates text content. It provides real-time feedback on generation progress and final statistics. ```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 ``` -------------------------------- ### Select CLI Model Source: https://cursor.com/docs/cli/reference/configuration Use slash commands to select a model for the Cursor CLI. 'auto' selects the default, while specific model names can be provided. ```bash /model auto ``` ```bash /model gpt-5.2 ``` ```bash /model sonnet-4.5-thinking ``` -------------------------------- ### Set API Key via Command Line Flag Source: https://cursor.com/docs/cli/reference/authentication Provides an API key for authentication directly via the --api-key command line flag. Useful for one-off commands or when environment variables are not feasible. ```bash agent --api-key your_api_key_here "implement user authentication" ``` -------------------------------- ### cursor/ask_question Source: https://cursor.com/docs/cli/acp This method is used to present multiple-choice questions to the user. The agent blocks until the client responds with the user's selection. ```APIDOC ## cursor/ask_question ### Description 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" }; } ``` ### Request Example ```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 } ] } ``` ``` -------------------------------- ### Set API Key via Environment Variable Source: https://cursor.com/docs/cli/reference/authentication Provides an API key for authentication using the CURSOR_API_KEY environment variable. Recommended for automation and CI/CD. ```bash export CURSOR_API_KEY=your_api_key_here agent "implement user authentication" ``` -------------------------------- ### Process Multiple Media Files with Headless CLI Source: https://cursor.com/docs/cli/headless This command processes multiple media files by referencing their paths in the prompt. The agent can handle various file types. ```bash # Process multiple media files agent -p "Compare these two images and identify differences: ./before.png ./after.png" ``` -------------------------------- ### Search Codebase with Default Text Format Source: https://cursor.com/docs/cli/headless A simple script to ask a question about the codebase. By default, `--print` mode uses the `text` output format for clean, final-answer-only responses. ```bash #!/bin/bash # Simple codebase question - uses text format by default agent -p "What does this codebase do?" ``` -------------------------------- ### Login to an MCP Server Source: https://cursor.com/docs/cli/mcp Authenticate with an MCP server configured in `mcp.json`. The CLI handles the login flow and callback automatically. ```bash agent mcp login ``` -------------------------------- ### Analyze an Image with Headless CLI Source: https://cursor.com/docs/cli/headless This command analyzes a single image file. Ensure the image path is correct and accessible. ```bash # Analyze an image agent -p "Analyze this image and describe what you see: ./screenshot.png" ``` -------------------------------- ### Manage Cursor CLI Sessions Source: https://cursor.com/docs/cli/overview List previous chats, resume the latest conversation, continue the previous session, or resume a specific conversation using its chat ID. ```bash agent ls ``` ```bash agent resume ``` ```bash agent --continue ``` ```bash agent --resume="chat-id-here" ``` -------------------------------- ### Enable Vim Mode in CLI Source: https://cursor.com/docs/cli/reference/configuration Configure the Cursor CLI to use Vim keybindings by setting 'editor.vimMode' to true. Requires a valid JSON configuration. ```json { "version": 1, "editor": { "vimMode": true }, "permissions": { "allow": ["Shell(ls)"], "deny": [] } } ``` -------------------------------- ### Force Light Theme Source: https://cursor.com/docs/cli/reference/terminal-setup Set 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 export COLORFGBG="0;15" ``` -------------------------------- ### Cursor Create Plan Response Source: https://cursor.com/docs/cli/acp Response indicating whether the user accepted or rejected the plan, or if it was cancelled. ```typescript interface CursorCreatePlanResponse { outcome: | { outcome: "accepted"; planUri?: string } | { outcome: "rejected"; reason?: string } | { outcome: "cancelled" }; } ``` -------------------------------- ### Analyze Image using Headless CLI Script Source: https://cursor.com/docs/cli/headless This bash script uses the headless CLI to analyze an image file and outputs the result using `jq`. Ensure the `IMAGE_PATH` variable points to a valid image. ```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' ``` -------------------------------- ### Run Cursor CLI in Non-Interactive Mode Source: https://cursor.com/docs/cli/overview Execute the agent with a specific prompt and model, or include git changes for review. Use --output-format text for script-friendly output. ```bash agent -p "find and fix performance issues" --model "gpt-5.2" ``` ```bash agent -p "review these changes for security issues" --output-format text ``` -------------------------------- ### Troubleshoot Config Errors Source: https://cursor.com/docs/cli/reference/configuration If the CLI encounters configuration errors, move the current config file aside and restart. This helps in diagnosing issues with the JSON format or file permissions. ```bash mv ~/.cursor/cli-config.json ~/.cursor/cli-config.json.bad ``` -------------------------------- ### Send Task to Cloud Agent Source: https://cursor.com/docs/cli/overview Prepend '&' to a message to send a task to a Cloud Agent for continued processing. ```bash & refactor the auth module and add comprehensive tests ``` -------------------------------- ### Resume Previous Conversation Source: https://cursor.com/docs/cli/using Use `--resume [thread id]` to load prior context and continue an existing conversation thread. For the most recent conversation, use `agent resume`, `--continue`, or `/resume`. ```bash agent ls ``` -------------------------------- ### Configure Proxy Environment Variables Source: https://cursor.com/docs/cli/reference/configuration Set environment variables for HTTP and HTTPS proxies before running the CLI. Ensure NODE_USE_ENV_PROXY is set to 1 for Node.js compatibility. ```bash export HTTP_PROXY=http://your-proxy:port ``` ```bash export HTTPS_PROXY=http://your-proxy:port ``` ```bash export NODE_USE_ENV_PROXY=1 ``` -------------------------------- ### Target Repository and Use Worktree Source: https://cursor.com/docs/cli/using Combine `--workspace` to specify a repository root and `--worktree` to isolate edits within that project. This is useful for targeting specific projects from any location. ```bash # Target a repository from anywhere, but keep the changes isolated agent --workspace ~/src/my-app --worktree "fix the flaky auth test and open a PR" ``` -------------------------------- ### Send Task to Cloud Agent Source: https://cursor.com/docs/cli/using Prepend '&' to any message to send the task to a Cloud Agent for background processing. This allows you to continue your work while the agent handles the task. ```bash # Send a task to Cloud Agent mid-conversation & refactor the auth module and add comprehensive tests ``` -------------------------------- ### Force Dark Theme Source: https://cursor.com/docs/cli/reference/terminal-setup Set this environment variable to force the Cursor CLI to use a dark theme, overriding automatic detection. Add it to your shell profile for persistence. ```bash export COLORFGBG="15;0" ``` -------------------------------- ### Batch Media Processing Script Source: https://cursor.com/docs/cli/headless This bash script iterates through image files in a directory, processes each one using the headless CLI to generate a description, and saves the output to a text file. The output file is named based on the original image file. ```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 ``` -------------------------------- ### Toggle Vim Mode Source: https://cursor.com/docs/cli/reference/terminal-setup Use this slash command to toggle Vim mode on or off for the current session. The preference is saved automatically. ```bash /vim ``` -------------------------------- ### Run Agent in a New Worktree Source: https://cursor.com/docs/cli/using Use the `--worktree` flag to run the agent in a temporary Git worktree, isolating edits from your current checkout. Cursor manages these worktrees under `~/.cursor/worktrees`. ```bash # Create a temporary worktree from the current repository agent --worktree "upgrade the test runner and fix any broken snapshots" ``` -------------------------------- ### Enable File Modifications in Print Mode Source: https://cursor.com/docs/cli/headless Use `--print` with `--force` (or `--yolo`) to allow the agent to modify files directly in scripts. Without `--force`, changes are only proposed. ```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 Shift+Enter in VS Code Source: https://cursor.com/docs/cli/reference/terminal-setup Add this entry to your keybindings.json to ensure the terminal correctly sends the Shift+Enter sequence. ```json { "key": "shift+enter", "command": "workbench.action.terminal.sendSequence", "args": { "text": "\u001b[13;2u" }, "when": "terminalFocus" } ``` -------------------------------- ### 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 messages, handling responses, and processing session updates. ```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(); }); ``` -------------------------------- ### Configure Permissions for Cursor CLI Source: https://cursor.com/docs/cli/github-actions Enforces restrictions on agent operations at the CLI level, specifying allowed and denied actions for file access and shell commands. ```json { "permissions": { "allow": [ "Read(**/*.md)", "Write(docs/**/*)", "Shell(grep)", "Shell(find)" ], "deny": ["Shell(git)", "Shell(gh)", "Write(.env*)", "Write(package.json)"] } } ``` -------------------------------- ### Write File Tool Call Completed Source: https://cursor.com/docs/cli/reference/output-format Result of a completed write file tool call, indicating the absolute path of the created file, lines created, and file size. ```json { "path": "/absolute/path", "linesCreated": 19, "fileSize": 942 } ```