Sets up CQRS (command/query separation) with handlers and a pipeline for validation, logging, and transactions across .NET, NestJS, Express/Fastify, Python, Spring Boot, and Go stacks.
Ships in AI for Developers Toolkit. 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.
Wire up CQRS: command/query separation, one handler per use case, and the cross-cutting pipeline (validation, logging, transactions) that makes CQRS pay off - using the idiom of the project's stack, with or without a mediator library.
Works on a target, not pasted snippets: a file, folder, project/repo, or GitHub URL (git clone --depth 1 <url> then scan). If the project exists, read one feature first and match its conventions (folder layout, naming, return types, error handling).
| Manifest | Stack | Default approach |
|---|---|---|
*.csproj | C# / .NET | MediatR if already referenced; otherwise offer MediatR (check license), a source-generated mediator, or a thin custom dispatcher |
package.json with @nestjs/core | NestJS | @nestjs/cqrs (CommandBus, QueryBus, @CommandHandler) |
package.json (Express/Fastify) | Node / TypeScript | Plain handler functions or classes + a small typed dispatcher or direct calls |
pyproject.toml / requirements*.txt | Python | Plain handlers + a message-bus dict, decorators for cross-cutting concerns |
pom.xml / build.gradle(.kts) | Java / Kotlin (Spring) | Plain @Service command handlers and query services; Spring AOP/@Transactional/Bean Validation for the pipeline; Axon Framework only for full CQRS/ES |
go.mod | Go | Handler structs with Handle(ctx, cmd) + decorator wrappers; Watermill CQRS if commands go over a broker |
CreateOrder, GetOrderById.Choosing the dispatcher: MediatR is the common default, but recent major versions moved to a commercial license (with a free tier for some organizations) - check the license terms for the user's org before adding it, or stay on the version already in use. Alternatives: a source-generated mediator (e.g. the Mediator package), Wolverine, or a thin custom dispatcher (an ICommandHandler<TCommand, TResult> interface resolved from DI plus decorators).
dotnet add package MediatR
dotnet add package FluentValidation.DependencyInjectionExtensions
builder.Services.AddMediatR(c => c.RegisterServicesFromAssembly(typeof(Program).Assembly));
builder.Services.AddValidatorsFromAssembly(typeof(Program).Assembly);
Command + handler:
public record CreateOrderCommand(Guid CustomerId, List<OrderLine> Lines) : IRequest<Result<Guid>>;
public class CreateOrderHandler(IOrderRepository repo, IUnitOfWork uow)
: IRequestHandler<CreateOrderCommand, Result<Guid>>
{
public async Task<Result<Guid>> Handle(CreateOrderCommand cmd, CancellationToken ct)
{
var order = Order.Create(cmd.CustomerId, cmd.Lines);
await repo.AddAsync(order, ct);
await uow.SaveChangesAsync(ct);
return Result.Success(order.Id);
}
}
Queries are the same shape with IRequest<TDto> and a read-only handler (AsNoTracking, projection).
Pipeline behaviors (where CQRS earns its keep):
public class ValidationBehavior<TReq, TRes>(IEnumerable<IValidator<TReq>> validators)
: IPipelineBehavior<TReq, TRes> where TReq : notnull
{
public async Task<TRes> Handle(TReq req, RequestHandlerDelegate<TRes> next, CancellationToken ct)
{
foreach (var v in validators)
{
var r = await v.ValidateAsync(req, ct);
if (!r.IsValid) throw new ValidationException(r.Errors); // or map to a Result
}
return await next();
}
}
builder.Services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));
Add LoggingBehavior and a TransactionBehavior (open a transaction around commands only) the same way. With a custom dispatcher, implement the same three as decorators (Scrutor's Decorate or manual registration).
NestJS (@nestjs/cqrs):
export class CreateOrderCommand { constructor(readonly customerId: string, readonly lines: OrderLine[]) {} }
@CommandHandler(CreateOrderCommand)
export class CreateOrderHandler implements ICommandHandler<CreateOrderCommand> {
constructor(private readonly orders: OrderRepository) {}
async execute(cmd: CreateOrderCommand): Promise<string> {
const order = Order.create(cmd.customerId, cmd.lines);
await this.orders.save(order);
return order.id;
}
}
// module: imports: [CqrsModule], providers: [CreateOrderHandler]
// controller: return this.commandBus.execute(new CreateOrderCommand(dto.customerId, dto.lines));
Queries use QueryBus + @QueryHandler. Validation stays in ValidationPipe at the controller; logging/transactions via interceptors or a wrapper around the handler.
Express / Fastify (no framework bus): plain handlers typed as (cmd: C) => Promise<R>, composed with higher-order wrappers - withValidation(schema), withTransaction(db), withLogging(name) - and called directly from the route. A map-based dispatcher is only worth it when something must dispatch by message type (queues, jobs).
Plain handlers plus a small bus, in the "Cosmic Python" message-bus style:
@dataclass(frozen=True)
class CreateOrder:
customer_id: UUID
lines: list[OrderLine]
def create_order(cmd: CreateOrder, uow: UnitOfWork) -> UUID:
with uow:
order = Order.create(cmd.customer_id, cmd.lines)
uow.orders.add(order)
uow.commit()
return order.id
COMMAND_HANDLERS = {CreateOrder: create_order}
def dispatch(cmd, uow):
handler = COMMAND_HANDLERS[type(cmd)]
log.info("handling", command=type(cmd).__name__)
return handler(cmd, uow)
Validation comes from Pydantic models at the edge (FastAPI) or serializers (DRF); transactions from the unit of work or transaction.atomic() (Django); logging/metrics as decorators on handlers. Query handlers select columns straight into DTOs. Async: same shape with async def.
CQRS in Spring is usually just discipline, not a library: OrderCommandService methods (or one @Service per command) annotated @Transactional, and OrderQueryService with @Transactional(readOnly = true) returning DTO projections. Validation via @Validated + Bean Validation on command records; logging/metrics via an aspect or Micrometer @Observed. Separate read repositories (interface projections, JdbcClient/jOOQ) from the write-side JPA repositories. Reach for Axon Framework only when you also want event sourcing and distributed command/query buses.
type CreateOrder struct { CustomerID string; Lines []OrderLine }
type CommandHandler[C any, R any] interface { Handle(ctx context.Context, cmd C) (R, error) }
type createOrderHandler struct { repo OrderRepository; tx TxManager }
func (h createOrderHandler) Handle(ctx context.Context, cmd CreateOrder) (string, error) {
var id string
err := h.tx.WithinTx(ctx, func(ctx context.Context) error {
o, err := NewOrder(cmd.CustomerID, cmd.Lines)
if err != nil { return err }
id = o.ID
return h.repo.Save(ctx, o)
})
return id, err
}
Cross-cutting concerns as decorators implementing the same interface (loggingDecorator[C, R], metricsDecorator), composed in main/wiring. Keep app/command and app/query packages separate. Use Watermill's CQRS component only when commands/events travel over a message broker.
## Detected
<stack, existing conventions, dispatcher chosen and why (incl. license note for MediatR)>
## Files
<commands/queries, handlers, pipeline pieces, registration - full code>
## Wiring
<DI/module registration and how endpoints call it>
## When not to
<anything that should stay a direct call>
Point it at a project and say what you want: "add CQRS with MediatR + validation/transaction behaviors", "CQRS without MediatR", "convert these controllers to commands/queries", "set up @nestjs/cqrs for orders", "command handlers with a unit of work in my FastAPI app", "split my Spring service into command and query services", "command handlers with logging decorators in Go". For new feature slices pair with clean-architecture-scaffolder; for handler return types pair with result-pattern-scaffolder.
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
cqrs, command-query-separation, mediator, pipeline-behaviors
45 skills in this plugin
/api-endpoint-scaffolderScaffold HTTP API endpoints in any stack - ASP.NET Core Minimal APIs or controllers, Express, Fastify, NestJS, FastAPI, Django REST Framework, Spring Boot controllers, Go net/http, chi, Gin - one feature per endpoint (REPR style) with request validation, typed responses, route grouping, auth, and OpenAPI metadata. Use this skill whenever the user wants to add an endpoint or route, convert controllers to minimal APIs, structure routes or routers, set up endpoint groups, TypedResults, route handlers, request DTOs/schemas (zod, Pydantic, Bean Validation, binding tags), or asks "how do I add an endpoint / structure my API routes". Always use this skill for endpoint scaffolding; it generates a complete, validated endpoint that matches the project's conventions./architecture-test-generatorGenerate architecture tests / fitness functions that fail the build when architectural rules are violated - layer dependencies, module boundaries, cycles, naming, and visibility conventions - in any stack: NetArchTest or ArchUnitNET (.NET), ArchUnit or Konsist (Java/Kotlin), dependency-cruiser or eslint-plugin-boundaries (TypeScript/JavaScript), import-linter (Python), go-arch-lint or depguard (Go). Use this skill whenever the user wants architecture tests, to enforce layering or the dependency rule, dependency rules as tests, import rules, forbidden imports, no circular dependencies, naming conventions, fitness functions, or asks "how do I stop people breaking the architecture / enforce my layers / keep modules from importing each other". Always use this skill for architecture-test requests; it generates rules matching the project's real structure./async-await-auditorAudit async and concurrent code in any language for correctness and performance bugs - C#/.NET (async/await, Task), JavaScript/TypeScript (Promises, async/await), Python (asyncio), Java/Kotlin (CompletableFuture, virtual threads, coroutines), Go (goroutines, channels, context), Rust (tokio/async). Use this skill whenever the user shares async or concurrent code, or asks about deadlocks, hangs, blocking calls, .Result/.Wait(), async void, ConfigureAwait, floating or unhandled promises, await in a loop vs Promise.all, blocking the event loop, forgotten await, asyncio.gather/TaskGroup, CompletableFuture.join, virtual thread pinning, goroutine leaks, context cancellation, WaitGroup/errgroup, holding a lock across .await, fire-and-forget tasks, cancellation tokens, or "why does my async code hang". Always use this skill for async/concurrency reviews instead of answering from memory; it applies a fixed checklist and rewrites the code./authorization-setupDesign API authorization in any stack - policy-based, role-based, claims/permission-based, and resource-based (ownership) checks. Covers ASP.NET Core policies and AuthorizationHandler, NestJS guards, Express middleware and CASL, FastAPI dependencies/scopes, Django and DRF permission classes, Spring Security (@PreAuthorize, SecurityFilterChain), Go middleware, and Casbin/OPA. Use this skill whenever the user wants authorization policies, role/claim/permission checks, RBAC/ABAC, custom authorization rules, resource-based authorization, IDOR protection, "deny by default", or asks "how do I authorize this / policy vs role / restrict this endpoint to X / stop users seeing other users' data". Always use this skill for authorization requests; it generates policies, handlers, and endpoint wiring./benchmark-setupSet up correct micro-benchmarks in any stack and interpret the results - BenchmarkDotNet (.NET), JMH (Java/Kotlin), pytest-benchmark / pyperf (Python), Vitest bench / tinybench / mitata (JavaScript/TypeScript), Go testing.B + benchstat, Rust criterion. Use this skill whenever the user wants to benchmark code, measure performance, compare two implementations or functions, set up a benchmark harness, or asks "which is faster", "benchmark these two functions", "how do I benchmark this", "is this optimization worth it", or "interpret these benchmark results". Always use this skill for micro-benchmarking requests; it writes correct benchmarks, avoids the classic pitfalls, and explains the numbers./caching-strategy-setupAdd the right caching to an app in any stack - in-process, distributed (Redis/Valkey/Memcached), two-level, or HTTP/output caching - with correct keys, expiration, stampede protection, and invalidation. Covers HybridCache / IMemoryCache / IDistributedCache / output caching in .NET, lru-cache / keyv / cache-manager / ioredis in Node, functools / cachetools / redis-py / Django cache in Python, Spring Cache with Caffeine or Redis in Java/Kotlin, and ristretto / groupcache / singleflight / go-redis in Go. Use this skill whenever the user wants caching, to cache a query/response, Redis caching, @Cacheable, lru_cache, HybridCache, cache-aside, output caching, or asks "how do I cache this / add caching / avoid cache stampede / invalidate this cache". Always use this skill for caching requests; it picks the right layer and wires expiration + invalidation correctly./ai-dev-toolkit:cqrs-setupfrom AI for Developers Toolkit
npx claudepluginhub stefanthecode/ai-for-developers --plugin ai-dev-toolkitOther plugins' skills for the same job