/cap-developer:cap-messagingfrom cap-developer
Guides adding event-driven pub-sub messaging to CAP Node.js apps: declaring events in CDS, emitting/receiving with srv.emit/srv.on, transactional outbox, local file-based messaging, and production brokers like SAP Event Mesh.
Ships in cap-developer. 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.
None: SKILL.md is the whole skill.
Guide developers step-by-step through adding event-driven pub-sub messaging to a CAP Node.js application — from declaring events in CDS, wiring up emit/receive handlers, configuring a message channel for cross-process communication, ensuring reliable delivery with the outbox pattern, and connecting to production brokers.
Always use cds-mcp_search_docs to:
cds.MessagingService APIs and configuration options before writing codeCAP messaging has two layers:
| Layer | What it is |
|---|---|
| Conceptual | Events declared in CDS, emitted/received via service APIs — broker-independent |
| Technical | cds.MessagingService implementations that connect to real brokers |
In a single process, conceptual events flow through the CAP event bus with no broker needed. When services run in separate processes, a message channel is required — but application code stays unchanged. This is the key insight: topology (co-located vs. microservices) is a configuration concern, not a code concern.
Why messaging over synchronous calls:
Define events inside a service in a .cds file:
service ReviewsService {
event reviewed {
subject : String;
count : Integer;
rating : Decimal;
}
}
Conventions:
reviewed, OrderPlaced, StockChanged@topic, the topic is the fully qualified name: <namespace>.<ServiceName>.<EventName>@topic only when the broker requires a specific name:@topic: 'my.company/orders/placed/v1'
event OrderPlaced { ID: UUID; amount: Decimal; }
Emit from a service handler using this.emit:
module.exports = class ReviewsService extends cds.ApplicationService {
async init() {
this.after(['CREATE', 'UPDATE'], 'Reviews', async (review) => {
const { subject } = review
const { count, avg: rating } = await SELECT.one
`count(*) as count, avg(rating) as avg`
.from('Reviews').where({ subject })
await this.emit('reviewed', { subject, count, rating })
})
return super.init()
}
}
Key rules:
this.emit(eventName, data) inside a service handler — emits on the owning servicesrv.after, never srv.before — the transaction hasn't committed yet, and
the event would fire even if the operation is later rejectedSubscribe to events from another service using service.on:
module.exports = class BookstoreService extends cds.ApplicationService {
async init() {
const reviews = await cds.connect.to('ReviewsService')
const { Books } = this.entities
reviews.on('reviewed', async ({ data: { subject, count, rating } }) => {
await UPDATE(Books, subject).with({ numReviews: count, rating })
})
return super.init()
}
}
Key rules:
cds.connect.to('ServiceName')remoteService.on(...) — not this.on (that only receives events
on the current service)cds.User.privileged — implement authorization checks explicitly if neededIn-process eventing works out of the box. For separate processes, configure a channel.
file-based-messagingAdd to package.json:
"cds": {
"requires": {
"messaging": {
"[development]": { "kind": "file-based-messaging" }
}
}
}
Start each service in its own terminal — see cap-inner-loop for the server lifecycle
(starting in a separate terminal window, discovering the actual ports, stopping servers):
cds watch reviews
cds watch bookstore
Ports are assigned dynamically; use cds bindings to look up each server's real URL.
Messages emitted by reviews are written to ~/.cds-msg-box and picked up by bookstore —
even if bookstore was down when the message was emitted (resilience in action).
To inspect unconsumed messages:
cat ~/.cds-msg-box
# ReviewsService.reviewed {"data":{"subject":"201",...}, "headers": {...}}
Configure a real broker for production. Swap the kind per profile:
"cds": {
"requires": {
"messaging": {
"[development]": { "kind": "file-based-messaging" },
"[production]": { "kind": "event-broker" }
}
}
}
| Broker | npm add | kind |
|---|---|---|
| SAP Cloud Application Event Hub | @cap-js/event-broker | event-broker |
| SAP Event Mesh | @sap/xb-msg-amqp-v100 | enterprise-messaging |
| SAP Advanced Event Mesh | @cap-js/enterprise-messaging | enterprise-messaging |
Use cds-mcp_search_docs for the full configuration for each broker.
$namespace PlaceholderFor application-local events, scope topicRules in the Event Mesh service descriptor
(event-mesh.json) to the instance namespace. If the application consumes events from external
namespaces (for example SAP S/4HANA CloudEvents), explicitly allow those required topic patterns
instead. Avoid a bare *, which permits unrestricted cross-namespace publish/subscribe access:
// event-mesh.json
"topicRules": {
"publishFilter": ["${namespace}/*"], // MTA syntax — resolved at deploy time
"subscribeFilter": ["${namespace}/*"]
}
Scoping rules alone is not enough. Without a publishPrefix, CAP emits raw FQN topics
(e.g. OrdersService.OrderChanged) that don't start with the namespace, so the filter silently
rejects every message. The prefix requirement applies to both runtimes; only the config file and
syntax differ. For CAP Java (Spring), add matching prefixes in application.yaml:
# application.yaml (CAP Java/Spring) — cloud & hybrid profiles only
cds:
messaging.services:
samples-messaging:
kind: enterprise-messaging
publishPrefix: "$namespace/" # CAP runtime placeholder — single $, no braces
subscribePrefix: "$namespace/"
For CAP Node.js, set the same publishPrefix/subscribePrefix under
cds.requires.<service> in .cdsrc.json or package.json (not application.yaml).
$namespacevs${namespace}— use$namespace(no braces) in CAP YAML config; Spring interprets${namespace}as a Spring property and fails to resolve it, producing errors like:Failed to send message to topic 'topic:${namespace}/OrdersService.OrderChanged'
| Context | Syntax | Resolved by |
|---|---|---|
event-mesh.json / mta.yaml | ${namespace} | MTA deployer at deploy time |
| CAP messaging config | $namespace | CAP runtime from the EM binding |
| Spring properties | ${some.property} | Spring |
The transactional outbox ensures events aren't lost if the broker is temporarily
unavailable. Wrap a service with cds.outboxed():
const reviewsSvc = await cds.connect.to('ReviewsService')
const reviews_ = cds.outboxed(reviewsSvc) // events stored in DB, sent after commit
this.after('SAVE', Orders, async (order) => {
await reviews_.emit('OrderCreated', { orderId: order.ID })
})
The outbox persists the event in a DB table within the same transaction and forwards it with automatic retries. To bypass the outbox for an immediate emit:
await cds.unboxed(reviews_).emit('OrderCreated', { orderId: order.ID })
For
this.emit(...)inside a service handler, CAP already applies transactional semantics automatically — no need to wrap withcds.outboxed().
Persist received messages before processing for at-least-once delivery:
"cds": {
"requires": {
"messaging": {
"kind": "enterprise-messaging",
"inboxed": true
}
}
}
Route different events through different brokers using composite-messaging:
"cds": {
"requires": {
"messaging": {
"kind": "composite-messaging",
"routes": {
"ChannelA": ["**/ReviewsService/*"],
"ChannelB": ["**/sap/s4/**"]
}
},
"ChannelA": { "kind": "enterprise-messaging" },
"ChannelB": { "kind": "enterprise-messaging" }
}
}
Route patterns use glob syntax: ** matches any characters, * matches any except / and ..
Test locally against a real cloud broker:
# 1. Add the AMQP client (required for enterprise-messaging-shared)
npm add @sap/xb-msg-amqp-v100
# 2. Bind to the cloud messaging service instance
cds bind -2 <instance>:<service-key>
# 3. Run services with the hybrid profile
cds watch reviews --profile hybrid
cds watch bookstore --profile hybrid
The cds bind adds service bindings to the local environment, which is picked up by the hybrid profile.
Bindings land in .cdsrc-private.json; remove them after hybrid testing to revert to
file-based development. Verify with cds env requires --profile hybrid.
Enable CloudEvents-compliant wire format for interoperability with external systems:
"cds": {
"requires": {
"messaging": {
"format": "cloudevents"
}
}
}
CAP fills all mandatory fields (type, source, id, specversion, datacontenttype,
time) automatically. Application code does not change.
srv.before — the transaction hasn't committed; use srv.after insteadthis.on('eventName', ...) for remote events — only catches events on the current
service; use remoteService.on(...) for events from another servicecds.outboxed() for fire-and-forget writes — without it, a broker outage silently
drops events[development] profile for file-based-messaging — without it, cross-process
events are silently discarded; check ~/.cds-msg-box to verify messages are landingcds.connect.to('messaging').emit(...)) — bypasses in-process eventing,
loses service-local topic names, and breaks co-location. Prefer the conceptual APIcds watch tries to connect to
a remote URL unexpectedly, remove the leftover binding from .cdsrc-private.json*) topic rules on SAP Event Mesh — grants cross-namespace publish/subscribe
to every binding of the instance. Scope topicRules to ${namespace}/* (MTA syntax) in the
service descriptor${namespace}/* filter rejects the raw
FQN topics CAP publishes by default, silently breaking delivery. Also set
publishPrefix/subscribePrefix: "$namespace/" so topics land inside the filter${namespace} in application.yaml — Spring fails to resolve it; use $namespace (no
braces) for the CAP messaging placeholdercap-developer — general CAP Node.js patterns and project structurecap-add-remote-service — consuming external OData/S4 services in your CAP appcap-troubleshooting — diagnose why events aren't received or services fail to startWhat SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub capire/skills --plugin cap-developer10 skills in this plugin
/cap-add-remote-serviceAdd a remote service integration to an existing CAP Node.js application using the Calesi pattern. Imports external APIs (from other CAP apps or OData/S4 sources), creates consumption views, wires up delegation and data federation handlers, and validates the result with cds watch. Use when a developer wants to consume an external service in their CAP app./cap-cds-reviewReview and assess CDS data models in CAP applications for correctness, best practices, and potential issues. Produces a structured report with severity-rated findings covering naming conventions, associations/compositions, annotations, reuse patterns, service projections, and performance considerations. Use this skill whenever a developer asks to review, audit, or improve their CDS model, or proactively when you notice potential modeling issues while working on a CAP project./cap-Other plugins' skills for the same job