@terreno/api 57.0.0 → 57.2.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 (175) hide show
  1. package/.ai/skills/mongoose-schema-safety/SKILL.md +8 -0
  2. package/dist/actions.d.ts +7 -2
  3. package/dist/actions.js +60 -25
  4. package/dist/adminModelRouter.d.ts +14 -0
  5. package/dist/adminModelRouter.js +199 -0
  6. package/dist/adminTypes.d.ts +182 -0
  7. package/dist/adminTypes.js +5 -0
  8. package/dist/api.d.ts +44 -3
  9. package/dist/api.js +74 -26
  10. package/dist/auth.d.ts +18 -1
  11. package/dist/auth.js +122 -20
  12. package/dist/consentApp.d.ts +2 -0
  13. package/dist/consentApp.js +98 -0
  14. package/dist/index.d.ts +22 -1
  15. package/dist/index.js +51 -7
  16. package/dist/mcp/auth.d.ts +11 -0
  17. package/dist/mcp/auth.js +133 -0
  18. package/dist/mcp/createMCPRequest.d.ts +16 -0
  19. package/dist/mcp/createMCPRequest.js +26 -0
  20. package/dist/mcp/handlers.d.ts +8 -0
  21. package/dist/mcp/handlers.js +793 -0
  22. package/dist/mcp/query.d.ts +32 -0
  23. package/dist/mcp/query.js +232 -0
  24. package/dist/mcp/registry.d.ts +21 -0
  25. package/dist/mcp/registry.js +54 -0
  26. package/dist/mcp/schemaGenerator.d.ts +14 -0
  27. package/dist/mcp/schemaGenerator.js +379 -0
  28. package/dist/mcp/server.d.ts +8 -0
  29. package/dist/mcp/server.js +133 -0
  30. package/dist/mcp/toolGenerator.d.ts +14 -0
  31. package/dist/mcp/toolGenerator.js +246 -0
  32. package/dist/mcp/types.d.ts +85 -0
  33. package/dist/mcp/types.js +2 -0
  34. package/dist/openApi.d.ts +1 -1
  35. package/dist/openApi.js +26 -8
  36. package/dist/permissions.js +15 -15
  37. package/dist/rbac/access.d.ts +3 -0
  38. package/dist/rbac/access.js +294 -0
  39. package/dist/rbac/auditModel.d.ts +31 -0
  40. package/dist/rbac/auditModel.js +112 -0
  41. package/dist/rbac/backfillAdmins.d.ts +18 -0
  42. package/dist/rbac/backfillAdmins.js +139 -0
  43. package/dist/rbac/fieldViews.d.ts +3 -0
  44. package/dist/rbac/fieldViews.js +201 -0
  45. package/dist/rbac/middleware.d.ts +21 -0
  46. package/dist/rbac/middleware.js +108 -0
  47. package/dist/rbac/modelRouterAccess.d.ts +42 -0
  48. package/dist/rbac/modelRouterAccess.js +388 -0
  49. package/dist/rbac/permissionUtils.d.ts +8 -0
  50. package/dist/rbac/permissionUtils.js +209 -0
  51. package/dist/rbac/realtimeAccess.d.ts +18 -0
  52. package/dist/rbac/realtimeAccess.js +173 -0
  53. package/dist/rbac/resolve.d.ts +28 -0
  54. package/dist/rbac/resolve.js +387 -0
  55. package/dist/rbac/roleManager.d.ts +20 -0
  56. package/dist/rbac/roleManager.js +741 -0
  57. package/dist/rbac/roleModel.d.ts +42 -0
  58. package/dist/rbac/roleModel.js +267 -0
  59. package/dist/rbac/routes.d.ts +9 -0
  60. package/dist/rbac/routes.js +211 -0
  61. package/dist/rbac/scopes.d.ts +15 -0
  62. package/dist/rbac/scopes.js +155 -0
  63. package/dist/rbac/statements.d.ts +30 -0
  64. package/dist/rbac/statements.js +126 -0
  65. package/dist/rbac/types.d.ts +202 -0
  66. package/dist/rbac/types.js +2 -0
  67. package/dist/rbac/userPlugin.d.ts +12 -0
  68. package/dist/rbac/userPlugin.js +41 -0
  69. package/dist/realtime/changeStreamWatcher.d.ts +1 -1
  70. package/dist/realtime/changeStreamWatcher.js +48 -39
  71. package/dist/realtime/realtimeApp.js +4 -8
  72. package/dist/realtime/registry.d.ts +5 -0
  73. package/dist/realtime/registry.js +13 -1
  74. package/dist/scrubAdminFields.d.ts +17 -0
  75. package/dist/scrubAdminFields.js +192 -0
  76. package/dist/sync/executors.d.ts +1 -1
  77. package/dist/sync/executors.js +63 -40
  78. package/dist/sync/loadHarness.js +4 -5
  79. package/dist/sync/registry.d.ts +5 -0
  80. package/dist/sync/registry.js +13 -1
  81. package/dist/sync/routes.js +41 -36
  82. package/dist/sync/serialize.js +5 -6
  83. package/dist/terrenoApp.d.ts +18 -0
  84. package/dist/terrenoApp.js +46 -3
  85. package/dist/terrenoPlugin.d.ts +8 -1
  86. package/dist/tests/createTestData.js +8 -0
  87. package/dist/tests/models.d.ts +1 -0
  88. package/dist/tests/models.js +5 -0
  89. package/dist/tests/testHelper.js +1 -2
  90. package/dist/transformers.js +16 -1
  91. package/package.json +17 -13
  92. package/src/__snapshots__/openApi.test.ts.snap +192 -0
  93. package/src/actions.test.ts +194 -1
  94. package/src/actions.ts +65 -8
  95. package/src/adminModelRouter.ts +154 -0
  96. package/src/adminTypes.ts +206 -0
  97. package/src/api.test.ts +66 -1
  98. package/src/api.ts +131 -12
  99. package/src/auth.test.ts +135 -1
  100. package/src/auth.ts +81 -3
  101. package/src/consentApp.test.ts +24 -0
  102. package/src/consentApp.ts +100 -0
  103. package/src/index.ts +56 -0
  104. package/src/mcp/auth.test.ts +197 -0
  105. package/src/mcp/auth.ts +100 -0
  106. package/src/mcp/createMCPRequest.test.ts +47 -0
  107. package/src/mcp/createMCPRequest.ts +32 -0
  108. package/src/mcp/customTools.test.ts +54 -0
  109. package/src/mcp/handlers.ts +639 -0
  110. package/src/mcp/integration.test.ts +1493 -0
  111. package/src/mcp/query.test.ts +172 -0
  112. package/src/mcp/query.ts +179 -0
  113. package/src/mcp/registry.ts +70 -0
  114. package/src/mcp/schemaGenerator.test.ts +182 -0
  115. package/src/mcp/schemaGenerator.ts +354 -0
  116. package/src/mcp/server.test.ts +226 -0
  117. package/src/mcp/server.ts +86 -0
  118. package/src/mcp/toolGenerator.test.ts +284 -0
  119. package/src/mcp/toolGenerator.ts +199 -0
  120. package/src/mcp/types.ts +95 -0
  121. package/src/openApi.test.ts +107 -0
  122. package/src/openApi.ts +32 -1
  123. package/src/permissions.ts +3 -2
  124. package/src/rbac/access.test.ts +357 -0
  125. package/src/rbac/access.ts +201 -0
  126. package/src/rbac/auditModel.ts +103 -0
  127. package/src/rbac/backfillAdmins.ts +54 -0
  128. package/src/rbac/fieldViews.test.ts +39 -0
  129. package/src/rbac/fieldViews.ts +122 -0
  130. package/src/rbac/middleware.ts +55 -0
  131. package/src/rbac/modelRouterAccess.test.ts +336 -0
  132. package/src/rbac/modelRouterAccess.ts +331 -0
  133. package/src/rbac/permissionUtils.test.ts +112 -0
  134. package/src/rbac/permissionUtils.ts +83 -0
  135. package/src/rbac/realtimeAccess.test.ts +242 -0
  136. package/src/rbac/realtimeAccess.ts +138 -0
  137. package/src/rbac/resolve.test.ts +358 -0
  138. package/src/rbac/resolve.ts +285 -0
  139. package/src/rbac/roleManager.test.ts +915 -0
  140. package/src/rbac/roleManager.ts +440 -0
  141. package/src/rbac/roleModel.test.ts +114 -0
  142. package/src/rbac/roleModel.ts +196 -0
  143. package/src/rbac/routes.ts +170 -0
  144. package/src/rbac/scopes.test.ts +105 -0
  145. package/src/rbac/scopes.ts +81 -0
  146. package/src/rbac/statements.test.ts +67 -0
  147. package/src/rbac/statements.ts +73 -0
  148. package/src/rbac/types.ts +198 -0
  149. package/src/rbac/userPlugin.test.ts +55 -0
  150. package/src/rbac/userPlugin.ts +25 -0
  151. package/src/realtime/changeStreamWatcher.ts +20 -15
  152. package/src/realtime/realtime.test.ts +25 -1
  153. package/src/realtime/realtimeApp.ts +2 -5
  154. package/src/realtime/registry.ts +15 -0
  155. package/src/scrubAdminFields.test.ts +113 -0
  156. package/src/scrubAdminFields.ts +158 -0
  157. package/src/sync/executors.ts +31 -1
  158. package/src/sync/loadHarness.ts +8 -7
  159. package/src/sync/models.test.ts +262 -0
  160. package/src/sync/registry.ts +15 -0
  161. package/src/sync/routes.ts +25 -11
  162. package/src/sync/scripts/compactTombstones.test.ts +4 -6
  163. package/src/sync/serialize.ts +17 -9
  164. package/src/sync/sync.test.ts +52 -0
  165. package/src/sync/syncRoutes.test.ts +5 -2
  166. package/src/sync/syncSocket.test.ts +28 -0
  167. package/src/terrenoApp.test.ts +100 -0
  168. package/src/terrenoApp.ts +65 -3
  169. package/src/terrenoPlugin.ts +10 -1
  170. package/src/tests/bunSetup.ts +2 -0
  171. package/src/tests/createTestData.ts +5 -1
  172. package/src/tests/models.ts +6 -0
  173. package/src/tests/testHelper.ts +1 -3
  174. package/src/transformers.test.ts +12 -0
  175. package/src/transformers.ts +7 -1
@@ -0,0 +1,639 @@
1
+ import mongoose from "mongoose";
2
+
3
+ import {addPopulateToQuery, type JSONValue} from "../api";
4
+ import {omitUserRolesFromWriteBody, type User} from "../auth";
5
+ import {isAPIError} from "../errors";
6
+ import {checkPermissions} from "../permissions";
7
+ import type {PopulatePath} from "../populate";
8
+ import {validateAccessWritePayload} from "../rbac/modelRouterAccess";
9
+ import {defaultResponseHandler, transform} from "../transformers";
10
+ import {createMCPRequest} from "./createMCPRequest";
11
+ import {buildListQuery} from "./query";
12
+ import {restWriteExcludeFields, writeExcludeFields} from "./schemaGenerator";
13
+ import type {MCPDocument, MCPMethod, MCPRegistryEntry, MCPToolArgs, MCPToolResult} from "./types";
14
+
15
+ /** Methods whose responses go through a responseHandler (delete returns only a status). */
16
+ type SerializableMCPMethod = Exclude<MCPMethod, "delete">;
17
+
18
+ // Causes stay server-side: a WeakMap lets the observability wrapper capture the
19
+ // original exception without adding stack traces or internal details to the MCP result.
20
+ const errorCauses = new WeakMap<MCPToolResult, unknown>();
21
+
22
+ export const getMCPErrorCause = (result: MCPToolResult): unknown => {
23
+ return errorCauses.get(result);
24
+ };
25
+
26
+ const isPlainObject = (value: unknown): value is Record<string, unknown> => {
27
+ return typeof value === "object" && value !== null && !Array.isArray(value);
28
+ };
29
+
30
+ /** Mongoose documents only expose their fields through toObject(). */
31
+ const toPlain = (value: unknown): unknown => {
32
+ if (isPlainObject(value) && typeof value.toObject === "function") {
33
+ return (value.toObject as () => unknown)();
34
+ }
35
+ return value;
36
+ };
37
+
38
+ /**
39
+ * Values that serialize themselves — ObjectId, Date, Decimal128, Buffer — must be passed
40
+ * through untouched. Rebuilding them entry by entry would replace an ObjectId with its
41
+ * raw `{buffer: ...}` internals and a Date with `{}`.
42
+ */
43
+ const isSelfSerializing = (value: Record<string, unknown>): boolean => {
44
+ return typeof value.toJSON === "function";
45
+ };
46
+
47
+ /**
48
+ * Delete a dot-notation path, descending into arrays element-wise so paths through
49
+ * arrays of subdocuments (e.g. "items.secret") are removed from every element.
50
+ */
51
+ const deleteAtPath = (obj: unknown, segments: string[]): void => {
52
+ if (Array.isArray(obj)) {
53
+ for (const item of obj) {
54
+ deleteAtPath(item, segments);
55
+ }
56
+ return;
57
+ }
58
+ if (!isPlainObject(obj) || segments.length === 0) {
59
+ return;
60
+ }
61
+ const [head, ...rest] = segments;
62
+ if (rest.length === 0) {
63
+ delete obj[head];
64
+ return;
65
+ }
66
+ deleteAtPath(obj[head], rest);
67
+ };
68
+
69
+ /**
70
+ * Remove excluded fields from an MCP response.
71
+ *
72
+ * Bare field names are removed at every depth (including inside arrays and populated
73
+ * refs) so a redacted name never leaks through a nested document. Use a dot-notation
74
+ * path when only one specific location should be removed. Literal object keys that
75
+ * equal a denylist entry (including dotted names) are also dropped.
76
+ */
77
+ const stripExcludedFields = (data: unknown, excludeFields: string[]): unknown => {
78
+ if (!excludeFields.length || !data) {
79
+ return data;
80
+ }
81
+
82
+ const bareKeys = new Set(excludeFields.filter((field) => !field.includes(".")));
83
+ const dotPaths = excludeFields
84
+ .filter((field) => field.includes("."))
85
+ .map((field) => field.split("."));
86
+
87
+ const strip = (value: unknown): unknown => {
88
+ const plain = toPlain(value);
89
+ if (Array.isArray(plain)) {
90
+ return plain.map(strip);
91
+ }
92
+ if (!isPlainObject(plain) || isSelfSerializing(plain)) {
93
+ return plain;
94
+ }
95
+ const result: Record<string, unknown> = {};
96
+ for (const [key, nested] of Object.entries(plain)) {
97
+ // Exact key match covers both bare names and literal dotted keys
98
+ // ("metadata.nested.token") that Mongoose would otherwise treat as a path.
99
+ if (bareKeys.has(key) || excludeFields.includes(key)) {
100
+ continue;
101
+ }
102
+ result[key] = strip(nested);
103
+ }
104
+ return result;
105
+ };
106
+
107
+ const stripped = strip(data);
108
+ for (const segments of dotPaths) {
109
+ deleteAtPath(stripped, segments);
110
+ }
111
+ return stripped;
112
+ };
113
+
114
+ /**
115
+ * Resolve the `populate` tool argument against the model router's declared paths.
116
+ *
117
+ * REST never lets a caller choose populate paths — population comes entirely from
118
+ * `options.populatePaths`, whose `fields` limit which columns of the referenced document
119
+ * are exposed. An arbitrary path from an MCP client would bypass that limit and return
120
+ * whole referenced documents, so a requested path must match a declared one. Requesting
121
+ * paths only narrows the set; anything undeclared is an error rather than a silent widen.
122
+ */
123
+ const resolvePopulatePaths = (
124
+ populateStr: string | undefined,
125
+ declaredPaths?: PopulatePath[]
126
+ ): {paths?: PopulatePath[]; error?: string} => {
127
+ const declared = declaredPaths ?? [];
128
+ if (!populateStr) {
129
+ return {paths: declared};
130
+ }
131
+
132
+ const requested = populateStr
133
+ .split(",")
134
+ .map((path) => path.trim())
135
+ .filter(Boolean);
136
+ if (!requested.length) {
137
+ return {paths: declared};
138
+ }
139
+
140
+ const paths: PopulatePath[] = [];
141
+ for (const path of requested) {
142
+ const match = declared.find((declaredPath) => declaredPath.path === path);
143
+ if (!match) {
144
+ const allowed = declared.map((declaredPath) => declaredPath.path).join(", ");
145
+ return {
146
+ error: allowed
147
+ ? `${path} is not a populate-able path. Allowed: ${allowed}`
148
+ : `${path} is not a populate-able path. This model has no populate-able paths`,
149
+ };
150
+ }
151
+ if (!paths.includes(match)) {
152
+ paths.push(match);
153
+ }
154
+ }
155
+ return {paths};
156
+ };
157
+
158
+ const asOptionalString = (value: unknown): string | undefined => {
159
+ return typeof value === "string" ? value : undefined;
160
+ };
161
+
162
+ /**
163
+ * Remove denylisted keys from an MCP create/update body.
164
+ *
165
+ * Matches response redaction: a bare name is deleted at every depth (including
166
+ * Mixed/embedded objects and arrays), and a dotted path is deleted at that
167
+ * location only. The incoming args object is not mutated.
168
+ */
169
+ const omitDeniedWriteFields = (body: MCPToolArgs, denied: string[]): MCPToolArgs => {
170
+ if (denied.length === 0) {
171
+ return body;
172
+ }
173
+ return stripExcludedFields(body, denied) as MCPToolArgs;
174
+ };
175
+
176
+ /** Mongoose's populated query result types don't narrow to a single document. */
177
+ const asDocument = (result: unknown): MCPDocument | null => {
178
+ return (result ?? null) as MCPDocument | null;
179
+ };
180
+
181
+ /**
182
+ * Run a findById query and map Mongoose CastError (malformed ids) to null so
183
+ * callers can return a structured not-found. 24-hex ids with mixed case are
184
+ * valid for findById even though `isValidObjectId` requires canonical lowercase.
185
+ */
186
+ const execFindByIdQuery = async (query: {
187
+ exec: () => Promise<unknown>;
188
+ }): Promise<MCPDocument | null> => {
189
+ try {
190
+ return asDocument(await query.exec());
191
+ } catch (error) {
192
+ if (error instanceof mongoose.Error.CastError) {
193
+ return null;
194
+ }
195
+ throw error;
196
+ }
197
+ };
198
+
199
+ const missingDocumentResult = (id: unknown): MCPToolResult => {
200
+ return errorResult(`Document ${id} not found`);
201
+ };
202
+
203
+ /**
204
+ * Mirror REST's `authenticateMiddleware(options.allowAnonymous)`, which answers 401 before
205
+ * any permission check when credentials are missing. Without this, read-only helpers like
206
+ * `IsAuthenticatedOrReadOnly` would let an anonymous MCP client list or read data that the
207
+ * same router refuses over HTTP.
208
+ */
209
+ const requiresAuthentication = (entry: MCPRegistryEntry, user?: User): boolean => {
210
+ return !user && entry.options.allowAnonymous !== true;
211
+ };
212
+
213
+ const hookFailureResult = (label: string, error: unknown): MCPToolResult => {
214
+ if (isAPIError(error)) {
215
+ return errorResult(error.title, error);
216
+ }
217
+ return errorResult(`${label}: ${errorMessage(error)}`, error);
218
+ };
219
+
220
+ const serializeResponse = async (
221
+ data: unknown,
222
+ method: SerializableMCPMethod,
223
+ entry: MCPRegistryEntry,
224
+ user?: User
225
+ ): Promise<{error: MCPToolResult} | {value: JSONValue}> => {
226
+ try {
227
+ const excludeFields = entry.config.excludeFields ?? [];
228
+
229
+ if (entry.config.mcpResponseHandler) {
230
+ const result = await entry.config.mcpResponseHandler(data, method, user);
231
+ return {value: stripExcludedFields(result, excludeFields) as JSONValue};
232
+ }
233
+
234
+ // Use the model router's responseHandler if available, otherwise default
235
+ const responseHandler = entry.options.responseHandler ?? defaultResponseHandler;
236
+
237
+ const result = await responseHandler(data, method, createMCPRequest({user}), entry.options);
238
+ return {value: stripExcludedFields(result, excludeFields) as JSONValue};
239
+ } catch (error) {
240
+ if (isAPIError(error)) {
241
+ return {error: errorResult(error.title, error)};
242
+ }
243
+ return {error: errorResult(`Response handler failed: ${errorMessage(error)}`, error)};
244
+ }
245
+ };
246
+
247
+ export const handleList = async (
248
+ entry: MCPRegistryEntry,
249
+ args: MCPToolArgs,
250
+ user?: User
251
+ ): Promise<MCPToolResult> => {
252
+ const {model, config, options} = entry;
253
+ const maxLimit = config.maxLimit ?? 50;
254
+
255
+ if (requiresAuthentication(entry, user)) {
256
+ return errorResult("Permission denied: authentication required");
257
+ }
258
+
259
+ // Check permissions
260
+ if (!(await checkPermissions("list", options.permissions.list, user))) {
261
+ return errorResult("Permission denied: cannot list");
262
+ }
263
+
264
+ // Build query from args — only fields in queryFields, with an allowlist of operators
265
+ const {error: queryError, query: builtFilter} = buildListQuery({args, config, options});
266
+ if (queryError || !builtFilter) {
267
+ return errorResult(queryError ?? "Could not build query");
268
+ }
269
+ let query: Record<string, unknown> = builtFilter;
270
+
271
+ // Apply query filter
272
+ if (options.queryFilter) {
273
+ try {
274
+ const filtered = await options.queryFilter(user, query);
275
+ if (filtered === null) {
276
+ return textResult(JSON.stringify({data: [], more: false, page: 1, total: 0}));
277
+ }
278
+ query = {...query, ...filtered};
279
+ } catch (error) {
280
+ if (isAPIError(error)) {
281
+ return errorResult(error.title, error);
282
+ }
283
+ return errorResult(`queryFilter failed: ${errorMessage(error)}`, error);
284
+ }
285
+ }
286
+
287
+ // Pagination
288
+ const limit = Math.max(1, Math.min(Number(args.limit) || maxLimit, maxLimit));
289
+ const page = Math.max(1, Number(args.page) || 1);
290
+
291
+ let builtQuery = model.find(query).limit(limit + 1);
292
+ const total = await model.countDocuments(query);
293
+
294
+ if (page > 1) {
295
+ builtQuery = builtQuery.skip((page - 1) * limit);
296
+ }
297
+
298
+ // Sort
299
+ const sort = asOptionalString(args.sort) ?? options.sort;
300
+ if (sort) {
301
+ builtQuery = builtQuery.sort(sort);
302
+ }
303
+
304
+ // Populate
305
+ const {error: populateError, paths: populatePaths} = resolvePopulatePaths(
306
+ asOptionalString(args.populate),
307
+ options.populatePaths
308
+ );
309
+ if (populateError || !populatePaths) {
310
+ return errorResult(populateError ?? "Could not resolve populate paths");
311
+ }
312
+ const populatedQuery = addPopulateToQuery(builtQuery, populatePaths);
313
+
314
+ const data = await populatedQuery.exec();
315
+ const more = data.length > limit;
316
+ const sliced = more ? data.slice(0, limit) : data;
317
+
318
+ const serialized = await serializeResponse(sliced, "list", entry, user);
319
+ if ("error" in serialized) {
320
+ return serialized.error;
321
+ }
322
+
323
+ return textResult(JSON.stringify({data: serialized.value, more, page, total}));
324
+ };
325
+
326
+ export const handleRead = async (
327
+ entry: MCPRegistryEntry,
328
+ args: MCPToolArgs,
329
+ user?: User
330
+ ): Promise<MCPToolResult> => {
331
+ const {model, options} = entry;
332
+
333
+ if (requiresAuthentication(entry, user)) {
334
+ return errorResult("Permission denied: authentication required");
335
+ }
336
+
337
+ // Check method-level permission
338
+ if (!(await checkPermissions("read", options.permissions.read, user))) {
339
+ return errorResult("Permission denied: cannot read");
340
+ }
341
+
342
+ const {error: populateError, paths: populatePaths} = resolvePopulatePaths(
343
+ asOptionalString(args.populate),
344
+ options.populatePaths
345
+ );
346
+ if (populateError || !populatePaths) {
347
+ return errorResult(populateError ?? "Could not resolve populate paths");
348
+ }
349
+ const id = asOptionalString(args.id);
350
+ if (!id) {
351
+ return missingDocumentResult(args.id);
352
+ }
353
+ const data = await execFindByIdQuery(addPopulateToQuery(model.findById(id), populatePaths));
354
+
355
+ if (!data) {
356
+ return missingDocumentResult(id);
357
+ }
358
+
359
+ // Check object-level permission
360
+ if (!(await checkPermissions("read", options.permissions.read, user, data))) {
361
+ return errorResult("Permission denied: cannot read this document");
362
+ }
363
+
364
+ const serialized = await serializeResponse(data, "read", entry, user);
365
+ if ("error" in serialized) {
366
+ return serialized.error;
367
+ }
368
+ return textResult(JSON.stringify({data: serialized.value}));
369
+ };
370
+
371
+ export const handleCreate = async (
372
+ entry: MCPRegistryEntry,
373
+ args: MCPToolArgs,
374
+ user?: User
375
+ ): Promise<MCPToolResult> => {
376
+ const {model, options} = entry;
377
+
378
+ if (requiresAuthentication(entry, user)) {
379
+ return errorResult("Permission denied: authentication required");
380
+ }
381
+
382
+ if (!(await checkPermissions("create", options.permissions.create, user))) {
383
+ return errorResult("Permission denied: cannot create");
384
+ }
385
+
386
+ let body: MCPToolArgs | null = omitDeniedWriteFields(
387
+ args,
388
+ writeExcludeFields(entry.config, restWriteExcludeFields("create", options.validation))
389
+ );
390
+ try {
391
+ body = transform(options, body, "create", user) as MCPToolArgs;
392
+ } catch (error) {
393
+ return errorResult(`Transform failed: ${errorMessage(error)}`, error);
394
+ }
395
+
396
+ if (options.preCreate) {
397
+ try {
398
+ body = await options.preCreate(body, createMCPRequest({body, user}));
399
+ if (body === null || body === undefined) {
400
+ return errorResult("Create not allowed");
401
+ }
402
+ } catch (error) {
403
+ return hookFailureResult("preCreate hook failed", error);
404
+ }
405
+ }
406
+
407
+ body = omitUserRolesFromWriteBody(entry.modelName, options.accessControl, body) as MCPToolArgs;
408
+
409
+ try {
410
+ await validateAccessWritePayload({
411
+ body,
412
+ options,
413
+ phase: "create",
414
+ user,
415
+ });
416
+ } catch (error) {
417
+ if (isAPIError(error)) {
418
+ return errorResult(error.title, error);
419
+ }
420
+ return errorResult(`Write validation failed: ${errorMessage(error)}`, error);
421
+ }
422
+
423
+ let data: MCPDocument | null;
424
+ try {
425
+ data = asDocument(await model.create(body));
426
+ } catch (error) {
427
+ return errorResult(`Create failed: ${errorMessage(error)}`, error);
428
+ }
429
+
430
+ if (options.populatePaths) {
431
+ const populateQuery = addPopulateToQuery(model.findById(data?._id), options.populatePaths);
432
+ data = asDocument(await populateQuery.exec());
433
+ }
434
+
435
+ if (options.postCreate) {
436
+ try {
437
+ await options.postCreate(data, createMCPRequest({body, user}));
438
+ } catch (error) {
439
+ return hookFailureResult("postCreate hook failed", error);
440
+ }
441
+ }
442
+
443
+ const serialized = await serializeResponse(data, "create", entry, user);
444
+ if ("error" in serialized) {
445
+ return serialized.error;
446
+ }
447
+ return textResult(JSON.stringify({data: serialized.value}));
448
+ };
449
+
450
+ export const handleUpdate = async (
451
+ entry: MCPRegistryEntry,
452
+ args: MCPToolArgs,
453
+ user?: User
454
+ ): Promise<MCPToolResult> => {
455
+ const {model, options} = entry;
456
+ const {id, ...updateFields} = args;
457
+
458
+ if (requiresAuthentication(entry, user)) {
459
+ return errorResult("Permission denied: authentication required");
460
+ }
461
+
462
+ if (!(await checkPermissions("update", options.permissions.update, user))) {
463
+ return errorResult("Permission denied: cannot update");
464
+ }
465
+
466
+ const documentId = asOptionalString(id);
467
+ if (!documentId) {
468
+ return missingDocumentResult(id);
469
+ }
470
+
471
+ let doc = await execFindByIdQuery(
472
+ addPopulateToQuery(model.findById(documentId), options.populatePaths)
473
+ );
474
+
475
+ if (!doc) {
476
+ return missingDocumentResult(documentId);
477
+ }
478
+
479
+ if (!(await checkPermissions("update", options.permissions.update, user, doc))) {
480
+ return errorResult("Permission denied: cannot update this document");
481
+ }
482
+
483
+ let body: MCPToolArgs | null = omitDeniedWriteFields(
484
+ updateFields,
485
+ writeExcludeFields(entry.config, restWriteExcludeFields("update", options.validation))
486
+ );
487
+ try {
488
+ body = transform(options, body, "update", user) as MCPToolArgs;
489
+ } catch (error) {
490
+ return errorResult(`Transform failed: ${errorMessage(error)}`, error);
491
+ }
492
+
493
+ if (options.preUpdate) {
494
+ try {
495
+ body = await options.preUpdate(body, createMCPRequest({body, user}));
496
+ if (body === null || body === undefined) {
497
+ return errorResult("Update not allowed");
498
+ }
499
+ } catch (error) {
500
+ return hookFailureResult("preUpdate hook failed", error);
501
+ }
502
+ }
503
+
504
+ body = omitUserRolesFromWriteBody(entry.modelName, options.accessControl, body) as MCPToolArgs;
505
+
506
+ try {
507
+ await validateAccessWritePayload({
508
+ body,
509
+ doc,
510
+ options,
511
+ phase: "write",
512
+ user,
513
+ });
514
+ } catch (error) {
515
+ if (isAPIError(error)) {
516
+ return errorResult(error.title, error);
517
+ }
518
+ return errorResult(`Write validation failed: ${errorMessage(error)}`, error);
519
+ }
520
+
521
+ const prevDoc = doc.toObject();
522
+
523
+ try {
524
+ doc.set(body);
525
+ await doc.save();
526
+ } catch (error) {
527
+ return errorResult(`Update failed: ${errorMessage(error)}`, error);
528
+ }
529
+
530
+ if (options.populatePaths) {
531
+ const populateQuery = addPopulateToQuery(model.findById(doc._id), options.populatePaths);
532
+ doc = asDocument(await populateQuery.exec());
533
+ }
534
+
535
+ if (options.postUpdate) {
536
+ try {
537
+ await options.postUpdate(doc, body, createMCPRequest({body, user}), prevDoc);
538
+ } catch (error) {
539
+ return hookFailureResult("postUpdate hook failed", error);
540
+ }
541
+ }
542
+
543
+ const serialized = await serializeResponse(doc, "update", entry, user);
544
+ if ("error" in serialized) {
545
+ return serialized.error;
546
+ }
547
+ return textResult(JSON.stringify({data: serialized.value}));
548
+ };
549
+
550
+ export const handleDelete = async (
551
+ entry: MCPRegistryEntry,
552
+ args: MCPToolArgs,
553
+ user?: User
554
+ ): Promise<MCPToolResult> => {
555
+ const {model, options} = entry;
556
+ const {id} = args;
557
+
558
+ if (requiresAuthentication(entry, user)) {
559
+ return errorResult("Permission denied: authentication required");
560
+ }
561
+
562
+ if (!(await checkPermissions("delete", options.permissions.delete, user))) {
563
+ return errorResult("Permission denied: cannot delete");
564
+ }
565
+
566
+ const documentId = asOptionalString(id);
567
+ if (!documentId) {
568
+ return missingDocumentResult(id);
569
+ }
570
+
571
+ // Populate before the object-level permission check so custom permissions can inspect
572
+ // populated refs, matching handleRead/handleUpdate and REST's permissionMiddleware.
573
+ const doc = await execFindByIdQuery(
574
+ addPopulateToQuery(model.findById(documentId), options.populatePaths)
575
+ );
576
+
577
+ if (!doc) {
578
+ return missingDocumentResult(documentId);
579
+ }
580
+
581
+ if (!(await checkPermissions("delete", options.permissions.delete, user, doc))) {
582
+ return errorResult("Permission denied: cannot delete this document");
583
+ }
584
+
585
+ if (options.preDelete) {
586
+ try {
587
+ const result = await options.preDelete(doc, createMCPRequest({body: args, user}));
588
+ if (result === null || result === undefined) {
589
+ return errorResult("Delete not allowed");
590
+ }
591
+ } catch (error) {
592
+ return hookFailureResult("preDelete hook failed", error);
593
+ }
594
+ }
595
+
596
+ // Support soft delete via isDeleted plugin
597
+ try {
598
+ if (
599
+ Object.keys(model.schema.paths).includes("deleted") &&
600
+ model.schema.paths.deleted.instance === "Boolean"
601
+ ) {
602
+ doc.deleted = true;
603
+ await doc.save();
604
+ } else {
605
+ await doc.deleteOne();
606
+ }
607
+ } catch (error) {
608
+ return errorResult(`Delete failed: ${errorMessage(error)}`, error);
609
+ }
610
+
611
+ if (options.postDelete) {
612
+ try {
613
+ await options.postDelete(createMCPRequest({body: args, user}), doc);
614
+ } catch (error) {
615
+ return hookFailureResult("postDelete hook failed", error);
616
+ }
617
+ }
618
+
619
+ return textResult(JSON.stringify({success: true}));
620
+ };
621
+
622
+ const errorMessage = (error: unknown): string => {
623
+ return error instanceof Error ? error.message : String(error);
624
+ };
625
+
626
+ const textResult = (text: string): MCPToolResult => ({
627
+ content: [{text, type: "text" as const}],
628
+ });
629
+
630
+ const errorResult = (message: string, cause?: unknown): MCPToolResult => {
631
+ const result: MCPToolResult = {
632
+ content: [{text: JSON.stringify({error: message}), type: "text" as const}],
633
+ isError: true,
634
+ };
635
+ if (cause !== undefined) {
636
+ errorCauses.set(result, cause);
637
+ }
638
+ return result;
639
+ };