@abgov/adsp-sdk-mcp-server 1.23.0 → 1.24.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +50 -5
  2. package/assets/docs/services/access-service.md +10 -12
  3. package/assets/docs/services/audit-service.md +252 -133
  4. package/assets/docs/services/configuration-service.md +163 -59
  5. package/assets/docs/services/event-service.md +138 -33
  6. package/assets/docs/services/form-service.md +152 -12
  7. package/assets/docs/services/notification-service.md +2 -0
  8. package/assets/docs/services/pdf-service.md +7 -7
  9. package/assets/docs/services/project-planner-service.md +11 -11
  10. package/assets/docs/services/status-service.md +162 -6
  11. package/assets/docs/services/token-handler.md +68 -10
  12. package/assets/docs/services/value-service.md +95 -9
  13. package/assets/docs/tutorials/form-service/building-forms.md +1 -1
  14. package/assets/docs/tutorials/form-service/cheat-sheet.md +1 -1
  15. package/assets/docs/tutorials/form-service/form-app.md +1 -1
  16. package/assets/docs/tutorials/form-service/form-submissions.md +1 -1
  17. package/assets/docs/tutorials/form-service/introduction.md +1 -1
  18. package/assets/docs/tutorials/form-service/security.md +1 -1
  19. package/assets/docs/tutorials/status-service/health.md +1 -1
  20. package/assets/docs/tutorials/status-service/status.md +2 -2
  21. package/package.json +2 -1
  22. package/src/config.d.ts +11 -0
  23. package/src/config.js +47 -0
  24. package/src/config.js.map +1 -0
  25. package/src/guards.d.ts +11 -0
  26. package/src/guards.js +94 -0
  27. package/src/guards.js.map +1 -0
  28. package/src/http.d.ts +17 -1
  29. package/src/http.js +23 -17
  30. package/src/http.js.map +1 -1
  31. package/src/main.js +8 -4
  32. package/src/main.js.map +1 -1
  33. package/src/semaphore.d.ts +16 -0
  34. package/src/semaphore.js +71 -0
  35. package/src/semaphore.js.map +1 -0
  36. package/src/server.js +10 -3
  37. package/src/server.js.map +1 -1
  38. package/src/tools/liveToolLimit.d.ts +8 -0
  39. package/src/tools/liveToolLimit.js +45 -0
  40. package/src/tools/liveToolLimit.js.map +1 -0
  41. package/src/tools/registerConfigurationSchemaTool.js +3 -2
  42. package/src/tools/registerConfigurationSchemaTool.js.map +1 -1
  43. package/src/tools/registerServiceRolesTool.js +3 -2
  44. package/src/tools/registerServiceRolesTool.js.map +1 -1
  45. package/src/tools/types.d.ts +6 -2
package/README.md CHANGED
@@ -51,10 +51,18 @@ at `POST /mcp`, with a liveness check at `GET /health`.
51
51
  |---|---|---|
52
52
  | `MCP_TRANSPORT` | `stdio` | `http` to serve HTTP |
53
53
  | `PORT` | `3000` | Port to listen on |
54
- | `CORS_ORIGIN` | `*` | Value of `Access-Control-Allow-Origin` |
54
+ | `CORS_ORIGIN` | unset | Comma-separated browser origins allowed to call `/mcp`, for example `https://a.example,https://b.example`. Unset allows none; `*` allows any (not for hosted use) |
55
+ | `MCP_MAX_IN_FLIGHT` | `64` | `POST /mcp` requests handled at once per process |
56
+ | `MCP_IN_FLIGHT_WAIT_MS` | `1000` | How long a request waits for a free slot before getting `503`. Also how long a live tool waits for a free upstream slot |
57
+ | `MCP_RATE_LIMIT_PER_MINUTE` | `1200` | `POST /mcp` requests allowed per client IP per minute, per process. `0` turns the limit off |
58
+ | `MCP_LIVE_TOOL_MAX_CONCURRENT` | `8` | Live-tool calls to ADSP running at once per process, across both live tools |
59
+ | `TRUSTED_PROXY` | `uniquelocal` | Express [`trust proxy`](https://expressjs.com/en/guide/behind-proxies.html) setting, so the client IP comes from the router's `X-Forwarded-For` |
55
60
  | `OTEL_EXPORTER_OTLP_ENDPOINT` | unset | OTLP/HTTP collector base URL. When set, metrics are exported to `<endpoint>/v1/metrics` |
56
61
  | `OTEL_METRIC_EXPORT_INTERVAL` | `60000` | Metric export interval, in milliseconds |
57
62
 
63
+ An invalid value for one of the `MCP_*` numbers, or `*` mixed with origins in `CORS_ORIGIN`, stops the server at
64
+ startup with an error naming the variable.
65
+
58
66
  HTTP mode is stateless: each `POST /mcp` gets its own MCP server, the response is JSON (the server never streams),
59
67
  and nothing is kept between requests. The response carries no `Mcp-Session-Id`, so any replica can serve any request
60
68
  and an idle client never loses its session. `GET /mcp` and `DELETE /mcp` return `405` with `Allow: POST`, because
@@ -62,6 +70,46 @@ there is no stream to open and no session to delete.
62
70
 
63
71
  `SESSION_TTL_MINUTES` has been removed and is ignored: there are no sessions to expire.
64
72
 
73
+ #### Overload guards
74
+
75
+ `POST /mcp` passes these checks in order. `GET /health` skips all of them. Every rejection is a JSON-RPC error body
76
+ (`code: -32000`) and is counted in `mcp.requests.rejected`.
77
+
78
+ 1. **Origin.** A request with an `Origin` header not in `CORS_ORIGIN` gets `403` (`Origin not allowed`), as the MCP
79
+ specification requires. `Origin: null` is never allowed. A request without an `Origin` header, which is what
80
+ non-browser clients such as agent-service and the MCP SDK send, passes. `Access-Control-Allow-Origin` is sent only
81
+ for an allowed origin.
82
+ 2. **Rate limit.** Over `MCP_RATE_LIMIT_PER_MINUTE` from one client IP, a request gets `429` with `Retry-After`
83
+ (`Rate limit exceeded`).
84
+ 3. **In-flight cap.** With `MCP_MAX_IN_FLIGHT` requests already running, a request waits up to
85
+ `MCP_IN_FLIGHT_WAIT_MS` for a slot, so a short burst completes. A request still waiting after that, or arriving
86
+ when as many requests are already waiting as `MCP_MAX_IN_FLIGHT`, gets `503` with `Retry-After: 1`
87
+ (`Server busy`). Requests already running are never affected. A request is admitted before its body arrives, so
88
+ the server allows 20 s for the headers and 30 s for the whole request. A client that sends more slowly is closed
89
+ and its slot freed. These limits don't apply to how long a tool call takes.
90
+
91
+ The live tools also share `MCP_LIVE_TOOL_MAX_CONCURRENT` slots for their calls to ADSP. A live-tool call that can't
92
+ get one within `MCP_IN_FLIGHT_WAIT_MS` answers with the tool error `ADSP upstream is busy. Retry shortly.` instead of
93
+ waiting on a slow upstream. A live-tool call whose client cancels it or disconnects while it waits gives up its
94
+ place and never calls ADSP. This applies in stdio mode too.
95
+
96
+ Things to know when sizing and tuning these:
97
+
98
+ - **The limits are per process.** With N replicas, the cluster takes about N times each limit.
99
+ - **The rate limit is per client IP until authentication is added.** Every agent-service pod is then one client, and
100
+ so is any group of users behind one NAT or proxy. Connecting and calling one tool is 3 `POST`s, so the default
101
+ allows about 400 such client sessions a minute from one IP. Retune it once the deployment shows which client IPs
102
+ reach the pod.
103
+ - **Clients don't retry.** Measured locally with `MCP_MAX_IN_FLIGHT=2` and both slots held:
104
+
105
+ | Client | Over the cap for longer than `MCP_IN_FLIGHT_WAIT_MS` | Over the cap briefly (`MCP_IN_FLIGHT_WAIT_MS=3000`, slots freed after 0.5 s) |
106
+ |---|---|---|
107
+ | `@modelcontextprotocol/sdk` 1.32.1 | `connect()` throws `StreamableHTTPError` (code 503) after the wait. One request, no retry, `Retry-After` ignored | Connects and calls the tool after about 0.5 s |
108
+ | `@mastra/mcp` 1.8.1 | Logs `MCP_CLIENT_GET_TOOLS_FAILED` and `listTools()` returns no tools from this server, without throwing. One request, no retry | Lists all six tools and calls one after about 0.5 s |
109
+
110
+ So a `503` becomes a failed tool call, or an agent turn with no ADSP tools at all. Size `MCP_MAX_IN_FLIGHT` and
111
+ the replica count so it stays rare, and watch `mcp.requests.rejected`.
112
+
65
113
  #### Metrics
66
114
 
67
115
  In HTTP mode with `OTEL_EXPORTER_OTLP_ENDPOINT` set, the server exports these OpenTelemetry metrics (meter
@@ -70,7 +118,7 @@ OpenTelemetry SDK isn't loaded. Stdio mode never exports metrics.
70
118
 
71
119
  | Name | Kind | Unit | Labels | Meaning |
72
120
  |---|---|---|---|---|
73
- | `mcp.requests.in_flight` | UpDownCounter | `{request}` | none | `POST /mcp` requests being handled |
121
+ | `mcp.requests.in_flight` | UpDownCounter | `{request}` | none | `POST /mcp` requests admitted by the in-flight cap and not yet answered (waiting requests aren't counted) |
74
122
  | `mcp.requests.rejected` | Counter | `{request}` | `reason` | Requests or tool calls refused by an overload guard |
75
123
  | `mcp.request.duration` | Histogram | `s` | `mcp.method.name`, and `http.response.status_code` or `error.type=aborted` | Time to answer a `POST /mcp` request, or until the client disconnected |
76
124
  | `mcp.tool.duration` | Histogram | `s` | `mcp.tool.name`, `error.type` (absent on success) | Time to run a tool call |
@@ -94,9 +142,6 @@ Every label takes a value from a fixed set:
94
142
  request, which `adsp-cli` reports the same way.
95
143
  - `reason` on `mcp.requests.rejected`: `in_flight_cap`, `rate_limit`, `origin` or `live_tool_cap`.
96
144
 
97
- This version has no overload guards yet, so `mcp.requests.rejected` and the `busy` error type are defined but never
98
- recorded.
99
-
100
145
  ### Using `list_service_roles`
101
146
 
102
147
  That one tool needs a real ADSP environment and a logged-in session (via `@abgov/adsp-cli`, a separate package this
@@ -22,23 +22,21 @@ Security-sensitive changes in a tenant realm and failed logins are recorded in t
22
22
 
23
23
  | action | severity | resource type | recorded when |
24
24
  |:-|:-|:-|:-|
25
- | access.user.created | info | user | A user is created. |
26
- | access.user.updated | info | user | A user is updated. |
27
- | access.user.deleted | critical | user | A user is deleted. |
28
- | access.user.role-assigned | warning | user | Client roles are assigned to a user. |
29
- | access.user.role-removed | warning | user | Client roles are removed from a user. |
30
- | access.service-account.created | warning | service-account | A client is created. |
31
- | access.service-account.credential-rotated | critical | service-account | The secret of a client is regenerated. |
32
- | access.service-account.deleted | critical | service-account | A client is deleted. |
33
- | access.realm.configuration-changed | critical | realm | The realm settings, including its event settings, are updated. |
34
- | access.user.login-failed | warning | user, when known | A login attempt fails (`LOGIN_ERROR`). Recorded with `failure` status. |
25
+ | user.created | info | user | A user is created. |
26
+ | user.updated | info | user | A user is updated. |
27
+ | user.deleted | critical | user | A user is deleted. |
28
+ | user.role-assigned | warning | user | Client roles are assigned to a user. |
29
+ | user.role-removed | warning | user | Client roles are removed from a user. |
30
+ | service-account.created | warning | service-account | A client is created. |
31
+ | service-account.credential-rotated | critical | service-account | The secret of a client is regenerated. |
32
+ | service-account.deleted | critical | service-account | A client is deleted. |
33
+ | realm.configuration-changed | critical | realm | The realm settings, including its event settings, are updated. |
34
+ | user.login-failed | warning | user, when known | A login attempt fails (`LOGIN_ERROR`). Recorded with `failure` status. |
35
35
 
36
36
  Every client is recorded as a `service-account` resource, since a deleted client cannot be told apart from other clients. Resources are identified by their Keycloak ID: users are named by username and created clients by client ID when available. Realm resources use the realm ID of the event.
37
37
 
38
38
  The actor of an admin action is the administrator's Keycloak user ID. Its metadata includes `realm`, `operationType`, `resourcePath` and `actorRealm` (the administrator's realm); role changes add the `roles` names and the `clientId` (Keycloak client ID) of the roles. The actor of a failed login is the user. When Keycloak does not know the user, the actor ID is `unknown` and the attempted username, truncated to 255 characters, is the actor name. Its metadata includes `realm`, `clientId` (also truncated to 255 characters) and the Keycloak error as `reason`.
39
39
 
40
- Action names start with `access.` so they do not take generic names such as `user.created` from tenant catalogs. Audit Service rejects a tenant action whose name matches any Core action.
41
-
42
40
  Records never include the Keycloak representation itself, regenerated client secrets, IP addresses, or login details other than the username.
43
41
 
44
42
  ### Prerequisites
@@ -14,36 +14,24 @@ Use the `auditService` capability in `@abgov/adsp-service-sdk`, or call the REST
14
14
  There is no separate Audit SDK package. Action catalogs and retention settings live in
15
15
  Configuration Service; committed events live in PostgreSQL.
16
16
 
17
- ## Prepare access
17
+ ## Client roles
18
18
 
19
- Start with the [Node.js SDK service-account setup](../platform/platform-node-sdk.md#setting-up-a-service-account).
20
- Use an SDK release that includes `auditActions`, `auditService.record()` and `auditService.query()`.
21
- Keep client secrets in approved secret storage, never in source code.
22
-
23
- | Identifier | Example | Purpose |
24
- | --- | --- | --- |
25
- | Application client ID | `urn:ads:case-team:case-service` | Keycloak client and SDK `serviceId`. |
26
- | Audit namespace | `case-service` | The service component of the client ID: `serviceId.service`. |
27
- | Audit Service client | `urn:ads:platform:audit-service` | Owns the Audit roles and required token audience. |
28
- | API discovery ID | `urn:ads:platform:audit-service:v1` | Resolves the environment's Audit API URL. |
29
- | Action catalog | `audit-service:actions-case-service` | Configuration namespace and document name. |
19
+ These client roles belong to `urn:ads:platform:audit-service` and are registered by the service on startup:
30
20
 
31
- Audit namespaces must be lowercase kebab-case, at most 40 characters. A tenant writer can write
32
- only to the namespace derived from its verified client identity (`azp`). Readers can read all
33
- namespaces within their tenant. Core callers need the appropriate role and an explicit target
34
- tenant for event writes and history reads.
21
+ | Role | Permission | Included in `tenant-admin` |
22
+ | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------- |
23
+ | `audit-reader` | Read action catalogs, retention settings and audit history, and export history as CSV. | Yes, after provisioning. |
24
+ | `audit-writer` | Submit audit events. Assign to application service accounts. | No; assign explicitly. |
25
+ | `audit-admin` | Add actions to a tenant catalog, list and replay failed events, and include actor name and email in CSV exports (which also require `audit-reader`). | No; assign only when needed. |
35
26
 
36
- ### Roles and audience
27
+ `audit-admin` does not replace reader or writer permissions. Each role grants access when it is held in the
28
+ caller's tenant, or as a Core role.
37
29
 
38
- These client roles belong to `urn:ads:platform:audit-service`:
30
+ ### Grant access to an application
39
31
 
40
- | Role | Permission | Included in `tenant-admin` |
41
- | --- | --- | --- |
42
- | `audit-reader` | Read action definitions and audit history. | Yes, after provisioning. |
43
- | `audit-writer` | Submit audit events. | No; assign explicitly. |
44
- | `audit-admin` | Administer failed events and access protected actor identity. | No; assign only when needed. |
45
-
46
- `audit-admin` does not replace reader or writer permissions.
32
+ Start with the [Node.js SDK service-account setup](../platform/platform-node-sdk.md#setting-up-a-service-account).
33
+ Use an SDK release that includes `auditActions`, `auditService.record()` and `auditService.query()`.
34
+ Keep client secrets in approved secret storage, never in source code.
47
35
 
48
36
  1. In **Tenant Management App > Access > Service roles**, find Audit Service, including under
49
37
  **Core service roles**. Use **Action > +** to provision missing roles in the tenant realm.
@@ -63,6 +51,245 @@ Action registration separately requires Configuration Service access and audienc
63
51
  SDK registration path uses `configured-service`; creating and activating revisions requires an
64
52
  authorized `configuration-admin`. `audit-writer` alone cannot publish action definitions.
65
53
 
54
+ ## Tenancy
55
+
56
+ Audit data is isolated by tenant: every stored event, failed event and tenant catalog belongs to one tenant.
57
+
58
+ - **Tenant callers** always act on the tenant of their token. Setting the `tenantId` query parameter to any other
59
+ tenant responds 403; a value that is not a tenant URN (`urn:ads:platform:tenant-service:v2:/tenants/<id>`)
60
+ responds 400.
61
+ - **Core callers** select the tenant with `tenantId`. It is required to write events (400 without it), to read,
62
+ list namespaces or export history (403 without it), to add actions (400) and to administer failed events (400).
63
+ Without it, `GET /actions` and `GET /{namespace}/actions` return only Core catalogs and `GET /retention` returns
64
+ empty settings.
65
+ - **Namespace ownership.** A tenant writer can write only to the namespace that matches the service part of its
66
+ verified client ID (`azp`), for example `case-service` for `urn:ads:case-team:case-service`. Core writers may
67
+ write to any namespace. Readers can read every namespace in their tenant.
68
+ - **Platform versus tenant catalogs.** Action catalogs and retention settings are merged from Core and the tenant.
69
+ For actions, Core wins on duplicate names and tenants cannot add actions to a Core namespace. For retention, the
70
+ tenant's `retention` settings override built-in defaults, and `retention-<application>` overrides both.
71
+ - **Isolation.** An event or failed-event ID from another tenant responds 404, not 403.
72
+
73
+ ## API overview
74
+
75
+ All endpoints are under `https://audit-service.adsp.alberta.ca/audit/v1`; resolve
76
+ `urn:ads:platform:audit-service:v1` through the Directory Service to get the URL for other environments. See the
77
+ [API documentation](https://api.adsp.alberta.ca) for request and response schemas; each environment also serves
78
+ its OpenAPI document at the service root's `_links.docs.href` (`/swagger/docs/v1`).
79
+
80
+ | Endpoint | Purpose | Required role |
81
+ | :----------------------------------------- | :----------------------------------------------------- | :------------- |
82
+ | `GET /audit/v1/actions` | List all action catalogs visible to the tenant. | `audit-reader` |
83
+ | `GET /audit/v1/{namespace}/actions` | List a namespace's effective action definitions. | `audit-reader` |
84
+ | `POST /audit/v1/{namespace}/actions` | Add an action to the tenant's catalog for a namespace. | `audit-admin` |
85
+ | `GET /audit/v1/retention` | Read configured retention settings, without defaults. | `audit-reader` |
86
+ | `POST /audit/v1/{namespace}/events` | Submit a batch of 1 to 500 events. | `audit-writer` |
87
+ | `GET /audit/v1/events` | Read history across the tenant's namespaces. | `audit-reader` |
88
+ | `GET /audit/v1/{namespace}/events` | Read history in one namespace. | `audit-reader` |
89
+ | `GET /audit/v1/{namespace}/events/{id}` | Read one stored event. | `audit-reader` |
90
+ | `GET /audit/v1/namespaces` | List namespaces with stored events. | `audit-reader` |
91
+ | `GET /audit/v1/events/export` | Stream matching events as CSV. | `audit-reader` |
92
+ | `GET /audit/v1/{namespace}/events/export` | Stream one namespace's events as CSV. | `audit-reader` |
93
+ | `GET /audit/v1/failed-events` | List failed (parked) events. | `audit-admin` |
94
+ | `POST /audit/v1/failed-events/{id}/replay` | Replay an open failed event; no body required. | `audit-admin` |
95
+
96
+ Retention settings, application retention overrides and Core rate limits are configuration: change them through
97
+ the [configuration service](configuration-service.md) in the `audit-service` namespace. The audit service has no
98
+ endpoints of its own for writing them. The probes `/health`, `/health/live` and `/health/ready` are not part of
99
+ the API documentation.
100
+
101
+ ## Concepts
102
+
103
+ | Identifier | Example | Purpose |
104
+ | --------------------- | ------------------------------------ | ------------------------------------------------------------ |
105
+ | Application client ID | `urn:ads:case-team:case-service` | Keycloak client and SDK `serviceId`. |
106
+ | Audit namespace | `case-service` | The service component of the client ID: `serviceId.service`. |
107
+ | Audit Service client | `urn:ads:platform:audit-service` | Owns the Audit roles and required token audience. |
108
+ | API discovery ID | `urn:ads:platform:audit-service:v1` | Resolves the environment's Audit API URL. |
109
+ | Action catalog | `audit-service:actions-case-service` | Configuration namespace and document name. |
110
+
111
+ ### Namespace
112
+
113
+ A namespace groups the events of one application. It is the service part of the writer's client ID, and must be
114
+ lowercase kebab-case, at most 40 characters.
115
+
116
+ ### Action catalog
117
+
118
+ An action catalog lists the actions an application can record, each with a `version`, `category`, `severity` and
119
+ optional retention class, resource type, metadata schema and change-set capture. Catalogs live in the
120
+ configuration service as `audit-service:actions-<application>`, registered by Core or by a tenant. Registering an
121
+ action does not create an audit record. See [Register and publish actions](#register-and-publish-actions).
122
+
123
+ ### Audit event
124
+
125
+ An event records that an actor performed an action, with an outcome `status`, on an optional resource. The writer
126
+ supplies the `eventId` (a UUID, unique per tenant and namespace, so a resend is a duplicate rather than a second
127
+ record) and `occurredAt`. The service sets the tenant, namespace, `writtenBy`, `receivedAt`, category, severity,
128
+ retention class and expiry, and assigns the `id` used to read the event back. The API never changes a stored
129
+ event; the retention job deletes it after `retentionUntil`.
130
+
131
+ ### Retention class
132
+
133
+ Actions name a retention class rather than a period. The class's period, resolved when the event is written,
134
+ fixes the event's `retentionUntil`. See [Retention and administration](#retention-and-administration).
135
+
136
+ ### Failed event
137
+
138
+ When storage fails after an event is accepted for writing, the event is parked in failed-event storage and the
139
+ write reports it as rejected with code `storage_failed`. An `audit-admin` can list parked events and replay an open
140
+ one, which stores it as a normal event.
141
+
142
+ ## Events
143
+
144
+ The audit service doesn't send or consume domain events. Audit events are a separate concept: they are stored
145
+ records, not messages.
146
+
147
+ The service records its own sensitive operations as audit events in the `audit-service` namespace: history reads
148
+ (`events.list`, `events.list-all`, `events.read`), exports (`events.export`), failed-event listing
149
+ (`failed-events.list`) and replays (`failed-event.replay`). Read them like any other namespace.
150
+
151
+ ## Code examples
152
+
153
+ The examples use `fetch` with a bearer token for a client that has the Audit audience and the role named in each
154
+ example. Core callers also add `tenantId` with the tenant URN to each request.
155
+
156
+ ### Add an action
157
+
158
+ Requires `audit-admin`. The caller's token is forwarded to the configuration service, so configuration write
159
+ permission is required as well.
160
+
161
+ ```typescript
162
+ const response = await fetch('https://audit-service.adsp.alberta.ca/audit/v1/case-service/actions', {
163
+ method: 'POST',
164
+ headers: {
165
+ Authorization: `Bearer ${accessToken}`,
166
+ 'Content-Type': 'application/json',
167
+ },
168
+ body: JSON.stringify({
169
+ name: 'case.update',
170
+ version: 1,
171
+ category: 'administrative',
172
+ severity: 'info',
173
+ resourceType: 'case',
174
+ }),
175
+ });
176
+
177
+ // 201 with the added definition; 409 if the name already exists.
178
+ const { name, version } = await response.json();
179
+ ```
180
+
181
+ The action is added to the caller's tenant catalog (`actions-<namespace>`, created if missing). The name is
182
+ compared in full and case-insensitively with the namespace's own catalog, read directly from the configuration
183
+ service rather than the cache. Names in other namespaces, including Core ones, do not conflict. `409` is returned
184
+ when the name already exists in the namespace, or when the namespace is itself a Core namespace; `503` when the
185
+ check cannot be made, in which case nothing is written.
186
+
187
+ ### Write events
188
+
189
+ Requires `audit-writer`. Generate the `eventId` and `occurredAt` once and preserve both when retrying.
190
+
191
+ ```typescript
192
+ const response = await fetch('https://audit-service.adsp.alberta.ca/audit/v1/case-service/events', {
193
+ method: 'POST',
194
+ headers: {
195
+ Authorization: `Bearer ${accessToken}`,
196
+ 'Content-Type': 'application/json',
197
+ },
198
+ body: JSON.stringify({
199
+ events: [
200
+ {
201
+ eventId: crypto.randomUUID(),
202
+ occurredAt: new Date().toISOString(),
203
+ action: 'case.update',
204
+ actionVersion: 1,
205
+ status: 'success',
206
+ actor: { id: 'test.user@gov.ab.ca', type: 'user' },
207
+ resource: { type: 'case', id: 'case-001' },
208
+ metadata: { reason: 'Address updated' },
209
+ },
210
+ ],
211
+ }),
212
+ });
213
+
214
+ // 202: { accepted: 1, duplicates: 0, rejected: [] }
215
+ const { accepted, duplicates, rejected } = await response.json();
216
+ ```
217
+
218
+ **202 alone does not mean every event succeeded.** Check all fields:
219
+ `accepted + duplicates + rejected.length` accounts for the submitted events. Rejections include
220
+ the zero-based input `index`, `code`, `reason`, and `eventId` when available.
221
+
222
+ | Constraint | Limit |
223
+ | ----------------------- | ------------------------------------------------------------------------- |
224
+ | Events per request | 1-500 |
225
+ | Occurrence time | Previous 7 days through 5 minutes into the future |
226
+ | Metadata and change set | 16 KiB UTF-8 JSON each |
227
+ | HTTP request body | 20 MiB; enriched batches must also fit the smaller service buffer |
228
+ | Action version | Omit to use the current catalog version; an explicit mismatch is rejected |
229
+
230
+ ### Read history
231
+
232
+ Requires `audit-reader`. The writer role alone is insufficient.
233
+
234
+ ```typescript
235
+ const params = new URLSearchParams({ resourceType: 'case', resourceId: 'case-001', top: '20' });
236
+ const response = await fetch(`https://audit-service.adsp.alberta.ca/audit/v1/case-service/events?${params}`, {
237
+ headers: { Authorization: `Bearer ${accessToken}` },
238
+ });
239
+
240
+ const { results, page } = await response.json();
241
+ for (const { id, action, occurredAt, actor } of results) {
242
+ console.log(id, action, occurredAt, actor.id);
243
+ }
244
+ // Pass page.next as `after`, with the same filters, for the next page.
245
+ ```
246
+
247
+ Both REST lists and SDK `query()` return `{ results, page }`. Results are newest first.
248
+ The detail endpoint (`GET /audit/v1/{namespace}/events/{id}`) uses the returned record's **`id`**, not the
249
+ caller's `eventId`. Unlike `record()`, SDK query failures reject the promise.
250
+
251
+ REST filters include `actor`, `resourceType`, `resourceId`, `action`, `status`, `category`,
252
+ `severity`, `scope`, `correlationId`, `sessionId`, `occurredFrom` and `occurredTo`. Filters combine
253
+ with AND; time bounds are inclusive. Free-text search is not supported. The SDK's typed criteria
254
+ cover a subset; see [SDK types](https://github.com/GovAlta/adsp-monorepo/blob/main/libs/adsp-service-sdk/src/audit/types.ts).
255
+ SDK query options also accept another readable `namespace` or an authorized user `token`.
256
+
257
+ ### Export history as CSV
258
+
259
+ Requires `audit-reader`.
260
+
261
+ ```typescript
262
+ const params = new URLSearchParams({ occurredFrom: '2026-11-01T00:00:00Z' });
263
+ const response = await fetch(`https://audit-service.adsp.alberta.ca/audit/v1/events/export?${params}`, {
264
+ headers: { Authorization: `Bearer ${accessToken}` },
265
+ });
266
+
267
+ const csv = await response.text();
268
+ ```
269
+
270
+ CSV exports use the same filters but ignore `top` and `after`; they are not capped to a page.
271
+ Actor name/email columns require `audit-admin` in addition to reader access. An interrupted
272
+ export may be incomplete. Removing an action definition does not delete or hide its stored history.
273
+
274
+ ### Replay a failed event
275
+
276
+ Requires `audit-admin`. List the failed events, then replay an open one by its `id`.
277
+
278
+ ```typescript
279
+ const headers = { Authorization: `Bearer ${accessToken}` };
280
+ const list = await fetch('https://audit-service.adsp.alberta.ca/audit/v1/failed-events?top=20', { headers });
281
+ const { results } = await list.json();
282
+
283
+ const open = results.find(({ status }) => status === 'open');
284
+ const replay = await fetch(`https://audit-service.adsp.alberta.ca/audit/v1/failed-events/${open.id}/replay`, {
285
+ method: 'POST',
286
+ headers,
287
+ });
288
+
289
+ // 200 with status 'replayed' and replayed_as set to the stored event's id.
290
+ const { status, replayed_as } = await replay.json();
291
+ ```
292
+
66
293
  ## Integrate with the Node.js SDK
67
294
 
68
295
  The examples run in asynchronous application code. `config` is validated deployment configuration
@@ -375,114 +602,6 @@ query a controlled event. Do not use a fixed sleep as a readiness check. Configu
375
602
  failures can appear as missing catalogs or unknown actions; a 404 alone does not prove that
376
603
  registration is absent.
377
604
 
378
- ## Use the REST API
379
-
380
- Resolve `urn:ads:platform:audit-service:v1` through the target environment's Directory Service.
381
- The SDK handles discovery automatically. For full schemas, follow the service root's
382
- `_links.docs.href` to its OpenAPI document (`/swagger/docs/v1`).
383
-
384
- ### Adding an action
385
-
386
- ```http
387
- POST /audit/v1/{namespace}/actions
388
- Authorization: Bearer <token with audit-admin>
389
- Content-Type: application/json
390
-
391
- { "name": "case.update", "version": 1, "category": "runtime", "severity": "info", "retentionClass": "standard" }
392
- ```
393
-
394
- Adds the action to the caller's tenant catalog (`actions-<namespace>`, created if missing). The caller's token is
395
- forwarded to the configuration service, so configuration write permission is required as well. The name is compared
396
- in full and case-insensitively with the namespace's own catalog and every Core catalog, read directly from the
397
- configuration service rather than the cache. `409` is returned when the name already exists in either, or when the
398
- namespace is itself a Core namespace; `503` when the check cannot be made, in which case nothing is written.
399
-
400
- ### Write an event
401
-
402
- Use a bearer token with the Audit audience and `audit-writer`. Replace the placeholders with
403
- a UUID and the current ISO 8601 UTC timestamp; preserve both when retrying.
404
- Core callers must also supply the URL-encoded tenant URN as the `tenantId` query parameter.
405
-
406
- ```http
407
- POST /audit/v1/case-service/events
408
- Authorization: Bearer {{ACCESS_TOKEN}}
409
- Content-Type: application/json
410
-
411
- {
412
- "events": [
413
- {
414
- "eventId": "{{EVENT_UUID}}",
415
- "occurredAt": "{{CURRENT_UTC_TIMESTAMP}}",
416
- "action": "case.update",
417
- "actionVersion": 1,
418
- "status": "success",
419
- "actor": { "id": "onboarding-test-user", "type": "user" },
420
- "resource": { "type": "case", "id": "onboarding-case-001" },
421
- "metadata": { "reason": "Onboarding verification" }
422
- }
423
- ]
424
- }
425
- ```
426
-
427
- A confirmed single-event write returns HTTP 202:
428
-
429
- ```json
430
- { "accepted": 1, "duplicates": 0, "rejected": [] }
431
- ```
432
-
433
- **202 alone does not mean every event succeeded.** Check all fields:
434
- `accepted + duplicates + rejected.length` accounts for the submitted events. Rejections include
435
- the zero-based input `index`, `code`, `reason`, and `eventId` when available.
436
-
437
- | Constraint | Limit |
438
- | --- | --- |
439
- | Events per request | 1-500 |
440
- | Occurrence time | Previous 7 days through 5 minutes into the future |
441
- | Metadata and change set | 16 KiB UTF-8 JSON each |
442
- | HTTP request body | 20 MiB; enriched batches must also fit the smaller service buffer |
443
- | Action version | Omit to use the current catalog version; an explicit mismatch is rejected |
444
-
445
- ### Read and export
446
-
447
- History reads require `audit-reader` and tenant context. The writer role alone is insufficient.
448
-
449
- ```http
450
- GET /audit/v1/case-service/events?resourceType=case&resourceId=onboarding-case-001&top=20
451
- Authorization: Bearer {{ACCESS_TOKEN}}
452
- ```
453
-
454
- Both REST lists and SDK `query()` return `{ results, page }`. Pass `page.next` as `after` for the
455
- next page, keeping the same filters; URL-encode it for REST. Results are newest first.
456
- The detail endpoint uses the returned record's **`id`**, not the caller's `eventId`.
457
- Unlike `record()`, SDK query failures reject the promise.
458
-
459
- REST filters include `actor`, `resourceType`, `resourceId`, `action`, `status`, `category`,
460
- `severity`, `scope`, `correlationId`, `sessionId`, `occurredFrom` and `occurredTo`. Filters combine
461
- with AND; time bounds are inclusive. Free-text search is not supported. The SDK's typed criteria
462
- cover a subset; see [SDK types](https://github.com/GovAlta/adsp-monorepo/blob/main/libs/adsp-service-sdk/src/audit/types.ts).
463
- SDK query options also accept another readable `namespace` or an authorized user `token`.
464
-
465
- All paths below are relative to `/audit/v1`.
466
-
467
- | Method and path | Role | Purpose |
468
- | --- | --- | --- |
469
- | `GET /{namespace}/actions` | `audit-reader` | Effective action definitions. |
470
- | `GET /actions` | `audit-reader` | All effective application catalogs. |
471
- | `GET /retention` | `audit-reader` | Configured retention settings, excluding implicit defaults. |
472
- | `POST /{namespace}/events` | `audit-writer` | Submit a batch of events. |
473
- | `GET /events` | `audit-reader` | History across the tenant's namespaces. |
474
- | `GET /{namespace}/events` | `audit-reader` | History in one namespace. |
475
- | `GET /{namespace}/events/{id}` | `audit-reader` | One stored record. |
476
- | `GET /namespaces` | `audit-reader` | Namespaces with stored events. |
477
- | `GET /events/export` | `audit-reader` | Stream matching events as CSV. |
478
- | `GET /{namespace}/events/export` | `audit-reader` | Stream one namespace's events as CSV. |
479
- | `GET /failed-events` | `audit-admin` | List failed events. |
480
- | `POST /failed-events/{id}/replay` | `audit-admin` | Replay an open failed event; no body required. |
481
-
482
- CSV exports use the same filters but ignore `top` and `after`; they are not capped to a page.
483
- Actor name/email columns require `audit-admin` in addition to reader access. An interrupted
484
- export may be incomplete. Removing an action definition does not delete or hide its stored history.
485
-
486
605
  ## Retention and administration
487
606
 
488
607
  Actions reference a retention class, not a number of days. Built-in defaults are **90 days**