/protean:command-handlerfrom protean
Defines a Protean command handler that receives domain commands and orchestrates state changes in aggregates. Use when implementing the write side of CQRS or connecting commands to aggregate logic.
Ships in protean. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
A command handler turns one aggregate's commands into changes to that aggregate: it loads or creates the aggregate, calls a method on it, and persists it. This skill defines handlers, their options, and how they fail.
from protean import Domain, handle
from protean.fields import Identifier, String
domain = Domain()
@domain.aggregate
class Order:
order_id: Identifier(identifier=True)
status: String(default="draft")
def place(self):
self.status = "placed"
@domain.command(part_of="Order")
class PlaceOrder:
order_id: Identifier(required=True)
@domain.command_handler(part_of=Order)
class OrderCommandHandler:
@handle(PlaceOrder)
def handle_place_order(self, command: PlaceOrder):
order = Order(order_id=command.order_id)
order.place()
domain.repository_for(Order).add(order)
@domain.command_handler(part_of=Order)part_of pointing to the SAME aggregate as the handler@handle(CommandClass)def method_name(self, command: CommandClass)@handle wraps every handler call in its own Unit of Work, which is one real database transaction on a provider with transactions, such as the SQL databases (ADR-0027). Do not wrap the body yourself. See Unit of Workfrom protean import handle (not from protean.core)part_of=AggregateClass. A string, part_of="AggregateName", also works on the handler and resolves at init, so the aggregate may be defined after the handler. Commands use the string form| Option | Default | Description |
|---|---|---|
part_of | None | The aggregate this handler belongs to, as a class or a string name. Required: registration fails without it |
stream_category | derived from part_of | The command stream the handler reads, <aggregate stream category>:command. Always derived from the aggregate; a value you pass is replaced |
timeout | None | Default validity window, in seconds or a timedelta, for commands this handler processes. Overrides the domain's command_default_timeout; a deadline or timeout passed to domain.process() overrides both |
retries | None | Maximum retries when the handler fails with a transient exception. Overrides the domain's server.transient_retry setting; None uses that setting |
backoff | None | Delay strategy between transient retries: "exponential", "linear" or "fixed". None uses the domain setting |
retry_exceptions | None | Exception types treated as transient, as classes or dotted paths. None uses the domain setting |
sequential_by | None | Name of an attribute on every command this handler handles. Registration checks that every handled command has the attribute. Commands do not go through the outbox yet, so they are not split by this value. See Sequential processing for what the option does on a command handler today |
subscription_type | None | SubscriptionType for the server's subscription. None uses the default |
subscription_profile | None | SubscriptionProfile preset for the subscription. None uses the default |
subscription_config | {} | Custom subscription settings that override the type and profile defaults |
suppress_checks | () | Diagnostic codes protean check should not report for this handler |
@domain.aggregate
class Account:
account_id: Identifier(identifier=True)
email: String(required=True)
status: String(default="pending")
def activate(self):
self.status = "active"
@domain.command(part_of="Account")
class RegisterAccount:
account_id: Identifier(required=True)
email: String(required=True)
@domain.command(part_of="Account")
class ActivateAccount:
account_id: Identifier(required=True)
@domain.command_handler(part_of=Account)
class AccountCommandHandler:
@handle(RegisterAccount)
def handle_register(self, command: RegisterAccount):
account = Account(
account_id=command.account_id,
email=command.email,
)
domain.repository_for(Account).add(account)
@handle(ActivateAccount)
def handle_activate(self, command: ActivateAccount):
account = domain.repository_for(Account).get(command.account_id)
account.activate()
domain.repository_for(Account).add(account)
Override handle_error classmethod for custom error recovery during async processing:
import logging
from protean.fields import Decimal, Identifier, String
logger = logging.getLogger(__name__)
@domain.aggregate
class Payment:
payment_id: Identifier(identifier=True)
amount: Decimal(precision=19, scale=4, required=True)
status: String(default="pending")
def execute(self):
self.status = "completed"
@domain.command(part_of="Payment")
class TransferFunds:
payment_id: Identifier(required=True)
amount: Decimal(precision=19, scale=4, required=True)
@domain.command_handler(part_of=Payment)
class PaymentCommandHandler:
@handle(TransferFunds)
def handle_transfer(self, command: TransferFunds):
payment = Payment(payment_id=command.payment_id, amount=command.amount)
payment.execute()
domain.repository_for(Payment).add(payment)
@classmethod
def handle_error(cls, exc: Exception, message) -> None:
logger.error(f"Payment failed: {exc}")
Initialize the domain once every element is registered, then process commands inside a domain context:
domain.init(traverse=False)
with domain.domain_context():
# Synchronous - blocks until done, returns handler result
result = domain.process(PlaceOrder(order_id="ORD-001"), asynchronous=False)
# Asynchronous (default) - returns position in event store
position = domain.process(PlaceOrder(order_id="ORD-002"))
# fragment
@handle(PlaceOrder)
def handle_place_order(self, command):
with UnitOfWork(): # Unnecessary! Already implicit
order = Order(order_id=command.order_id)
domain.repository_for(Order).add(order)
Instead: Let the implicit Unit of Work handle it. A with UnitOfWork(): inside the handler joins the outer one and adds nothing.
check reportscheck inspects your command handlers and reports these diagnostics:
COMMAND_HANDLER_CROSS_CLUSTER: the handler processes a command that belongs to another cluster, which puts that aggregate's write path outside its own consistency boundary. Move the handler into the owning cluster, or model the interaction as an event reaction across the boundary.HANDLER_TOO_BROAD: the handler handles more message types than the configured [lint] handler_breadth_limit, so it has grown into a catch-all. Split it into focused handlers, or raise the limit if the breadth is intentional.HANDLER_PERSISTS_AND_CALLS_OUT: one handler method calls an external system after its first repository_for(...), so the call runs with the Unit of Work's transaction open, holding row locks and a pooled connection for as long as the call takes, and a retry re-runs the method and re-issues the call. A call made before any repository access runs outside the transaction and is not flagged. Split the method into one that persists and one that calls out; when the call must follow the write, have the persisting method raise an event and handle that. If the write genuinely needs the call's result, keep both and pass the remote system's idempotency key so a retry does not duplicate the effect.command: Commands are the input to command handlersaggregate: Command handlers operate on aggregatesevent: Aggregates may raise events during handler processingevent-handler: Downstream processing of events raised during command handlingcheck and resolve what it reportsassets/command_handler_create_aggregate.py (opens in a new tab)assets/command_handler_error_handling.py (opens in a new tab)assets/command_handler_multiple_commands.py (opens in a new tab)assets/command_handler_simple.py (opens in a new tab)assets/command_handler_with_events.py (opens in a new tab)references/anti-patterns.md (opens in a new tab)references/error-handling.md (opens in a new tab)references/loading-aggregates.md (opens in a new tab)references/return-values.md (opens in a new tab)references/unit-of-work.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
39 skills in this plugin
/add-commandAdd 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./add-domain-service-flowBuild a domain service flow in Protean for business logic that spans two or more aggregates. Domain services are stateless, encapsulate cross-aggregate business rules, and run pre/post invariants for validation. They are used when business logic doesn't naturally belong to a single aggregate. Wire them into command handlers or application services for persistence. Use when the user asks to "add a domain service", "implement cross-aggregate logic", "coordinate multiple aggregates", "add a business operation spanning aggregates", "validate across aggregates", or when they describe scenarios like "placing an order checks inventory and reserves stock", "transferring funds between accounts", "scheduling involves both resource and calendar"./add-eventAdd 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 aggregates, sending notifications, or triggering downstream processes). This is the primary workflow for adding reactive, event-driven behavior to a Protean domain. Use when the user wants to "add an event", "add a domain event", "add a reaction to a state change", "add a side effect", "create an event flow", "wire an event handler", "add event-driven behavior", "react to a state change", "sync aggregates on event", or describes something that happened or should happen (like "when an order is placed, reduce inventory", "after payment is confirmed, send a notification", "when a user registers, create a welcome email", "notify the warehouse when an order ships"). This workflow composes the event, aggregate, and event-handler element skills./add-fieldAdd fields to Protean domain elements (aggregates, entities, value objects). Guides you through selecting the right field type, configuring validations, and placing fields correctly. Use when the user asks to "add a field", "add an attribute", "add a property", "I need to store [data]", "add a new field to [aggregate/entity]", or describes data that needs to be tracked. Covers simple fields, association fields (HasOne, HasMany, ValueObject), field validation, custom validators, and choosing between field types for different use cases./add-read-modelBuild a complete read model in Protean, a projection populated by a projector that reacts to domain events. Covers single-aggregate projections (flattened view of one aggregate), cross-aggregate projections (combining data from multiple aggregates), and choosing between database-backed and cache-backed storage. Use when the user asks to "add a read model", "create a projection with projector", "build a query view", "add a CQRS read side", "create a denormalized view", "build a reporting view", "add a dashboard query model", or when they need to combine data from multiple aggregates into one queryable structure./add-saga-flowBuild a complete saga in Protean using a process manager that coordinates a multi-step flow across several aggregates. The saga reacts to domain events, issues commands to drive each aggregate forward, tracks its own state, and closes on a terminal handler with a compensating path for failures. Use when the user asks to "add a saga", "coordinate a multi-step process", "orchestrate a workflow across aggregates", "manage order fulfillment", "add a process manager flow", "compensate on failure", "roll back a distributed transaction", or when they describe a flow like "reserve stock, take payment, then ship, and undo the reservation if payment fails".npx claudepluginhub proteanhq/protean --plugin proteanOther plugins' skills for the same job