Skip to content
Skills Library
Programming · Building & coding

add-command

/add-command

Add a complete command flow to an existing aggregate. It creates a command class, a FastAPI API endpoint, and a command handler with repository logic. This is the primary workflow for adding write operations to a Protean domain. Use when the user wants to "add a command", "add an action", "add an operation", "expose a write endpoint", "create a command flow", "wire up a POST endpoint", "add a new operation to an aggregate", or describes an action like "I want users to be able to [verb] a [thing]" (e.g., "place an order", "register a user", "cancel a reservation"). This workflow composes the co

Repository
protean ↗
Licence
Apache-2.0
Last repository change
27.10.2026

Assessment and security

100/ 100Class: good
Format25 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content35 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene15 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
7
Scripts
3
HTML comments
0
URLs in SKILL.md
0
Deprecation

No signals detected. Repository changed on 27.10.2026, without references to retired models or APIs.

Licence

Apache-2.0, otwarta: można używać i zmieniać, z zachowaniem licencji i informacji o zmianach.

What to check before installing
  • 3 scripts in this package. Review them before installing, as Claude may execute them.

Scripts: assets/add_command_create_flow.py, assets/add_command_multiple_commands.py, assets/add_command_update_flow.py

What it does and when to use it

Add a complete command flow to an existing aggregate. It creates a command class, a FastAPI API endpoint, and a command handler with repository logic. This is the primary workflow for adding write operations to a Protean domain. Use when the user wants to "add a command", "add an action", "add an operation", "expose a write endpoint", "create a command flow", "wire up a POST endpoint", "add a new operation to an aggregate", or describes an action like "I want users to be able to [verb] a [thing]" (e.g., "place an order", "register a user", "cancel a reservation"). This workflow composes the co

Triggers from the description

add a commandadd an actionadd an operationexpose a write endpointcreate a command flowwire up a POST endpointadd a new operation to an aggregateI want users to be able to [verb] a [thing]
Original author description

Add a complete command flow to an existing aggregate. It creates a command class, a FastAPI API endpoint, and a command handler with repository logic. This is the primary workflow for adding write operations to a Protean domain. Use when the user wants to "add a command", "add an action", "add an operation", "expose a write endpoint", "create a command flow", "wire up a POST endpoint", "add a new operation to an aggregate", or describes an action like "I want users to be able to [verb] a [thing]" (e.g., "place an order", "register a user", "cancel a reservation"). This workflow composes the co

How it works

  1. What this creates
  2. Information to gather
  3. Process
  4. File organization (Screaming Architecture)
  5. Adding to an existing handler
  6. Key rules
  7. Complete examples
  8. Related skills
  9. Verify your work
Original SKILL.md headings · 217 lines, 954 words
SKILL.md preview
---
name: add-command
description: Add a complete command flow to an existing aggregate. It creates a command class, a FastAPI API endpoint, and a command handler with repository logic. This is the primary workflow for adding write operations to a Protean domain. Use when the user wants to "add a command", "add an action", "add an operation", "expose a write endpoint", "create a command flow", "wire up a POST endpoint", "add a new operation to an aggregate", or describes an action like "I want users to be able to [verb] a [thing]" (e.g., "place an order", "register a user", "cancel a reservation"). This workflow composes the command, command-handler, and api-endpoint element skills.
license: Apache-2.0
compatibility: Requires Python 3.11+, protean framework, fastapi
metadata:
  author: proteanhq
  version: "0.1"
  category: workflow
  composes: [command, command-handler, api-endpoint]
---

# Add Command Flow

This workflow adds a complete command flow to an existing aggregate. It creates three artifacts that work together:

1. **Command**: An immutable DTO expressing intent (e.g., `PlaceOrder`)
2. **API Endpoint**: A thin FastAPI adapter that accepts HTTP payloads and submits commands
3. **Command Handler**: Orchestrates aggregate creation/loading, method invocation, and persistence

## What this creates

| Artifact | Role | File location |
|----------|------|---------------|
| Command class | Carries intent data | `<aggregate_folder>/<verb>_<noun>.py` |
| Command Handler | Loads/creates aggregate, calls methods, persists | Same file as command |
| API Endpoint | Translates HTTP to command, calls `domain.process()` | `<aggregate_folder>/<noun>_api.py` |

## Information to gather

Before generating, ensure you know the following. **If any item is unknown, ask the user before proceeding.**

- [ ] **Which aggregate** the command targets (must already exist)
- [ ] **Action name** (imperative verb + noun, e.g., PlaceOrder, CancelReservation)
- [ ] **Command fields** (the data needed to perform the action)
- [ ] **Create vs. Update**: Does this create a new aggregate or modify an existing one?
- [ ] **Aggregate method**: What method on the aggregate performs the business logic?
- [ ] **HTTP verb and route**: POST for creation, PUT for updates/actions

## Process

### Step 1: Define the Command

Follow the patterns in [command](../command/SKILL.md).

Key points for this workflow:
- Name with imperative verb: `PlaceOrder`, `RegisterUser`, `CancelReservation`
- Always specify `part_of="AggregateName"` (string, not class reference)
- Include all fields the handler needs (IDs, data fields)
- Commands are DTOs: only simple fields and value objects, no `HasOne`/`HasMany`

```python
@domain.command(part_of="Order")
class PlaceOrder:
    order_id: Identifier(required=True)
    customer_id: String(required=True)
    total_amount: Decimal(precision=19, scale=4, required=True)
```

### Step 2: Define the Command Handler

Follow the patterns in [command-handler](../command-handler/SKILL.md).

Key points for this workflow:
- Use `part_of=AggregateClass` when the class is in scope. A string reference also works and resolves at `init`
- Use `@handle(CommandClass)` decorator on handler methods
- **Creating aggregates**: Construct from command data, call method, persist with `domain.repository_for(Aggregate).add()`
- **Updating aggregates**: Load with `domain.repository_for(Aggregate).get(id)`, call method, persist
- Return the aggregate's identifier for synchronous processing
- Each handler runs within an implicit UnitOfWork, so do not wrap it in one

The handler works on an existing `Order` aggregate like this one:

```python
from decimal import Decimal as D


@domain.aggregate
class Order:
    order_id: Identifier(identifier=True)
    customer_id: String(required=True)
    total_amount: Decimal(precision=19, scale=4)
    status: String(default="draft")
    cancellation_reason: String()

    def place(self, total_amount: D):
        self.total_amount = total_amount
        self.status = "placed"

    def cancel(self, reason: str):
        self.status = "cancelled"
        self.cancellation_reason = reason
```

```python
@domain.command_handler(part_of=Order)
class OrderCommandHandler:
    @handle(PlaceOrder)
    def handle_place_order(self, command: PlaceOrder):
        order = Order(
            order_id=command.order_id,
            customer_id=command.customer_id,
        )
        order.place(total_amount=command.total_amount)
        domain.repository_for(Order).add(order)
        return order.order_id
```

### Step 3: Define the API Endpoint

Follow the patterns in [api-endpoint](../api-endpoint/SKILL.md).

Key points for this workflow:
- The endpoint is a thin adapter with no business logic
- Call `domain.init()` at app startup (the `lifespan` hook), after every registration and before the first request
- Always set up domain context middleware
- Construct command from request payload (and path parameters)
- Use `current_domain.process(command, asynchronous=False)` for synchronous processing
- Return appropriate HTTP status codes (201 for creation, 200 for updates)

```python
from contextlib import asynccontextmanager

from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

from protean import current_domain


@asynccontextmanager
async def lifespan(app: FastAPI):
    # Wire the commands and handlers once, before the app takes requests
    domain.init()
    try:
        yield
    finally:
        # Release the adapter connections on shutdown, even after an error
        domain.close()


app = FastAPI(lifespan=lifespan)


@app.middleware("http")
async def domain_context_middleware(request: Request, call_next):
    with domain.domain_context():
        return await call_next(request)


@app.post("/orders", status_code=201)
async def create_order(request: Request):
    payload = await request.json()
    command = PlaceOrder(
        order_id=payload["order_id"],
        customer_id=payload["customer_id"],
        total_amount=payload["total_amount"],
    )
    result = current_domain.process(command, asynchronous=False)
    return JSONResponse(status_code=201, content={"order_id": result})
```

## File organization (Screaming Architecture)

Colocate command + handler in a single file named after the action. Place API endpoints in a separate `<aggregate>_api.py` file:

```
src/myapp/order/
├── order.py              # Aggregate + entities + VOs
├── place_order.py        # PlaceOrder command + OrderCommandHandler
├── cancel_order.py       # CancelOrder command (add to existing handler or new file)
└── order_api.py          # All API endpoints for Order
```

## Adding to an existing handler

When the aggregate already has a command handler, add the new `@handle` method to the existing handler class rather than creating a second one. Protean enforces one handler per command but allows multiple `@handle` methods in one handler class.

```python
# In place_order.py - add new command and handler method
@domain.command(part_of="Order")
class CancelOrder:
    order_id: Identifier(required=True)
    reason: String(required=True)

# Add to existing handler
@domain.command_handler(part_of=Order)
class OrderCommandHandler:
    @handle(PlaceOrder)
    def handle_place_order(self, command): ...

    @handle(CancelOrder)
    def handle_cancel(self, command: CancelOrder):
        order = domain.repository_for(Order).get(command.order_id)
        order.cancel(reason=command.reason)
        domain.repository_for(Order).add(order)
```

## Key rules

1. **Commands use `part_of="String"`**: Handlers usually pass the class, `part_of=ClassRef`, and a string works on a handler too
2. **One handler per command**: Protean enforces this; multiple `@handle` methods in one handler is fine
3. **Implicit UnitOfWork**: Do NOT wrap handler methods in manual UnitOfWork
4. **Endpoints are thin**: Only construct commands and call `domain.process()`. No repository access, no business logic
5. **Endpoints call `current_domain.process()`**: Never call a handler directly
6. **Domain context middleware is required**: Without it, `current_domain` is not available
7. **Return values**: Handler returns go back to the caller when using `asynchronous=False`

## Complete examples

- [Create-aggregate command flow](references/create-aggregate-flow.md): Full flow for creating a new aggregate (POST)
- [Update-aggregate command flow](references/update-aggregate-flow.md): Full flow for modifying an existing aggregate (PUT)
- [Multiple commands flow](references/multiple-commands-flow.md): Adding multiple commands to one aggregate

### Asset files
- [add_command_create_flow.py](assets/add_command_create_flow.py): Complete create-aggregate flow with endpoint
- [add_command_update_flow.py](assets/add_command_update_flow.py): Complete update-aggregate flow with endpoint
- [add_command_multiple_commands.py](assets/add_command_multiple_commands.py): Multiple commands with shared handler and router

## Related skills

- [command](../command/SKILL.md): Command definition, fields, and naming
- [command-handler](../command-handler/SKILL.md): Handling commands and orchestrating aggregates
- [api-endpoint](../api-endpoint/SKILL.md): Exposing commands over HTTP

## Verify your work

- [Verify with check](../../references/verify-with-check.md): run `check` and resolve what it reports
Files in this package (7)
  • SKILL.md 9 KB
  • assets/add_command_create_flow.py 4 KB
  • assets/add_command_multiple_commands.py 7 KB
  • assets/add_command_update_flow.py 6 KB
  • references/create-aggregate-flow.md 3 KB
  • references/multiple-commands-flow.md 5 KB
  • references/update-aggregate-flow.md 4 KB

Versions

RepositoryScoreLicence
This page · proteanhq/protean100Apache-2.0
todoist/todoist-cli100MIT
doist/todoist-cli100MIT
coralogix/cx-cli100Apache-2.0
GO-VIRTUAL-bv/tile38.go100MPL-2.0
steamfield/stacks96Apache-2.0
steamfield/stacks96Apache-2.0
ldayton/dippy95MIT
steamfield/stacks86Apache-2.0

Identical content appears in 1 other GitHub folders. We show one copy with the highest score.

Database snapshot: 13.11.2026 · package version bbd3673ddf32 (SHA-256 digest of the entire package)

Downloads in the last 30 days: 0 · ranking

Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 100add-use-case
    Build a complete vertical slice in Protean, the full command flow from command definition through handler, aggregate mutation, event raising, and event handler reaction. This is the most common workflow for adding a new feature. Use when the user asks to "add a use case", "add a…
  • 100add-event
    Add a complete event flow to an existing aggregate. It creates a domain event, adds or updates an aggregate method that raises the event via self.raise_(), and wires an event handler that processes the event and performs specified side effects (such as syncing state across…
  • 100add-feature
    Add a vertical-slice feature (command/query + handler + validator + endpoint) to an existing FSH module. Use when adding an API endpoint or business operation to a module that already exists.
  • 100add-operation
    Add an API operation to a TurbineKit project. One operation is a REST endpoint, an MCP tool and an OpenAPI entry at once, backed by a service function that server actions reuse. Use for any new endpoint, tool, or action on a resource, including a whole new resource.
  • 90add-api-endpoint
    Use when a ticket asks to add or extend an HTTP/API endpoint — a new route, handler, or RPC method — with request validation and a defined response. Invoke for "add a POST /things endpoint", "expose a list API", or "add a field to the X response".
  • 96add-tool
    Add a tool to this MCP server, with typed input and output structs, domain logic, registration through addTool and in-memory protocol tests. Use when the user asks for a new tool, action, command or capability the agent host should be able to call.

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.