/protean:application-servicefrom protean
Defines a Protean application service: a stateless orchestration layer that coordinates use cases between external callers and the domain model. Use for pure DDD (non-CQRS) to load aggregates, invoke domain methods, and persist results without business 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.
from protean import Domain, current_domain, use_case
from protean.fields import Identifier, String
domain = Domain()
@domain.aggregate
class User:
email: String(required=True)
name: String()
status: String(default="INACTIVE")
def activate(self):
self.status = "ACTIVE"
@domain.application_service(part_of=User)
class UserServices:
@use_case
def register_user(self, email: str, name: str) -> Identifier:
user = User(email=email, name=name)
current_domain.repository_for(User).add(user)
return user.id
@use_case
def activate_user(self, user_id: Identifier) -> None:
user = current_domain.repository_for(User).get(user_id)
user.activate()
current_domain.repository_for(User).add(user)
@domain.application_service(part_of=User). A string reference (part_of="User") also works and resolves at init@use_case to get automatic UnitOfWork wrapping. Import from protean: from protean import use_case@use_case method runs within a UnitOfWork automatically. On a provider with transactions (the SQL databases), a Unit of Work is one real database transaction: on success, changes are committed; on exception, everything is rolled back. On the in-memory provider, a rollback discards the changes the Unit of Work has not committed. On Elasticsearch, commit and rollback are not atomic, and a rollback does not undo writes already sentdomain.init() and inside with domain.domain_context():. A use case called with no active domain context raises ConfigurationError. NOT dispatched via domain.process()register_user, place_order, cancel_subscription@use_case runs the method once. A version conflict (ExpectedVersionError) reaches the caller like any other exception. Command and event handlers retry it; use cases do not@domain.aggregate
class Account:
email: String(required=True)
status: String(default="INACTIVE")
def activate(self):
self.status = "ACTIVE"
def deactivate(self):
self.status = "INACTIVE"
@domain.application_service(part_of=Account)
class AccountServices:
@use_case
def create_account(self, email: str) -> Identifier:
account = Account(email=email)
current_domain.repository_for(Account).add(account)
return account.id
@use_case
def activate_account(self, account_id: Identifier) -> None:
account = current_domain.repository_for(Account).get(account_id)
account.activate()
current_domain.repository_for(Account).add(account)
@use_case
def deactivate_account(self, account_id: Identifier) -> None:
account = current_domain.repository_for(Account).get(account_id)
account.deactivate()
current_domain.repository_for(Account).add(account)
domain.init(traverse=False)
# Direct instantiation and call (NOT domain.process())
with domain.domain_context():
svc = AccountServices()
account_id = svc.create_account(email="[email protected]")
svc.activate_account(account_id=account_id)
In tests, the test_domain fixture activates a domain context for you.
Besides the Unit of Work and the domain context check (Key rules 2 to 4), @use_case logs each call at INFO level.
Only @use_case-decorated methods get UoW treatment. Regular helper methods do not:
from protean.exceptions import ValidationError
from protean.fields import List
@domain.aggregate
class Order:
items: List(content_type=String)
@classmethod
def place(cls, items: list) -> "Order":
if not items:
raise ValidationError({"items": ["Order must have items"]})
return cls(items=items)
@domain.application_service(part_of=Order)
class OrderServices:
@use_case
def place_order(self, items: list) -> Identifier:
# Runs inside UnitOfWork
order = Order.place(items=self._clean_items(items))
current_domain.repository_for(Order).add(order)
return order.id
def _clean_items(self, items: list) -> list:
# Regular helper - NO UnitOfWork wrapping
return [item.strip() for item in items if item.strip()]
Exceptions propagate directly to the caller. The UnitOfWork auto-rolls back. The caller, here an API handler, maps them to responses:
def register_user_endpoint(email: str, name: str):
with domain.domain_context():
try:
user_id = UserServices().register_user(email=email, name=name)
except ValidationError as exc:
return 400, exc.messages
# Other exceptions reach the web framework, which returns a 500
return 201, {"id": user_id}
status, body = register_user_endpoint(email="[email protected]", name="John")
assert status == 201
status, body = register_user_endpoint(email=None, name="John")
assert status == 400
| Aspect | Application Service | Command Handler |
|---|---|---|
| Invocation | Direct: svc.method() | Via dispatch: domain.process(cmd) |
| Return values | Always synchronous | Depends on sync/async mode |
| Error handling | Exceptions propagate to caller | handle_error hook available |
| Version conflict | Raised to the caller, no retry | Retried by default |
| Architecture | Pure DDD | CQRS |
| Input | Plain Python arguments | Command DTO |
When evolving to CQRS, application services are replaced by commands + command handlers.
# fragment
@use_case
def place_order(self, items: list) -> Identifier:
if len(items) == 0:
raise ValidationError({"items": ["Order must have items"]}) # Wrong!
total = sum(i.price * i.quantity for i in items) # Wrong!
order = Order(items=items, total=total)
...
Instead: Push business logic into the aggregate, as Order.place() does in the @use_case example above.
# fragment
# Wrong! Application services are not dispatched via domain.process()
domain.process(some_service_call)
Instead: Instantiate and call directly, inside a domain context, as the Invocation pattern shows.
# fragment
@use_case
def register_user(self, email, name):
with UnitOfWork(): # Unnecessary! Already implicit via @use_case
user = User(email=email, name=name)
...
The inner Unit of Work joins the one @use_case opened, so it adds nothing. Instead: Let @use_case handle the UnitOfWork
# fragment
@use_case
def register_user(self, email, name):
user = User(email=email, name=name)
current_domain.repository_for(User).add(user)
return user.id
# fragment
@use_case
def transfer_funds(self, from_id, to_id, amount):
from_acct = current_domain.repository_for(Account).get(from_id)
to_acct = current_domain.repository_for(Account).get(to_id)
from_acct.debit(amount)
to_acct.credit(amount)
current_domain.repository_for(Account).add(from_acct)
current_domain.repository_for(Account).add(to_acct) # Wrong!
This code runs, and the Unit of Work commits both accounts in one transaction. One aggregate per transaction is a design rule you follow yourself, so this code breaks it. Two instances of the same aggregate type count as two aggregates.
Instead: Change one account in the use case. The account raises an event (for example FundsDebited). An event handler in Account's cluster reacts to it and issues a command (for example CreditFunds). That command's handler credits the other account, and skips a transfer it has already applied, because events can be delivered more than once. The event-handler skill's cross-aggregate reference shows this pattern in full.
aggregate: Application services orchestrate aggregatescommand-handler: CQRS alternative; replaces application services when evolving to CQRSevent: Aggregates may raise events during application service operationsrepository: Application services use repositories to load/persist aggregatesdomain-service: Cross-aggregate logic invoked from application servicescheck and resolve what it reportsassets/application_service_error_handling.py (opens in a new tab)assets/application_service_multiple_use_cases.py (opens in a new tab)assets/application_service_return_values.py (opens in a new tab)assets/application_service_simple.py (opens in a new tab)assets/application_service_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/return-values.md (opens in a new tab)references/unit-of-work.md (opens in a new tab)references/use-case-decorator.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub proteanhq/protean --plugin protean39 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".Other plugins' skills for the same job