agentleFS
extractumioextractumio/extractum-skills/.cursor/rules/60-async-patterns.mdc

extractum-skills / rules

Cursor rule44 starsChanged 10 months agoMITView on GitHub

Async/await patterns for Claude Agent SDK

The file

We split this 60-async-patterns.mdc into the rules it gives an agent

2 rules. About 0 are common, 1 is distinctive, and 1 is very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈1

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 1

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Use asyncio.run() for the main entry point:

    line 13
  2. Distinctive:

    Always include proper return type hints for async functions:

    line 60

≈ “Common” is an estimate: at least 1 in 5 of the 3,030 Cursor rule files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
60-async-patterns.mdc
---
description: "Async/await patterns for Claude Agent SDK"
globs:
  - "**/*.py"
alwaysApply: false
priority: 5
---

# Async/Await Patterns

## Main Entry Point

Use `asyncio.run()` for the main entry point:

```python
async def main() -> None:
    """Main entry point for the agent script."""
    logger: logging.Logger = setup_logging()

    try:
        result: AgentResultSummary = await run_agent(DEFAULT_PROMPT, logger)
        log_execution_summary(result, logger)

    except Exception as e:
        logger.error(f"Failed to run agent: {e}")
        sys.exit(1)


if __name__ == "__main__":
    asyncio.run(main())
```

---

## Async Generator Processing

Process async generators with `async for`:

```python
async def run_agent(prompt: str, logger: logging.Logger) -> AgentResultSummary:
    """Run the Claude agent with the given prompt."""
    options: ClaudeAgentOptions = _create_agent_options()
    result_summary: AgentResultSummary = _create_empty_result(prompt)

    async for message in query(prompt=prompt, options=options):
        text_content: str = extract_text_from_message(message)
        
        if isinstance(message, AssistantMessage):
            _process_assistant_message(message, text_content, result_summary, logger)
        elif isinstance(message, ResultMessage):
            _process_result_message(message, text_content, result_summary, logger)

    return result_summary
```

---

## Type Hints for Async

Always include proper return type hints for async functions:

```python
# ✅ Good - Explicit async return type
async def run_agent(prompt: str, logger: logging.Logger) -> AgentResultSummary:
    ...

async def main() -> None:
    ...

# The return type is the actual value, not a coroutine
# Python handles the coroutine wrapping automatically
```

---

## Claude Agent SDK Query Pattern

The `query()` function is an async generator that yields messages:

```python
from claude_agent_sdk import (
    ClaudeAgentOptions,
    Message,
    AssistantMessage,
    ResultMessage,
    SystemMessage,
    query,
)

async for message in query(prompt=prompt, options=options):
    if isinstance(message, AssistantMessage):
        # Handle assistant response
        pass
    elif isinstance(message, ResultMessage):
        # Handle final result with cost/usage info
        pass
    elif isinstance(message, SystemMessage):
        # Handle system messages
        pass
```

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.