@abgov/adsp-sdk-mcp-server 1.22.1 → 1.24.0

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 (38) hide show
  1. package/README.md +83 -1
  2. package/assets/docs/services/agent-service.md +113 -27
  3. package/assets/docs/services/file-service.md +215 -116
  4. package/assets/docs/services/pdf-service.md +20 -0
  5. package/assets/docs/tutorials/file-service/file-types.md +2 -4
  6. package/assets/docs/tutorials/file-service/security.md +1 -1
  7. package/assets/docs/tutorials/file-service/working-with.md +5 -5
  8. package/package.json +6 -1
  9. package/src/config.d.ts +11 -0
  10. package/src/config.js +47 -0
  11. package/src/config.js.map +1 -0
  12. package/src/guards.d.ts +11 -0
  13. package/src/guards.js +94 -0
  14. package/src/guards.js.map +1 -0
  15. package/src/http.d.ts +17 -1
  16. package/src/http.js +39 -15
  17. package/src/http.js.map +1 -1
  18. package/src/main.js +13 -5
  19. package/src/main.js.map +1 -1
  20. package/src/metrics.d.ts +22 -0
  21. package/src/metrics.js +173 -0
  22. package/src/metrics.js.map +1 -0
  23. package/src/semaphore.d.ts +16 -0
  24. package/src/semaphore.js +71 -0
  25. package/src/semaphore.js.map +1 -0
  26. package/src/server.js +28 -3
  27. package/src/server.js.map +1 -1
  28. package/src/tools/liveToolLimit.d.ts +8 -0
  29. package/src/tools/liveToolLimit.js +45 -0
  30. package/src/tools/liveToolLimit.js.map +1 -0
  31. package/src/tools/registerConfigurationSchemaTool.js +7 -2
  32. package/src/tools/registerConfigurationSchemaTool.js.map +1 -1
  33. package/src/tools/registerServiceRolesTool.js +7 -2
  34. package/src/tools/registerServiceRolesTool.js.map +1 -1
  35. package/src/tools/types.d.ts +6 -2
  36. package/src/tools/upstreamErrors.d.ts +2 -0
  37. package/src/tools/upstreamErrors.js +18 -0
  38. package/src/tools/upstreamErrors.js.map +1 -0
@@ -5,38 +5,112 @@ parent: Services
5
5
  ---
6
6
 
7
7
  # File service
8
+
8
9
  File service provides the ability to upload and download files. Applications can upload files via multipart/form-data requests with the file and related metadata, then later allow users to access metadata of or download the file.
9
10
 
10
11
  The file service uses anti-virus services to scan uploaded files. Download of files that have not been scanned requires an explicit `unsafe=true` parameter.
11
12
 
12
-
13
13
  ## Client roles
14
+
14
15
  client `urn:ads:platform:file-service`
15
16
 
16
- | name | description |
17
- |:-|:-|
18
- | file-service-admin | Administrator role for the file service. This role grants read and write access across all files. |
17
+ | name | description |
18
+ | :----------------- | :------------------------------------------------------------------------------------------------------------------- |
19
+ | file-service-admin | Administrator role for the file service. This role grants read, upload and delete access to all files of the tenant. |
20
+
21
+ The role is included in the tenant admin composite role. Access to files is otherwise controlled by the `readRoles`, `updateRoles` and `anonymousRead` settings of each [file type](#file-type).
22
+
23
+ ## Tenancy
24
+
25
+ - **Which tenant is used.** Tenant users and tenant service accounts act on the tenant of their token. Core (platform) users act on the tenant given by the `tenantId` query parameter. An invalid `tenantId` responds 400.
26
+ - **File types.** The file types of a tenant are its own types combined with the platform file types registered by platform services (for example `generated-pdf` from the [PDF service](pdf-service.md)). A platform type replaces a tenant type with the same ID. Files uploaded to a platform type belong to the tenant of the request.
27
+ - **Listing and uploading files.** `GET /file/v1/files` requires a tenant context, so core users must set `tenantId` or the request responds 400. Uploads to a platform type without a tenant context also respond 400. Core users who copy a file to another type set `tenantId` so the type is found in that tenant.
28
+ - **Single file requests.** `GET`, `DELETE` and `POST /file/v1/files/{fileId}` and the download find the file by ID across tenants, and check access against the tenant of the file. A file of another tenant responds 403 (401 for `DELETE /file/v1/files`) rather than 404, unless its type allows anonymous read.
29
+ - **Role scope.** `readRoles`, `updateRoles` and `file-service-admin` are checked in the tenant of the file. Core users and platform service accounts holding a role in the core realm are also allowed, for any tenant. Roles configured on tenant file types are only created in tenant realms, so platform service accounts need roles from the core realm (see the description of the file type schema in the [API documentation](https://api.adsp.alberta.ca)).
30
+ - **Uploader access.** The user who uploaded a file can always read it. Deleting it also requires one of the type's `updateRoles`.
31
+
32
+ ## API overview
19
33
 
20
- File access is controlled by configuration of `readRoles` and `updateRoles` on each file type.
34
+ All endpoints are under `https://file-service.adsp.alberta.ca/file/v1`. See the [API documentation](https://api.adsp.alberta.ca) for request and response schemas.
35
+
36
+ | Endpoint | Purpose | Required role |
37
+ | :------------------------------------- | :--------------------------------------- | :------------------------------------------------------------------------------------------------------- |
38
+ | `GET /file/v1/types` | List the file types the user can access. | Any authenticated user; types are filtered by role |
39
+ | `GET /file/v1/types/{typeId}` | Get a file type. | A `readRoles` or `updateRoles` role of the type, or `file-service-admin`, or the type is `anonymousRead` |
40
+ | `POST /file/v1/files` | Upload a file (multipart/form-data). | An `updateRoles` role of the type, or `file-service-admin` |
41
+ | `GET /file/v1/files` | Find files of the tenant, paged. | Any authenticated user; files are filtered by access |
42
+ | `DELETE /file/v1/files?files=...` | Mark several files for deletion. | `file-service-admin`, or the uploader with an `updateRoles` role |
43
+ | `GET /file/v1/files/{fileId}` | Get the metadata of a file. | Uploader, a `readRoles` role, `file-service-admin`, or anonymous for `anonymousRead` types |
44
+ | `POST /file/v1/files/{fileId}` | Run a file operation (`copy`). | Read access to the file and an `updateRoles` role of the destination type, or `file-service-admin` |
45
+ | `DELETE /file/v1/files/{fileId}` | Mark a file for deletion. | `file-service-admin`, or the uploader with an `updateRoles` role |
46
+ | `GET /file/v1/files/{fileId}/download` | Download the file content. | Same as getting the metadata |
47
+
48
+ File types are configured through the [configuration service](configuration-service.md); file service has no endpoints of its own to change them.
21
49
 
22
50
  ## Concepts
51
+
23
52
  ### File type
24
- File type represents a category of files with specific access roles. For example, a 'Supporting Documents' file type may allow `intake-application` role to upload files and `assessor` role to download the files. File types are configured in the [configuration service](configuration-service.md) under the `platform:file-service` namespace and name.
53
+
54
+ File type represents a category of files with specific access roles. For example, a 'Supporting Documents' file type may allow `applicant` role to upload files and `assessor` role to download the files. File types are configured in the [configuration service](configuration-service.md) under the `platform:file-service` namespace and name.
55
+
56
+ | setting | effect |
57
+ | :----------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
58
+ | `readRoles` | Users with one of these roles can read the metadata of and download any file of the type. |
59
+ | `updateRoles` | Users with one of these roles can upload files of the type, read the type, and delete files they uploaded. |
60
+ | `anonymousRead` | Anyone, including requests without a bearer token, can read the metadata of and download files of the type. Embedded downloads of these files are sent with `Cache-Control: public`. |
61
+ | `allowedFileTypes` | File extensions accepted for upload, with the leading period (for example `.pdf`). The extension is detected from the content when possible, otherwise taken from the filename. Empty accepts any file. |
62
+ | `securityClassification` | Data classification of files of the type: `public`, `protected a` (default), `protected b` or `protected c`. It is copied to each file. |
63
+ | `rules.retention` | When `active`, a daily job deletes files of the type that have not been accessed for `deleteInDays` days. |
64
+
65
+ Users with `file-service-admin` can read and delete every file of the tenant, and upload files of any type.
25
66
 
26
67
  ### File
27
- A file represents an uploaded file and consists of a minimal metadata record and the actual file that was uploaded. File service provides minimal metadata and does not support extensible metadata; keep additional values in a domain record and reference it using `recordId`.
68
+
69
+ A file represents an uploaded file and consists of a minimal metadata record and the actual file that was uploaded. File service provides minimal metadata and does not support extensible metadata; keep additional values in a domain record and reference it using `recordId`. Each file has a URN, `urn:ads:platform:file-service:v1:/files/{fileId}`, that the [directory service](directory-service.md) can resolve to its URL.
70
+
71
+ Deleting a file marks it for deletion; the file content and record are removed afterwards by a job. Files marked for deletion are not listed and cannot be downloaded.
72
+
73
+ ### Upload
74
+
75
+ Files are uploaded with a `multipart/form-data` request with one file part named `file`, up to 3 GB, and at most 10 other fields. The metadata fields `type` (required), `recordId`, `filename` and `mimeType` must come before the file part, because the file is streamed to storage as it is received. They can also be sent as query parameters. The MIME type is detected from the content when possible, and `mimeType` is used otherwise.
76
+
77
+ ### Virus scanning and digest
78
+
79
+ After a file is uploaded or copied, file service scans it for malware and computes a SHA-256 digest of its content (`digest`, for example `sha256-...`). Until the scan completes, `scanned` is `false` and a download responds 400 unless `unsafe=true` is set. Infected files cannot be downloaded.
80
+
81
+ ### Download
82
+
83
+ A download responds with the file content and these headers:
84
+
85
+ - `Content-Type` is the MIME type of the file, or `application/octet-stream` if unknown. SVG images have `;base64` appended.
86
+ - `Content-Disposition` is `attachment` by default, or `inline` with `embed=true`, and includes the filename.
87
+ - `Cache-Control` is `no-store`, except `public` for embedded files of `anonymousRead` types.
88
+ - A single byte range in the `Range` header responds 206 with `Content-Range`. Multiple ranges and ranges outside the file respond 400.
89
+
90
+ ## Events
91
+
92
+ File service sends these domain events in the `file-service` namespace. Each payload includes the `file` metadata, and the `correlationId` is the file's `recordId`, or its URN if it has none.
93
+
94
+ | event | sent when | payload |
95
+ | :-------------- | :------------------------------------------------------------- | :------------------- |
96
+ | `file-uploaded` | A file is uploaded or copied. | `file`, `uploadedBy` |
97
+ | `file-deleted` | A file is marked for deletion, by a user or the retention job. | `file`, `deletedBy` |
98
+ | `file-scanned` | The virus scan of a file completes. | `file`, `infected` |
99
+
100
+ File service consumes its own `file-uploaded` and `file-deleted` events from a work queue to run the virus scan and digest, and to remove deleted files from storage. It also consumes configuration update events to refresh cached file types. The [cache service](cache-service.md) and [directory service](directory-service.md) use `file-deleted` to drop cached downloads and the file's resource entry.
28
101
 
29
102
  ## Audit actions
103
+
30
104
  File service records audit events in the `file-service` namespace of the [audit service](audit-service.md). Records are written to the tenant of the file, with the file as the resource (`{ type: 'file', id: <file ID>, name: <filename> }`), the `recordId` of the file as the correlation ID, and the `filename`, file `type`, `recordId` and `size` in the metadata. All actions are version 1.
31
105
 
32
- | action | category | severity | retention class | recorded when |
33
- |:-|:-|:-|:-|:-|
34
- | file.uploaded | data-access | info | compliance | A file is uploaded, even while its virus scan is pending, or a file is copied (with `sourceFileId` in the metadata). |
35
- | file.downloaded | data-access | info | compliance | A scanned file is downloaded. A partial (range) download includes the `range` in the metadata. |
36
- | file.unsafe-downloaded | data-access | warning | security | A file is downloaded with `unsafe=true` before its virus scan is completed. |
37
- | file.deleted | administrative | warning | compliance | A file is deleted through the API, or by the retention job (with `reason: 'retention'` and `retentionDays` in the metadata). |
38
- | file.scan-completed | runtime | info | standard | The virus scan result of a file is recorded, with `scanResult` of `clean` or `threat`. |
39
- | file.scan-threat-found | security | critical | security | The virus scan detects a threat. Threat names are included as `threats` when the anti-virus provider reports them. |
106
+ | action | category | severity | retention class | recorded when |
107
+ | :--------------------- | :------------- | :------- | :-------------- | :--------------------------------------------------------------------------------------------------------------------------- |
108
+ | file.uploaded | data-access | info | compliance | A file is uploaded, even while its virus scan is pending, or a file is copied (with `sourceFileId` in the metadata). |
109
+ | file.downloaded | data-access | info | compliance | A scanned file is downloaded. A partial (range) download includes the `range` in the metadata. |
110
+ | file.unsafe-downloaded | data-access | warning | security | A file is downloaded with `unsafe=true` before its virus scan is completed. |
111
+ | file.deleted | administrative | warning | compliance | A file is deleted through the API, or by the retention job (with `reason: 'retention'` and `retentionDays` in the metadata). |
112
+ | file.scan-completed | runtime | info | standard | The virus scan result of a file is recorded, with `scanResult` of `clean` or `threat`. |
113
+ | file.scan-threat-found | security | critical | security | The virus scan detects a threat. Threat names are included as `threats` when the anti-virus provider reports them. |
40
114
 
41
115
  Downloads of files of an `anonymousRead` type by users who are not signed in are recorded with the actor `{ id: 'anonymous', type: 'user' }`. Scan results and retention deletes are recorded with the system actor `file-service-job`. Scan results are recorded when the asynchronous scan completes, not when the file is uploaded.
42
116
 
@@ -47,137 +121,162 @@ Downloads can be high volume, so file service sends audit events in batches of u
47
121
  Audit recording is on by default. Set the environment variable `FILE_AUDIT_ENABLED=false` on file service to turn it off, or `true` to turn it on regardless of the SDK `AUDIT_ENABLED` variable, which applies when `FILE_AUDIT_ENABLED` is not set. The action catalog is still registered while recording is off, so turning it back on needs only a restart.
48
122
 
49
123
  ## Code examples
124
+
125
+ The examples use this base URL:
126
+
127
+ ```typescript
128
+ const fileServiceUrl = 'https://file-service.adsp.alberta.ca';
129
+ ```
130
+
50
131
  ### Configure a file type
132
+
51
133
  File types are configured using the [configuration service](configuration-service.md). Note that new configuration may take up to 15 mins to apply.
52
134
 
53
135
  ```typescript
54
- const configurationServiceUrl = 'https://configuration-service.adsp.alberta.ca';
55
- const request = {
56
- operation: 'UPDATE',
57
- update: {
58
- 'supporting-document': {
59
- id: 'supporting-document',
60
- name: 'Support Document',
61
- anonymousRead: false,
62
- readRoles: ['assessor'],
63
- updateRoles: ['applicant'],
64
- }
65
- }
66
- }
67
-
68
- await fetch(
69
- `${configurationServiceUrl}/configuration/v2/configuration/platform/file-service`,
70
- {
71
- method: 'PATCH',
72
- headers: {
73
- 'Authorization': `Bearer ${accessToken}`,
74
- 'Content-Type': 'application/json'
75
- },
76
- body: JSON.stringify(request),
77
- }
78
- );
136
+ const configurationServiceUrl = 'https://configuration-service.adsp.alberta.ca';
137
+ const request = {
138
+ operation: 'UPDATE',
139
+ update: {
140
+ 'supporting-documents': {
141
+ id: 'supporting-documents',
142
+ name: 'Supporting Documents',
143
+ anonymousRead: false,
144
+ readRoles: ['assessor'],
145
+ updateRoles: ['applicant'],
146
+ allowedFileTypes: ['.pdf', '.jpg'],
147
+ rules: { retention: { active: true, deleteInDays: 365 } },
148
+ },
149
+ },
150
+ };
151
+
152
+ await fetch(`${configurationServiceUrl}/configuration/v2/configuration/platform/file-service`, {
153
+ method: 'PATCH',
154
+ headers: {
155
+ Authorization: `Bearer ${accessToken}`,
156
+ 'Content-Type': 'application/json',
157
+ },
158
+ body: JSON.stringify(request),
159
+ });
79
160
  ```
80
161
 
81
162
  ### Upload a file
163
+
82
164
  ```typescript
83
- // Note that the file needs to be last.
84
- const formData = new FormData();
85
- formData.append('type', 'supporting-docs');
86
- // Use filename to override the original name of the file.
87
- formData.append('filename', 'proof-of-income.pdf');
88
- // Use recordId to reference the associated record.
89
- formData.append('recordId', '8bcbc6b1-600a-40c5-99c8-d02734f97ca5');
90
- formData.append('file', selectedFile);
91
-
92
- await fetch(
93
- 'https://file-service.adsp.alberta.ca/file/v1/files',
94
- {
95
- method: 'POST',
96
- headers: { Authorization: `Bearer ${accessToken}` },
97
- body: formData,
98
- }
99
- );
165
+ // The metadata fields must come before the file.
166
+ const formData = new FormData();
167
+ formData.append('type', 'supporting-documents');
168
+ // Use filename to override the original name of the file.
169
+ formData.append('filename', 'proof-of-income.pdf');
170
+ // Use recordId to reference the associated record.
171
+ formData.append('recordId', '8bcbc6b1-600a-40c5-99c8-d02734f97ca5');
172
+ formData.append('file', selectedFile);
173
+
174
+ const response = await fetch(`${fileServiceUrl}/file/v1/files`, {
175
+ method: 'POST',
176
+ headers: { Authorization: `Bearer ${accessToken}` },
177
+ body: formData,
178
+ });
179
+
180
+ // scanned is false until the virus scan completes.
181
+ const { id, urn, scanned } = await response.json();
100
182
  ```
101
183
 
102
184
  Note that file service requires an authenticated user for uploads. In order to allow public upload, proxy the request and add service account access token in the server.
103
185
 
104
186
  ```typescript
105
- app.use(
106
- '/api/upload',
107
- proxy('https://file-service.adsp.alberta.ca', {
108
- proxyReqPathResolver: function() {
109
- return '/file/v1/files';
110
- },
111
- proxyReqOptDecorator: async (proxyReq) => {
112
- const accessToken = await getServiceAccountToken();
113
- proxyReq.headers['Authorization'] = `Bearer ${accessToken}`;
114
- return proxyReq;
115
- },
116
- })
117
- );
187
+ app.use(
188
+ '/api/upload',
189
+ proxy('https://file-service.adsp.alberta.ca', {
190
+ proxyReqPathResolver: function () {
191
+ return '/file/v1/files';
192
+ },
193
+ proxyReqOptDecorator: async (proxyReq) => {
194
+ const accessToken = await getServiceAccountToken();
195
+ proxyReq.headers['Authorization'] = `Bearer ${accessToken}`;
196
+ return proxyReq;
197
+ },
198
+ }),
199
+ );
118
200
  ```
119
201
 
120
202
  ### Find files
203
+
121
204
  ```typescript
122
- const top = 10;
123
- const criteria = { typeEquals: 'supporting-docs' };
124
- await fetch(
125
- `${fileServiceUrl}/file/v1/files?top=${top}&criteria=${JSON.stringify(criteria)}`,
126
- {
127
- method: 'GET',
128
- headers: { Authorization: `Bearer ${accessToken}` },
129
- }
130
- );
205
+ const top = 10;
206
+ const criteria = { typeEquals: 'supporting-documents', recordIdEquals: '8bcbc6b1-600a-40c5-99c8-d02734f97ca5' };
207
+ const response = await fetch(
208
+ `${fileServiceUrl}/file/v1/files?top=${top}&criteria=${encodeURIComponent(JSON.stringify(criteria))}`,
209
+ {
210
+ method: 'GET',
211
+ headers: { Authorization: `Bearer ${accessToken}` },
212
+ },
213
+ );
214
+
215
+ // Pass page.next as the after parameter to get the next page.
216
+ const { results, page } = await response.json();
131
217
  ```
132
218
 
133
219
  ### Get file metadata
220
+
134
221
  ```typescript
135
- const response = await fetch(
136
- `${fileServiceUrl}/file/v1/files/84401bb2-1f49-42ef-92b0-649e6c0e7462`,
137
- {
138
- method: 'GET',
139
- headers: { Authorization: `Bearer ${accessToken}` },
140
- }
141
- );
142
-
143
- const {
144
- typeName,
145
- filename,
146
- size,
147
- recordId,
148
- } = await response.json();
222
+ const response = await fetch(`${fileServiceUrl}/file/v1/files/84401bb2-1f49-42ef-92b0-649e6c0e7462`, {
223
+ method: 'GET',
224
+ headers: { Authorization: `Bearer ${accessToken}` },
225
+ });
226
+
227
+ const { typeName, filename, size, recordId, scanned, infected } = await response.json();
149
228
  ```
150
229
 
151
230
  ### Download a file
231
+
232
+ ```typescript
233
+ const response = await fetch(`${fileServiceUrl}/file/v1/files/a217db73-0c29-4fbd-b576-49d049f855a6/download`, {
234
+ method: 'GET',
235
+ headers: { Authorization: `Bearer ${accessToken}` },
236
+ });
237
+
238
+ const contentType = response.headers.get('Content-Type');
239
+ const content = await response.blob();
240
+ ```
241
+
242
+ Use `unsafe=true` to download a file before it has been virus scanned, and `embed=true` to display it in the browser instead of saving it.
243
+
152
244
  ```typescript
153
- await fetch(
154
- `${fileServiceUrl}/file/v1/files/a217db73-0c29-4fbd-b576-49d049f855a6/download`,
155
- {
156
- method: 'GET',
157
- headers: { Authorization: `Bearer ${accessToken}` },
158
- }
159
- );
245
+ await fetch(`${fileServiceUrl}/file/v1/files/a217db73-0c29-4fbd-b576-49d049f855a6/download?unsafe=true`, {
246
+ method: 'GET',
247
+ headers: { Authorization: `Bearer ${accessToken}` },
248
+ });
160
249
  ```
161
250
 
162
- Use `unsafe=true` to download a file before it has been virus scanned.
251
+ ### Copy a file
163
252
 
164
253
  ```typescript
165
- await fetch(
166
- `${fileServiceUrl}/file/v1/files/a217db73-0c29-4fbd-b576-49d049f855a6/download?unsafe=true`,
167
- {
168
- method: 'GET',
169
- headers: { Authorization: `Bearer ${accessToken}` },
170
- }
171
- );
254
+ const response = await fetch(`${fileServiceUrl}/file/v1/files/a217db73-0c29-4fbd-b576-49d049f855a6`, {
255
+ method: 'POST',
256
+ headers: {
257
+ Authorization: `Bearer ${accessToken}`,
258
+ 'Content-Type': 'application/json',
259
+ },
260
+ body: JSON.stringify({ operation: 'copy', type: 'supporting-documents', filename: 'proof-of-income-copy.pdf' }),
261
+ });
262
+
263
+ const { id } = await response.json();
172
264
  ```
173
265
 
174
- ### Delete a file
266
+ ### Delete files
267
+
175
268
  ```typescript
176
- await fetch(
177
- `${fileServiceUrl}/file/v1/files/a217db73-0c29-4fbd-b576-49d049f855a6`,
178
- {
179
- method: 'DELETE',
180
- headers: { Authorization: `Bearer ${accessToken}` },
181
- }
182
- );
269
+ await fetch(`${fileServiceUrl}/file/v1/files/a217db73-0c29-4fbd-b576-49d049f855a6`, {
270
+ method: 'DELETE',
271
+ headers: { Authorization: `Bearer ${accessToken}` },
272
+ });
273
+
274
+ // Delete several files in one request.
275
+ const fileIds = ['a217db73-0c29-4fbd-b576-49d049f855a6', '84401bb2-1f49-42ef-92b0-649e6c0e7462'];
276
+ const response = await fetch(`${fileServiceUrl}/file/v1/files?files=${fileIds.join(',')}`, {
277
+ method: 'DELETE',
278
+ headers: { Authorization: `Bearer ${accessToken}` },
279
+ });
280
+
281
+ const { deleted, results } = await response.json();
183
282
  ```
@@ -75,6 +75,26 @@ The PDF service sends the following domain events under the `pdf-service` namesp
75
75
 
76
76
  These events are available on the [push service](push-service.md) stream `pdf-generation-updates`, for subscribers with the pdf-generator role. The PDF service doesn't consume events from other services.
77
77
 
78
+ ## Audit actions
79
+
80
+ PDF service records audit events in the `pdf-service` namespace of the [audit service](audit-service.md). Action names start with `pdf.` so they do not take generic names such as `job.created` from tenant catalogs. Records are written to the tenant of the job or template. All actions are version 1, and their retention class is derived from the category.
81
+
82
+ | action | category | severity | retention class | recorded when |
83
+ |:-|:-|:-|:-|:-|
84
+ | pdf.job.created | runtime | info | standard | A PDF generation job is queued through `POST /pdf/v1/jobs`. |
85
+ | pdf.job.generated | runtime | info | standard | A generation job finishes: status `success` when the PDF is stored in file service, with the resulting `fileId` in the metadata, or status `failure` when the job fails, with the `error` in the metadata. |
86
+ | pdf.template.created | administrative | info | compliance | A template is created through `POST /pdf/v1/templates`. |
87
+ | pdf.template.updated | administrative | warning | compliance | A template is updated through `PATCH /pdf/v1/templates/{templateId}`, with the names of the changed fields as `changedFields` in the metadata. |
88
+ | pdf.template.deleted | administrative | warning | compliance | A template is deleted through `DELETE /pdf/v1/templates/{templateId}`. |
89
+
90
+ Job records have the job as the resource (`{ type: 'pdf-job', id: <job ID>, name: <filename> }`), the `recordId` of the generated file as the correlation ID, and the `templateId`, `filename`, `fileType` and `recordId` in the metadata. Since file service uses the same `recordId` as the correlation ID, the `fileId` and correlation ID link a job to the `file.uploaded` record of the generated file. `pdf.job.generated` is recorded by the job worker after generation completes, with the requester of the job as the actor; a failure is recorded only when the job is marked failed, not on an attempt that will be retried. Failures are found by filtering on `status=failure`.
91
+
92
+ Template records have the template as the resource (`{ type: 'pdf-template', id: <template ID>, name: <name> }`) and the `templateId` and `name` in the metadata. Template changes made directly in the [configuration service](configuration-service.md) rather than through the PDF service API are recorded only in the `configuration-service` namespace; changes through the PDF service API are recorded in both. Reads of templates and job status are not recorded.
93
+
94
+ Audit failures are logged by the SDK and do not fail the PDF operation. The PDF service account requires the `audit-writer` role of `urn:ads:platform:audit-service`.
95
+
96
+ Audit recording is on by default. Set the environment variable `PDF_AUDIT_ENABLED=false` on PDF service to turn it off, or `true` to turn it on regardless of the SDK `AUDIT_ENABLED` variable, which applies when `PDF_AUDIT_ENABLED` is not set. The action catalog is still registered while recording is off, so turning it back on needs only a restart.
97
+
78
98
  ## Code examples
79
99
 
80
100
  ### Configure a template
@@ -8,7 +8,7 @@ grand_parent: Tutorials
8
8
 
9
9
  ## File Type collections
10
10
 
11
- A **File type** is a _named collection_ of files. You can assign certain file-properties to a collection, such as access permissions, and when files are added to it they will inherit them. So, for example, you can create a new file type named _public_, and assign it a _read-only_ file-property. Any files added to the _public_ collection will then be immutable, but accessible to anyone.
11
+ A **File type** is a _named collection_ of files. You can assign certain file-properties to a collection, such as access permissions, and when files are added to it they will inherit them. So, for example, you can create a new file type named _public_, and grant it public read access. Any files added to the _public_ collection will then be readable by anyone, without signing in.
12
12
 
13
13
  This gives developers a means for organizing and managing files with shared properties. You would want to create a File Type collection to
14
14
 
@@ -30,6 +30,4 @@ There is also an option to grant public read-only permission for any file added
30
30
 
31
31
  ### Retention Policy
32
32
 
33
- Note: Retention Policy is still under development.
34
-
35
- The _File Service_ gives you much more fine grained control through our [File Type collections](/adsp-monorepo/tutorials/file-service/file-types.html). You can set the retention policy for files in the collection, and those that have lived longer than the retention period will be automatically deleted.
33
+ The _File Service_ gives you much more fine grained control through our [File Type collections](/adsp-monorepo/tutorials/file-service/file-types.html). You can set the retention policy for files in the collection, and files that have not been accessed for longer than the retention period will be automatically deleted by a daily job.
@@ -28,4 +28,4 @@ All data stored in Azure Blob is [encrypted](https://learn.microsoft.com/en-us/a
28
28
 
29
29
  The _File Service_ gives you fine grained control of file retention through our [File Type collections](/adsp-monorepo/tutorials/file-service/file-types.html). You can set the retention policy for files in the collection, and those that have been untouched for longer than the retention period will be automatically deleted.
30
30
 
31
- Note: this policy does support any specific retention policies for _deleted files_ that may be required for your application. i.e. Once a file has been deleted from the File Service the data will be lost after a 7 day retention period that is set in the _Azure Blob_ configuration. You can, however, define the required retention period in your _File Type collection_ and let the _File Service_ mange the lifecycle. The file will only be deleted once it has been untouched for the defined period of time.
31
+ Note: this policy does not support any specific retention policies for _deleted files_ that may be required for your application. i.e. Once a file has been deleted from the File Service the data will be lost after a 7 day retention period that is set in the _Azure Blob_ configuration. You can, however, define the required retention period in your _File Type collection_ and let the _File Service_ mange the lifecycle. The file will only be deleted once it has been untouched for the defined period of time.
@@ -15,21 +15,21 @@ The _File Service_ has two main components;
15
15
 
16
16
  ### Tenant Admin Webapp
17
17
 
18
- Configuring the _File Service_ is about creating _File Type collections_, and setting up permissions and retention policies for them. You do this through our [Tenant Admin Webapp](https://adsp-uat.alberta.ca). See [File Type collections](/adsp-monorepo/tutorials/access-service/file-types.html) for more information.
18
+ Configuring the _File Service_ is about creating _File Type collections_, and setting up permissions and retention policies for them. You do this through our [Tenant Admin Webapp](https://adsp-uat.alberta.ca). See [File Type collections](/adsp-monorepo/tutorials/file-service/file-types.html) for more information.
19
19
 
20
20
  ### API
21
21
 
22
22
  You can learn the specific details of how an API works from our [Swagger Documentation](https://api.adsp.alberta.ca/autotest/?urls.primaryName=File%20service); here we'll just give a brief overview of the functionality supplied through them.
23
23
 
24
- All API calls to the _File Service_ require authentication via Keycloak. See the instructions for [setting up a tenant and getting access tokens](/adsp-monorepo/tutorials/access-service/introduction.html) for details on how to do this.
24
+ API calls to the _File Service_ require authentication via Keycloak, except reading and downloading files of File Type collections that allow public (anonymous) read. See the instructions for [setting up a tenant and getting access tokens](/adsp-monorepo/tutorials/access-service/introduction.html) for details on how to do this.
25
25
 
26
26
  ### Uploading
27
27
 
28
- Files are uploaded to Azure Blob Storage and stored as octet streams. In addition to the file, there is a small amount of metadata that gets created and stored along with it, as discussed below.
28
+ Files are uploaded as `multipart/form-data` requests and stored in Azure Blob Storage. In addition to the file, there is a small amount of metadata that gets created and stored along with it, as discussed below.
29
29
 
30
30
  ### File Scanning
31
31
 
32
- When you upload a file, you can specify whether or not it should be scanned for viruses or other malicious software (defaults to scan). Scanning is provided by [ClamAV](https://docs.clamav.net/Introduction.html), an open-source anti-virus toolkit maintained by Cisco Systems Inc. The database is updated frequently, so you can be sure the File Service will be looking for the latest threats. The service is designed to be fast, but you may find there is some delay between uploading and being able to access your file. This should not be an issue with small files.
32
+ Every uploaded file is scanned for viruses or other malicious software after the upload completes; a file cannot be downloaded until its scan is complete, unless the download explicitly sets `unsafe=true`. Scanning is provided by [ClamAV](https://docs.clamav.net/Introduction.html), an open-source anti-virus toolkit maintained by Cisco Systems Inc. The database is updated frequently, so you can be sure the File Service will be looking for the latest threats. The service is designed to be fast, but you may find there is some delay between uploading and being able to access your file. This should not be an issue with small files.
33
33
 
34
34
  ### Access Permission
35
35
 
@@ -62,4 +62,4 @@ You can search through your uploaded files using the following criteria
62
62
 
63
63
  ### Downloading
64
64
 
65
- Files are stored, and downloaded, as octet streams. Please see the [Swagger Documentation](https://api.adsp.alberta.ca/autotest/?urls.primaryName=File%20service#/File/get_file_v1_files__fileId__download) for more information on downloading via the APIs.
65
+ Files are downloaded with the `Content-Type` of the file (for example `application/pdf`), as an attachment by default or inline with `embed=true`. Please see the [Swagger Documentation](https://api.adsp.alberta.ca/autotest/?urls.primaryName=File%20service#/File/get_file_v1_files__fileId__download) for more information on downloading via the APIs.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@abgov/adsp-sdk-mcp-server",
3
- "version": "1.22.1",
3
+ "version": "1.24.0",
4
4
  "license": "Apache-2.0",
5
5
  "description": "Government of Alberta - MCP server for ADSP documentation and Node SDK reference lookup.",
6
6
  "repository": "https://github.com/GovAlta/adsp-monorepo",
@@ -10,7 +10,12 @@
10
10
  "dependencies": {
11
11
  "@abgov/adsp-cli": "^1.7.0",
12
12
  "@modelcontextprotocol/sdk": "^1.29.0",
13
+ "@opentelemetry/api": "1.9.0",
14
+ "@opentelemetry/exporter-metrics-otlp-http": "^0.221.0",
15
+ "@opentelemetry/resources": "2.10.0",
16
+ "@opentelemetry/sdk-metrics": "2.10.0",
13
17
  "express": "^4.21.0",
18
+ "express-rate-limit": "^7.1.4",
14
19
  "tslib": "^2.3.0",
15
20
  "zod": "^4.6.7"
16
21
  },
@@ -0,0 +1,11 @@
1
+ export interface McpServerConfig {
2
+ maxInFlight: number;
3
+ inFlightWaitMs: number;
4
+ /** 0 disables the rate limit. */
5
+ rateLimitPerMinute: number;
6
+ liveToolMaxConcurrent: number;
7
+ /** Passed to Express `trust proxy`. */
8
+ trustedProxy: boolean | number | string;
9
+ corsOrigins: '*' | string[];
10
+ }
11
+ export declare function readConfig(env?: NodeJS.ProcessEnv): McpServerConfig;
package/src/config.js ADDED
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.readConfig = readConfig;
4
+ function readInteger(env, name, defaultValue, minimum) {
5
+ const raw = env[name]?.trim();
6
+ if (!raw) {
7
+ return defaultValue;
8
+ }
9
+ if (!/^\d+$/.test(raw) || Number(raw) < minimum) {
10
+ throw new Error(`${name} must be an integer of at least ${minimum}, but is "${raw}".`);
11
+ }
12
+ return Number(raw);
13
+ }
14
+ function readTrustedProxy(env) {
15
+ const raw = env['TRUSTED_PROXY']?.trim();
16
+ if (!raw) {
17
+ return 'uniquelocal';
18
+ }
19
+ if (raw === 'true' || raw === 'false') {
20
+ return raw === 'true';
21
+ }
22
+ return /^\d+$/.test(raw) ? Number(raw) : raw;
23
+ }
24
+ function readCorsOrigins(env) {
25
+ const origins = (env['CORS_ORIGIN'] ?? '')
26
+ .split(',')
27
+ .map((origin) => origin.trim().replace(/\/+$/, ''))
28
+ .filter(Boolean);
29
+ if (!origins.includes('*')) {
30
+ return origins;
31
+ }
32
+ if (origins.length > 1) {
33
+ throw new Error('CORS_ORIGIN must be either * or a list of origins, not both.');
34
+ }
35
+ return '*';
36
+ }
37
+ function readConfig(env = process.env) {
38
+ return {
39
+ maxInFlight: readInteger(env, 'MCP_MAX_IN_FLIGHT', 64, 1),
40
+ inFlightWaitMs: readInteger(env, 'MCP_IN_FLIGHT_WAIT_MS', 1000, 0),
41
+ rateLimitPerMinute: readInteger(env, 'MCP_RATE_LIMIT_PER_MINUTE', 1200, 0),
42
+ liveToolMaxConcurrent: readInteger(env, 'MCP_LIVE_TOOL_MAX_CONCURRENT', 8, 1),
43
+ trustedProxy: readTrustedProxy(env),
44
+ corsOrigins: readCorsOrigins(env),
45
+ };
46
+ }
47
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../../../../libs/adsp-sdk-mcp-server/src/config.ts"],"names":[],"mappings":";;AA+CA,gCASC;AA7CD,SAAS,WAAW,CAAC,GAAsB,EAAE,IAAY,EAAE,YAAoB,EAAE,OAAe;IAC9F,MAAM,GAAG,GAAG,GAAG,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,CAAC;IAC9B,IAAI,CAAC,GAAG,EAAE,CAAC;QACT,OAAO,YAAY,CAAC;IACtB,CAAC;IACD,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,GAAG,OAAO,EAAE,CAAC;QAChD,MAAM,IAAI,KAAK,CAAC,GAAG,IAAI,mCAAmC,OAAO,aAAa,GAAG,IAAI,CAAC,CAAC;IACzF,CAAC;IACD,OAAO,MAAM,CAAC,GAAG,CAAC,CAAC;AACrB,CAAC;AAED,SAAS,gBAAgB,CAAC,GAAsB;IAC9C,MAAM,GAAG,GAAG,GAAG,CAAC,eAAe,CAAC,EAAE,IAAI,EAAE,CAAC;IACzC,IAAI,CAAC,GAAG,EAAE,CAAC;QACT,OAAO,aAAa,CAAC;IACvB,CAAC;IACD,IAAI,GAAG,KAAK,MAAM,IAAI,GAAG,KAAK,OAAO,EAAE,CAAC;QACtC,OAAO,GAAG,KAAK,MAAM,CAAC;IACxB,CAAC;IACD,OAAO,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;AAC/C,CAAC;AAED,SAAS,eAAe,CAAC,GAAsB;IAC7C,MAAM,OAAO,GAAG,CAAC,GAAG,CAAC,aAAa,CAAC,IAAI,EAAE,CAAC;SACvC,KAAK,CAAC,GAAG,CAAC;SACV,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;SAClD,MAAM,CAAC,OAAO,CAAC,CAAC;IACnB,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;QAC3B,OAAO,OAAO,CAAC;IACjB,CAAC;IACD,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACvB,MAAM,IAAI,KAAK,CAAC,8DAA8D,CAAC,CAAC;IAClF,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AAED,SAAgB,UAAU,CAAC,MAAyB,OAAO,CAAC,GAAG;IAC7D,OAAO;QACL,WAAW,EAAE,WAAW,CAAC,GAAG,EAAE,mBAAmB,EAAE,EAAE,EAAE,CAAC,CAAC;QACzD,cAAc,EAAE,WAAW,CAAC,GAAG,EAAE,uBAAuB,EAAE,IAAI,EAAE,CAAC,CAAC;QAClE,kBAAkB,EAAE,WAAW,CAAC,GAAG,EAAE,2BAA2B,EAAE,IAAI,EAAE,CAAC,CAAC;QAC1E,qBAAqB,EAAE,WAAW,CAAC,GAAG,EAAE,8BAA8B,EAAE,CAAC,EAAE,CAAC,CAAC;QAC7E,YAAY,EAAE,gBAAgB,CAAC,GAAG,CAAC;QACnC,WAAW,EAAE,eAAe,CAAC,GAAG,CAAC;KAClC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,11 @@
1
+ import type * as express from 'express';
2
+ import { McpServerConfig } from './config';
3
+ import { Semaphore } from './semaphore';
4
+ export declare function sendJsonRpcError(res: express.Response, status: number, message: string): void;
5
+ /** MCP requires servers to validate Origin (2025-11-25). Requests without one come from non-browser clients and pass. */
6
+ export declare function createCorsAndOriginGuard(corsOrigins: McpServerConfig['corsOrigins']): express.RequestHandler;
7
+ /** Keyed by client IP until authentication lands; then this should return the authenticated client. */
8
+ export declare function rateLimitKey(req: express.Request): string;
9
+ export declare function createRateLimit(limitPerMinute: number): express.RequestHandler;
10
+ /** Holds each admitted request's slot until its response closes; `mcp.requests.in_flight` counts admitted requests. */
11
+ export declare function createInFlightGate(semaphore: Semaphore, waitMs: number): express.RequestHandler;