12 Prompts for Cursor: AI-Assisted Development in Your IDE

12 Prompts for Cursor: AI-Assisted Development in Your IDE

Cursor is redefining how developers write code by embedding AI directly into the IDE. Unlike generic chatbots, Cursor understands your entire codebase, file structure, and project context. This guide presents 12 ready-to-use prompts across three core modes: autocomplete, chat, and command (Ctrl+K). Each prompt is battle-tested, with real examples and output.

Why These Prompts Matter

Cursor’s AI (powered by models like Claude 3.5 Sonnet and GPT‑4o) excels when given precise context. Vague prompts yield generic code; structured prompts deliver production-ready logic. According to Cursor’s official docs (cursor.com/docs), the key is to include file references, language, and constraints. These 12 prompts follow that principle.

1. Autocomplete: Generate a Function from a Comment

Task: Write a complete function based on a descriptive comment.
Prompt example in code:

# function to parse a CSV file, skip header, return list of dicts with column names as keys
def parse_csv(filepath: str) -> list[dict]:

Result: Cursor suggests the entire function body with error handling and type hints.
Why it works: The comment specifies input type, output format, and edge case (skip header).

2. Autocomplete: Refactor Inline Code into a Helper

Task: Extract repeated logic into a reusable function.
Prompt in code:

// Extract the discount calculation into a helper function
const total = items.reduce((sum, item) => {
  let discount = 0;
  if (item.price > 100) discount = 0.1 * item.price;
  return sum + item.price - discount;
}, 0);

Result: Cursor suggests a calcDiscount(price) function and refactors the reduce.
Why it works: The comment explicitly asks for extraction, guiding the AI to modularize.

3. Chat: Explain a Complex Code Block

Task: Understand a piece of legacy code.
Prompt:

Explain this function line by line. Assume I know Python but not async/await deeply.

async def fetch_data(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as resp:
            return await resp.json()

Result: Cursor explains async with context managers, session lifecycle, and JSON parsing.
Why it works: You specify knowledge level and ask for line-by-line breakdown.

4. Chat: Debug a Failing Test

Task: Get a fix suggestion for a test error.
Prompt:

My test for the checkout method fails with "TypeError: 'NoneType' object is not subscriptable". Here’s the test and the method:

def test_checkout():
    cart = Cart()
    cart.add_item({"price": 10})
    assert cart.checkout()["total"] == 10

def checkout(self):
    # ... logic
    return None

Result: Cursor points out that checkout() returns None instead of a dict, and suggests returning {"total": total}.
Why it works: You provide full context: error, test, and method body.

5. Command (Ctrl+K): Generate a Unit Test

Task: Create a test for an existing function.
Prompt in command bar:

Generate a pytest unit test for the function below. Cover normal case, empty list, and invalid input.

def average(numbers: list[float]) -> float:
    if not numbers:
        raise ValueError("empty list")
    return sum(numbers) / len(numbers)

Result: Cursor inserts a test file with three test functions including with pytest.raises(ValueError).
Why it works: The command specifies framework (pytest), coverage cases, and function signature.

6. Command (Ctrl+K): Optimize a Slow Loop

Task: Improve performance of a nested loop.
Prompt:

Optimize this code for speed. Use list comprehension or numpy if appropriate.

def find_duplicates(items):
    dups = []
    for i in range(len(items)):
        for j in range(i+1, len(items)):
            if items[i] == items[j]:
                dups.append(items[i])
    return dups

Result: Cursor suggests from collections import Counter; [item for item, count in Counter(items).items() if count > 1].
Why it works: The prompt includes the goal (speed) and allowed methods.

7. Chat: Design a Database Schema

Task: Model a new feature.
Prompt:

I need a PostgreSQL schema for a blog with users, posts, and comments. Users can have many posts, posts can have many comments. Include timestamps and foreign keys. Show me the CREATE TABLE statements.

Result: Cursor outputs three tables with SERIAL PRIMARY KEY, FOREIGN KEY, NOT NULL, and DEFAULT CURRENT_TIMESTAMP.
Why it works: You specify relationships, constraints, and database type.

8. Command (Ctrl+K): Add Error Handling

Task: Wrap risky code with try/except.
Prompt:

Add try/except blocks to handle FileNotFoundError and PermissionError. Log errors using the logging module.

def read_config(path):
    with open(path) as f:
        return f.read()

Result: Cursor inserts try: ... except FileNotFoundError as e: logging.error(...) and re-raises or returns default.
Why it works: The prompt lists specific exceptions and logging method.

9. Autocomplete: Generate Documentation Strings

Task: Add Google-style docstrings.
Prompt in code:

# Add Google-style docstring
def calculate_shipping(weight: float, distance: int) -> float:
    rate = 0.5 if weight < 5 else 0.75
    return rate * distance

Result: Cursor inserts a docstring with Args, Returns, and Raises sections.
Why it works: The comment specifies the docstring style.

10. Chat: Plan a Refactoring Strategy

Task: Get a step-by-step plan for improving code structure.
Prompt:

I have a 500-line function `process_order` that handles validation, payment, and email. Suggest how to split it into smaller functions. Show me the new function signatures.

Result: Cursor proposes validate_order(order), process_payment(order), send_confirmation(email) with clear inputs/outputs.
Why it works: You describe the problem (long function) and ask for concrete signatures.

11. Command (Ctrl+K): Convert Code Between Languages

Task: Translate a Python function to JavaScript.
Prompt:

Convert this Python function to modern JavaScript (ES6+). Use arrow functions and const.

def greet(name):
    return f"Hello, {name}!"

Result: Cursor outputs const greet = (name) => \Hello, ${name}!`;`
Why it works: The prompt specifies target language and style.

12. Chat: Review Code for Security Issues

Task: Find vulnerabilities in a snippet.
Prompt:

Review this Flask route for security issues. Look for SQL injection, XSS, and CSRF.

@app.route('/search')
def search():
    query = request.args.get('q')
    result = db.execute(f"SELECT * FROM items WHERE name = '{query}'")
    return render_template('results.html', items=result)

Result: Cursor flags SQL injection (f-string), suggests parameterized queries, and mentions missing CSRF token.
Why it works: The prompt lists specific vulnerabilities to check.

Conclusion

These 12 prompts cover the three primary modes of Cursor: autocomplete for quick generation, chat for deep understanding and planning, and command for targeted edits. By being specific about context, constraints, and expected output, you’ll get code that is not just syntactically correct but architecturally sound. Start with one prompt today, adapt it to your project, and you’ll see a measurable boost in your development speed.

Sources: Cursor official documentation (cursor.com/docs), Cursor changelog (cursor.com/changelog), and practical usage by the developer community.

← All posts

Comments