Skip to content
VerificationWould you notice if your agent drifted in production?Explore the 5-stage harness›
Specification Language

Operations: Queries, Mutations & Streams

This guide shows how to declare API operations in TypeSpec—including automated database queries with cursor pagination, auto-mutations with cache invalidation, real-time WebSocket streams, and custom server hooks.

  • An existing Aegil project with at least one model declared in specs/<feature>/*.tsp.
  • Basic understanding of TypeSpec syntax and types.

In traditional stacks, building a feature requires writing:

  1. An HTTP route or RPC endpoint on the server.
  2. A database query or mutation with transaction boundaries.
  3. Serialization and deserialization boilerplate on both ends.
  4. A client service, network caller, and state management class (BLoC/Notifier).

In Aegil, you write one operation signature in TypeSpec. The compiler generates the Serverpod endpoint, SQL query, network protocol, and reactive Flutter BLoC automatically.


The @autoQuery decorator generates an end-to-end read endpoint with built-in database queries, pagination, and Flutter state management.

@public
@autoQuery({
entity: "Note",
paginate: "cursor",
filterBy: ["ownerId"],
sortBy: ["createdAt"]
})
op listNotes(ownerId?: uuid, limit?: int): Page<Note>;
Parameter Type Description
entity string The target model name to query.
paginate "cursor" | "offset" The pagination strategy. Cursor-based pagination is recommended for high-performance and infinite scrolling.
filterBy string[] Fields that clients can filter by as query parameters.
sortBy string[] Allowed database sort columns.
  1. Serverpod Endpoint: Generates server/lib/src/endpoints/note_endpoint.g.dart executing parameterized SQL queries against PostgreSQL.
  2. Cursor Pagination: Returns a Page<Note> containing items, nextCursor, and hasMore.
  3. Flutter BLoC: Generates NoteBloc with ListNotesRequested(limit: ..., filter: ...) in client/lib/api.dart.
// Flutter UI usage
context.read<NoteBloc>().add(const ListNotesRequested(limit: 50));

The @autoMutation decorator generates create, update, or delete endpoints without hand-written database code.

@public
@autoMutation({
entity: "Note",
action: "create",
touches: ["Note"]
})
op addNote(title: string, content: string): Note;
Parameter Type Description
entity string The target model name being modified.
action "create" | "update" | "delete" The CRUD operation performed.
touches string[] Entities whose caches must be invalidated upon successful execution.

When addNote completes successfully, Aegil automatically invalidates any cached queries observing Note. The Flutter NoteBloc immediately refreshes its items in memory without requiring manual UI re-fetching logic.


To push database changes to connected clients over WebSockets in real time, use @autoStream:

@autoStream({ entity: "Ticket" })
op watchTickets(): Stream<Ticket>;
  1. Serverpod Streaming: Serverpod opens an active WebSocket connection between the client and server.
  2. Event Emission: Whenever an @autoMutation modifying Ticket succeeds, the server broadcasts the updated entity to listening sessions.
  3. Flutter UI: The generated TicketBloc listens to the stream and yields new states automatically:
BlocProvider(
create: (_) => TicketBloc(client: client, enableRealtimeStream: true),
child: const TicketScreen(),
)

Custom Mutations (@mutation) and Server Hooks

Section titled “Custom Mutations (@mutation) and Server Hooks”

For complex business logic—such as processing Stripe payments, issuing third-party API calls, or enforcing multi-entity state transitions—use @mutation.

@mutation
op escalateTicket(ticketId: uuid, reason: string): Ticket;

Unlike @autoMutation, @mutation does not generate auto-CRUD SQL. Instead, it generates a Server Business Hook contract:

  1. The compiler generates an abstract handler interface in .aegil/server/.
  2. The Action Manifest lists a pending task for hooks/escalate_ticket_hook.dart.
  3. You implement the business logic in Zone 2:
hooks/escalate_ticket_hook.dart
import 'package:helpdesk_server/api.dart';
class EscalateTicketHook implements EscalateTicketHandler {
@override
Future<Ticket> handle(Session session, EscalateTicketInput input) async {
// Auth, transactions, and CEL policy checks are already verified by the compiler!
// Write your isolated business side-effects here:
final ticket = await Ticket.db.findById(session, input.ticketId);
ticket.status = TicketStatus.Escalated;
await ticket.save(session);
return ticket;
}
}

By default, every operation requires an authenticated user session. The compiler automatically verifies that a valid session token exists before executing endpoint logic.

For onboarding, login, public landing pages, or public counters, attach @public:

// Accessible to anyone without signing in
@public
@autoQuery({ entity: "Article", paginate: "cursor", filterBy: [], sortBy: ["publishedAt"] })
op listPublicArticles(): Page<Article>;

[!WARNING] Operations targeting entities with @policy rules cannot be marked @public if the policy relies on auth.id or auth.role. Doing so triggers ERR_PUBLIC_ON_PROTECTED_ENTITY at compile time.