@terreno/api 57.0.0-beta.1 → 57.1.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 +156 -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 +20 -0
  64. package/dist/rbac/statements.js +115 -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 +16 -12
  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 +183 -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 +65 -0
  147. package/src/rbac/statements.ts +62 -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,284 @@
1
+ import {beforeEach, describe, expect, it, type Mock} from "bun:test";
2
+ import {Writable} from "node:stream";
3
+ import * as Sentry from "@sentry/bun";
4
+ import mongoose, {Schema} from "mongoose";
5
+ import winston from "winston";
6
+
7
+ import {winstonLogger} from "../logger";
8
+ import {Permissions} from "../permissions";
9
+ import {generateAllTools, generateToolsForEntry} from "./toolGenerator";
10
+ import type {MCPRegistryEntry} from "./types";
11
+
12
+ const createTestModel = () => {
13
+ try {
14
+ return mongoose.model("MCPToolGenTest");
15
+ } catch {
16
+ const schema = new Schema({
17
+ completed: {default: false, description: "Whether the item is complete", type: Boolean},
18
+ name: {description: "The name", required: true, type: String},
19
+ ownerId: {description: "Owner", ref: "User", type: Schema.Types.ObjectId},
20
+ });
21
+ return mongoose.model("MCPToolGenTest", schema);
22
+ }
23
+ };
24
+
25
+ const createEntry = (overrides?: Partial<MCPRegistryEntry>): MCPRegistryEntry => {
26
+ const model = createTestModel();
27
+ return {
28
+ config: {methods: ["list", "read"]},
29
+ model,
30
+ modelName: model.modelName,
31
+ options: {
32
+ permissions: {
33
+ create: [Permissions.IsAuthenticated],
34
+ delete: [Permissions.IsOwner],
35
+ list: [Permissions.IsAuthenticated],
36
+ read: [Permissions.IsOwner],
37
+ update: [Permissions.IsOwner],
38
+ },
39
+ queryFields: ["completed"],
40
+ },
41
+ ...overrides,
42
+ };
43
+ };
44
+
45
+ interface CapturedLog {
46
+ level: string;
47
+ message: string;
48
+ terrenoLabels?: Record<string, string>;
49
+ terrenoLogPrefix?: string;
50
+ }
51
+
52
+ const captureLogs = async (callback: () => Promise<void>): Promise<CapturedLog[]> => {
53
+ const logs: CapturedLog[] = [];
54
+ const transport = new winston.transports.Stream({
55
+ format: winston.format((info) => {
56
+ logs.push({
57
+ level: info.level,
58
+ message: String(info.message),
59
+ terrenoLabels: info.terrenoLabels as Record<string, string> | undefined,
60
+ terrenoLogPrefix: info.terrenoLogPrefix as string | undefined,
61
+ });
62
+ return info;
63
+ })(),
64
+ stream: new Writable({
65
+ write(_chunk, _encoding, done) {
66
+ done();
67
+ },
68
+ }),
69
+ });
70
+ winstonLogger.add(transport);
71
+ try {
72
+ await callback();
73
+ } finally {
74
+ winstonLogger.remove(transport);
75
+ }
76
+ return logs;
77
+ };
78
+
79
+ describe("generateToolsForEntry", () => {
80
+ it("generates tools for default methods (list, read)", () => {
81
+ const entry = createEntry();
82
+ const tools = generateToolsForEntry(entry);
83
+
84
+ expect(tools).toHaveLength(2);
85
+ expect(tools[0].name).toBe("mcptoolgentests_list");
86
+ expect(tools[1].name).toBe("mcptoolgentests_read");
87
+ });
88
+
89
+ it("generates tools for all CRUD methods", () => {
90
+ const entry = createEntry({
91
+ config: {methods: ["create", "list", "read", "update", "delete"]},
92
+ });
93
+ const tools = generateToolsForEntry(entry);
94
+
95
+ expect(tools).toHaveLength(5);
96
+ const names = tools.map((t) => t.name);
97
+ expect(names).toContain("mcptoolgentests_create");
98
+ expect(names).toContain("mcptoolgentests_list");
99
+ expect(names).toContain("mcptoolgentests_read");
100
+ expect(names).toContain("mcptoolgentests_update");
101
+ expect(names).toContain("mcptoolgentests_delete");
102
+ });
103
+
104
+ it("uses custom toolPrefix", () => {
105
+ const entry = createEntry({config: {methods: ["list"], toolPrefix: "items"}});
106
+ const tools = generateToolsForEntry(entry);
107
+
108
+ expect(tools[0].name).toBe("items_list");
109
+ });
110
+
111
+ it("skips methods with empty permission arrays", () => {
112
+ const entry = createEntry({
113
+ config: {methods: ["list", "read", "delete"]},
114
+ options: {
115
+ permissions: {
116
+ create: [Permissions.IsAuthenticated],
117
+ delete: [], // disabled
118
+ list: [Permissions.IsAuthenticated],
119
+ read: [Permissions.IsOwner],
120
+ update: [Permissions.IsOwner],
121
+ },
122
+ },
123
+ });
124
+ const tools = generateToolsForEntry(entry);
125
+
126
+ expect(tools).toHaveLength(2);
127
+ const names = tools.map((t) => t.name);
128
+ expect(names).not.toContain("mcptoolgentests_delete");
129
+ });
130
+
131
+ it("generates valid input schemas", () => {
132
+ const entry = createEntry({config: {methods: ["list", "read"]}});
133
+ const tools = generateToolsForEntry(entry);
134
+
135
+ const listTool = tools.find((t) => t.name.endsWith("_list"));
136
+ expect(listTool?.inputSchema).toBeDefined();
137
+ expect(listTool?.inputSchema.type).toBe("object");
138
+ expect(listTool?.inputSchema.properties).toBeDefined();
139
+
140
+ const readTool = tools.find((t) => t.name.endsWith("_read"));
141
+ expect(readTool?.inputSchema).toBeDefined();
142
+ expect(readTool?.inputSchema.properties?.id).toBeDefined();
143
+ });
144
+
145
+ it("includes descriptions on tools", () => {
146
+ const entry = createEntry();
147
+ const tools = generateToolsForEntry(entry);
148
+
149
+ expect(tools[0].description).toBeTruthy();
150
+ expect(tools[0].description.length).toBeGreaterThan(10);
151
+ });
152
+ });
153
+
154
+ describe("generateAllTools", () => {
155
+ it("generates tools from multiple entries", () => {
156
+ const entry1 = createEntry();
157
+ const entry2 = createEntry({
158
+ config: {methods: ["list"], toolPrefix: "others"},
159
+ });
160
+
161
+ const tools = generateAllTools([entry1, entry2]);
162
+ expect(tools.length).toBe(3); // 2 from entry1 + 1 from entry2
163
+ });
164
+ });
165
+
166
+ describe("tool-call observability", () => {
167
+ const captureException = Sentry.captureException as Mock<typeof Sentry.captureException>;
168
+
169
+ beforeEach(async () => {
170
+ captureException.mockClear();
171
+ await createTestModel().deleteMany({});
172
+ });
173
+
174
+ it("logs successful calls with stable MCP labels", async () => {
175
+ const entry = createEntry({
176
+ config: {methods: ["create"]},
177
+ options: {
178
+ allowAnonymous: true,
179
+ permissions: {
180
+ create: [Permissions.IsAny],
181
+ delete: [],
182
+ list: [],
183
+ read: [],
184
+ update: [],
185
+ },
186
+ },
187
+ });
188
+ const [tool] = generateToolsForEntry(entry);
189
+
190
+ const logs = await captureLogs(async () => {
191
+ const result = await tool.handler({name: "observable"});
192
+ expect(result.isError).not.toBe(true);
193
+ });
194
+
195
+ const succeeded = logs.find((line) => line.message.includes("MCP tool call succeeded"));
196
+ expect(succeeded?.level).toBe("info");
197
+ expect(succeeded?.terrenoLogPrefix).toBe("[MCPTool]");
198
+ expect(succeeded?.terrenoLabels).toEqual({
199
+ mcpMethod: "create",
200
+ mcpModel: "MCPToolGenTest",
201
+ mcpTool: "mcptoolgentests_create",
202
+ });
203
+ });
204
+
205
+ it("warns for expected refusals without capturing an exception", async () => {
206
+ const [tool] = generateToolsForEntry(createEntry({config: {methods: ["list"]}}));
207
+
208
+ const logs = await captureLogs(async () => {
209
+ const result = await tool.handler({});
210
+ expect(result.isError).toBe(true);
211
+ });
212
+
213
+ expect(logs.some((line) => line.level === "warn" && line.message.includes("refused"))).toBe(
214
+ true
215
+ );
216
+ expect(captureException).not.toHaveBeenCalled();
217
+ });
218
+
219
+ it("captures internal failures in Sentry without exposing the cause to the client", async () => {
220
+ process.env.USE_SENTRY_LOGGING = "true";
221
+ const entry = createEntry({
222
+ config: {methods: ["create"]},
223
+ options: {
224
+ allowAnonymous: true,
225
+ permissions: {
226
+ create: [Permissions.IsAny],
227
+ delete: [],
228
+ list: [],
229
+ read: [],
230
+ update: [],
231
+ },
232
+ },
233
+ });
234
+ const [tool] = generateToolsForEntry(entry);
235
+
236
+ const logs = await captureLogs(async () => {
237
+ const result = await tool.handler({});
238
+ expect(result.isError).toBe(true);
239
+ expect(result.content[0].text).toContain("Create failed");
240
+ expect(result.content[0].text).not.toContain("ValidationError:");
241
+ expect(Object.keys(result)).toEqual(["content", "isError"]);
242
+ });
243
+
244
+ expect(logs.some((line) => line.level === "error" && line.message.includes("Caught:"))).toBe(
245
+ true
246
+ );
247
+ expect(logs.some((line) => line.message.includes("MCP tool call failed"))).toBe(true);
248
+ expect(captureException).toHaveBeenCalledTimes(1);
249
+ expect(captureException.mock.calls[0][0]).toBeInstanceOf(Error);
250
+ });
251
+ });
252
+
253
+ describe("tool pluralization", () => {
254
+ it("pluralizes normal names", () => {
255
+ const entry = createEntry({config: {methods: ["list"]}});
256
+ const tools = generateToolsForEntry(entry);
257
+ // MCPToolGenTest -> mcptoolgentests
258
+ expect(tools[0].name).toContain("mcptoolgentests");
259
+ });
260
+
261
+ it("adds -es to sibilant endings", () => {
262
+ const entry = createEntry({config: {methods: ["list"]}, modelName: "Status"});
263
+ const tools = generateToolsForEntry(entry);
264
+
265
+ expect(tools[0].name).toBe("statuses_list");
266
+ });
267
+
268
+ it("adds -ies to consonant-y endings", () => {
269
+ const entry = createEntry({config: {methods: ["list"]}, modelName: "Category"});
270
+ const tools = generateToolsForEntry(entry);
271
+
272
+ expect(tools[0].name).toBe("categories_list");
273
+ });
274
+
275
+ it("lets toolPrefix override an irregular plural", () => {
276
+ const entry = createEntry({
277
+ config: {methods: ["list"], toolPrefix: "people"},
278
+ modelName: "Person",
279
+ });
280
+ const tools = generateToolsForEntry(entry);
281
+
282
+ expect(tools[0].name).toBe("people_list");
283
+ });
284
+ });
@@ -0,0 +1,199 @@
1
+ import {toJSONSchema, type ZodType} from "zod";
2
+
3
+ import type {User} from "../auth";
4
+ import {createScopedLogger} from "../logger";
5
+ import {setRequestContext} from "../requestContext";
6
+ import {
7
+ getMCPErrorCause,
8
+ handleCreate,
9
+ handleDelete,
10
+ handleList,
11
+ handleRead,
12
+ handleUpdate,
13
+ } from "./handlers";
14
+ import {getMCPCustomTools, getMCPRegistry} from "./registry";
15
+ import {
16
+ generateInputSchema,
17
+ generateToolDescription,
18
+ restWriteExcludeFields,
19
+ } from "./schemaGenerator";
20
+ import type {
21
+ MCPMethod,
22
+ MCPRegistryEntry,
23
+ MCPToolArgs,
24
+ MCPToolInputSchema,
25
+ MCPToolResult,
26
+ } from "./types";
27
+
28
+ export interface MCPToolDefinition {
29
+ name: string;
30
+ description: string;
31
+ inputSchema: MCPToolInputSchema;
32
+ zodSchema: ZodType;
33
+ handler: (args: MCPToolArgs, user?: User) => Promise<MCPToolResult>;
34
+ }
35
+
36
+ const getToolPrefix = (entry: MCPRegistryEntry): string => {
37
+ if (entry.config.toolPrefix) {
38
+ return entry.config.toolPrefix;
39
+ }
40
+ // Default: lowercase model name with simple pluralization. Irregular nouns are expected
41
+ // to set config.toolPrefix rather than growing an exception list here.
42
+ const name = entry.modelName.toLowerCase();
43
+ if (/(?:s|x|z|ch|sh)$/.test(name)) {
44
+ return `${name}es`;
45
+ }
46
+ if (name.endsWith("y") && !/[aeiou]y$/i.test(name)) {
47
+ return `${name.slice(0, -1)}ies`;
48
+ }
49
+ return `${name}s`;
50
+ };
51
+
52
+ const METHOD_HANDLERS: Record<
53
+ MCPMethod,
54
+ (entry: MCPRegistryEntry, args: MCPToolArgs, user?: User) => Promise<MCPToolResult>
55
+ > = {
56
+ create: handleCreate,
57
+ delete: handleDelete,
58
+ list: handleList,
59
+ read: handleRead,
60
+ update: handleUpdate,
61
+ };
62
+
63
+ const getToolErrorMessage = (result: MCPToolResult): string => {
64
+ const text = result.content[0]?.text;
65
+ if (!text) {
66
+ return "Unknown MCP tool error";
67
+ }
68
+ try {
69
+ const parsed = JSON.parse(text) as {error?: unknown};
70
+ return typeof parsed.error === "string" ? parsed.error : text;
71
+ } catch {
72
+ return text;
73
+ }
74
+ };
75
+
76
+ const executeTool = async ({
77
+ args,
78
+ entry,
79
+ handler,
80
+ method,
81
+ toolName,
82
+ user,
83
+ }: {
84
+ args: MCPToolArgs;
85
+ entry: MCPRegistryEntry;
86
+ handler: (entry: MCPRegistryEntry, args: MCPToolArgs, user?: User) => Promise<MCPToolResult>;
87
+ method: MCPMethod;
88
+ toolName: string;
89
+ user?: User;
90
+ }): Promise<MCPToolResult> => {
91
+ const userId = user?.id ?? (user?._id ? String(user._id) : undefined);
92
+ if (userId) {
93
+ setRequestContext({userId});
94
+ }
95
+ const log = createScopedLogger({
96
+ labels: {
97
+ mcpMethod: method,
98
+ mcpModel: entry.modelName,
99
+ mcpTool: toolName,
100
+ },
101
+ prefix: "[MCPTool]",
102
+ });
103
+ const startedAt = performance.now();
104
+
105
+ try {
106
+ const result = await handler(entry, args, user);
107
+ const durationMs = Math.round(performance.now() - startedAt);
108
+ if (!result.isError) {
109
+ log.info("MCP tool call succeeded", {durationMs});
110
+ return result;
111
+ }
112
+
113
+ const cause = getMCPErrorCause(result);
114
+ const message = getToolErrorMessage(result);
115
+ if (cause !== undefined) {
116
+ // ScopedLogger.catch records the original exception and captures it in Sentry when enabled.
117
+ log.catch(cause);
118
+ log.error("MCP tool call failed", {durationMs, message});
119
+ } else {
120
+ // Permission, not-found, and input errors are expected failures: retain an audit trail
121
+ // and Sentry log without reporting them as exceptions.
122
+ log.warn("MCP tool call refused", {durationMs, message});
123
+ }
124
+ return result;
125
+ } catch (error) {
126
+ const durationMs = Math.round(performance.now() - startedAt);
127
+ log.catch(error);
128
+ log.error("MCP tool call crashed", {durationMs});
129
+ throw error;
130
+ }
131
+ };
132
+
133
+ export const generateToolsForEntry = (entry: MCPRegistryEntry): MCPToolDefinition[] => {
134
+ const methods = entry.config.methods ?? ["list", "read"];
135
+ const prefix = getToolPrefix(entry);
136
+ const tools: MCPToolDefinition[] = [];
137
+
138
+ for (const method of methods) {
139
+ // Skip methods with empty permission arrays (disabled)
140
+ if (entry.options.permissions[method]?.length === 0) {
141
+ continue;
142
+ }
143
+
144
+ const restExcludeFields = restWriteExcludeFields(method, entry.options.validation);
145
+ const zodSchema = generateInputSchema(
146
+ entry.model,
147
+ method,
148
+ entry.config,
149
+ entry.options.queryFields,
150
+ entry.options.populatePaths,
151
+ restExcludeFields
152
+ );
153
+
154
+ const inputSchema = toJSONSchema(zodSchema);
155
+
156
+ const handler = METHOD_HANDLERS[method];
157
+ const toolName = `${prefix}_${method}`;
158
+
159
+ tools.push({
160
+ description: generateToolDescription(
161
+ entry.model,
162
+ method,
163
+ entry.config,
164
+ entry.options.queryFields,
165
+ entry.options.populatePaths,
166
+ restExcludeFields
167
+ ),
168
+ handler: (args: MCPToolArgs, user?: User) =>
169
+ executeTool({args, entry, handler, method, toolName, user}),
170
+ inputSchema: inputSchema as MCPToolInputSchema,
171
+ name: toolName,
172
+ zodSchema,
173
+ });
174
+ }
175
+
176
+ return tools;
177
+ };
178
+
179
+ export const generateAllTools = (entries: MCPRegistryEntry[]): MCPToolDefinition[] => {
180
+ const tools: MCPToolDefinition[] = [];
181
+ for (const entry of entries) {
182
+ tools.push(...generateToolsForEntry(entry));
183
+ }
184
+ return tools;
185
+ };
186
+
187
+ /** Model-router tools plus any custom tools registered with `registerMCPTool`. */
188
+ export const getAllMCPTools = (): MCPToolDefinition[] => {
189
+ const customTools: MCPToolDefinition[] = getMCPCustomTools().map((tool) => {
190
+ return {
191
+ description: tool.description,
192
+ handler: tool.handler,
193
+ inputSchema: toJSONSchema(tool.zodSchema) as MCPToolInputSchema,
194
+ name: tool.name,
195
+ zodSchema: tool.zodSchema,
196
+ };
197
+ });
198
+ return [...generateAllTools(getMCPRegistry()), ...customTools];
199
+ };
@@ -0,0 +1,95 @@
1
+ import type {HydratedDocument, Model} from "mongoose";
2
+
3
+ import type {JSONValue, ModelRouterOptions} from "../api";
4
+ import type {User} from "../auth";
5
+
6
+ export type MCPMethod = "create" | "list" | "read" | "update" | "delete";
7
+
8
+ /** Arguments an MCP client sends for a tool call, validated against the tool's Zod schema. */
9
+ export type MCPToolArgs = Record<string, unknown>;
10
+
11
+ /**
12
+ * The MCP content payload returned by every tool handler. The index signature keeps this
13
+ * structurally compatible with the MCP SDK's CallToolResult, which allows extra fields.
14
+ */
15
+ export interface MCPToolResult {
16
+ content: Array<{type: "text"; text: string}>;
17
+ isError?: boolean;
18
+ [key: string]: unknown;
19
+ }
20
+
21
+ /** JSON Schema emitted for a tool's inputs, as sent to MCP clients. */
22
+ export interface MCPToolInputSchema {
23
+ type?: string;
24
+ properties?: Record<string, unknown>;
25
+ required?: string[];
26
+ [key: string]: unknown;
27
+ }
28
+
29
+ /**
30
+ * A hydrated document from a consumer's model. The concrete field types are only known
31
+ * at runtime, so handlers work against the Mongoose document API plus an index signature.
32
+ */
33
+ export type MCPDocument = HydratedDocument<Record<string, unknown>>;
34
+
35
+ /**
36
+ * Express-shaped request handed to modelRouter lifecycle hooks and response handlers
37
+ * during an MCP tool call. Built by `createMCPRequest` as a stub: only `user`
38
+ * and `body` are populated. `headers`, `query`, and `params` are always empty
39
+ * objects — MCP does not forward HTTP request fields.
40
+ */
41
+ export interface MCPRequest {
42
+ body: MCPToolArgs;
43
+ /** Always `{}` on MCP paths — not forwarded from HTTP. */
44
+ headers: Record<string, string>;
45
+ /** Lets hooks detect an MCP tool call rather than an HTTP request. */
46
+ isMCPRequest: true;
47
+ method: "MCP";
48
+ params: Record<string, string>;
49
+ query: Record<string, unknown>;
50
+ user?: User;
51
+ }
52
+
53
+ export interface MCPConfig {
54
+ /** Which CRUD methods to expose as MCP tools. Default: ['list', 'read'] */
55
+ methods?: MCPMethod[];
56
+ /** Override auto-generated model description */
57
+ description?: string;
58
+ /**
59
+ * Override the tool name prefix. Tools are named `{prefix}_{method}`, e.g. `todos_list`.
60
+ *
61
+ * Defaults to the lowercase model name run through a simple English pluralizer, which
62
+ * gets common cases right (`Todo` -> `todos`, `Category` -> `categories`, `Status` ->
63
+ * `statuses`) but not irregular nouns. Set this explicitly whenever the default reads
64
+ * wrong, or to namespace tools that would otherwise collide.
65
+ *
66
+ * @example
67
+ * ```typescript
68
+ * mcp: {toolPrefix: "people"} // person_list -> people_list
69
+ * ```
70
+ */
71
+ toolPrefix?: string;
72
+ /**
73
+ * Fields to hide from MCP tool schemas, responses, and create/update persist bodies.
74
+ *
75
+ * A bare field name (`"hash"`) is removed at every depth of the response, including
76
+ * inside arrays and populated refs, so a redacted name cannot leak through a nested
77
+ * document. Use dot notation (`"metadata.secretKey"`) to remove one specific location.
78
+ */
79
+ excludeFields?: string[];
80
+ /** Max items returned by list tool (default: 50) */
81
+ maxLimit?: number;
82
+ /** MCP-specific serialization (separate from REST responseHandler) */
83
+ mcpResponseHandler?: (value: unknown, method: MCPMethod, user?: User) => Promise<JSONValue>;
84
+ }
85
+
86
+ export interface MCPRegistryEntry {
87
+ modelName: string;
88
+ // noExplicitAny: Mongoose's invariant generics require any to accept arbitrary consumer models
89
+ // biome-ignore lint/suspicious/noExplicitAny: Mongoose's invariant generics require any to accept arbitrary consumer models
90
+ model: Model<any>;
91
+ config: MCPConfig;
92
+ // noExplicitAny: ModelRouterOptions is generic over the consumer's document type
93
+ // biome-ignore lint/suspicious/noExplicitAny: ModelRouterOptions is generic over the consumer's document type
94
+ options: ModelRouterOptions<any>;
95
+ }
@@ -434,6 +434,113 @@ describe("openApi middleware no-op paths", () => {
434
434
  expect(mw.length).toBe(3);
435
435
  });
436
436
 
437
+ it("listOpenApiMiddleware emits x-terreno-sync when sync is configured", () => {
438
+ let captured: Record<string, unknown> | undefined;
439
+ listOpenApiMiddleware(
440
+ FoodModel as any,
441
+ {
442
+ openApi: {
443
+ path: (spec: Record<string, unknown>) => {
444
+ captured = spec;
445
+ return (() => {}) as express.RequestHandler;
446
+ },
447
+ } as any,
448
+ permissions: {
449
+ create: [Permissions.IsAny],
450
+ delete: [Permissions.IsAny],
451
+ list: [Permissions.IsAny],
452
+ read: [Permissions.IsAny],
453
+ update: [Permissions.IsAny],
454
+ },
455
+ sync: {scope: {type: "owner"}},
456
+ },
457
+ "/food"
458
+ );
459
+ expect(captured?.["x-terreno-sync"]).toEqual({collection: "food", scope: "owner"});
460
+ });
461
+
462
+ it("listOpenApiMiddleware omits x-terreno-sync when sync is not configured", () => {
463
+ let captured: Record<string, unknown> | undefined;
464
+ listOpenApiMiddleware(FoodModel as any, {
465
+ openApi: {
466
+ path: (spec: Record<string, unknown>) => {
467
+ captured = spec;
468
+ return (() => {}) as express.RequestHandler;
469
+ },
470
+ } as any,
471
+ permissions: {
472
+ create: [Permissions.IsAny],
473
+ delete: [Permissions.IsAny],
474
+ list: [Permissions.IsAny],
475
+ read: [Permissions.IsAny],
476
+ update: [Permissions.IsAny],
477
+ },
478
+ });
479
+ expect(captured?.["x-terreno-sync"]).toBeUndefined();
480
+ });
481
+
482
+ it("listOpenApiMiddleware falls back to the model collection name without routePath", () => {
483
+ let captured: Record<string, unknown> | undefined;
484
+ listOpenApiMiddleware(FoodModel as any, {
485
+ openApi: {
486
+ path: (spec: Record<string, unknown>) => {
487
+ captured = spec;
488
+ return (() => {}) as express.RequestHandler;
489
+ },
490
+ } as any,
491
+ permissions: {
492
+ create: [Permissions.IsAny],
493
+ delete: [Permissions.IsAny],
494
+ list: [Permissions.IsAny],
495
+ read: [Permissions.IsAny],
496
+ update: [Permissions.IsAny],
497
+ },
498
+ sync: {scope: {type: "owner"}},
499
+ });
500
+ expect(captured?.["x-terreno-sync"]).toEqual({
501
+ collection: FoodModel.collection.collectionName,
502
+ scope: "owner",
503
+ });
504
+ });
505
+
506
+ it("listOpenApiMiddleware maps tenant and custom sync scopes", () => {
507
+ let captured: Record<string, unknown> | undefined;
508
+ const capturePath = (spec: Record<string, unknown>): express.RequestHandler => {
509
+ captured = spec;
510
+ return (() => {}) as express.RequestHandler;
511
+ };
512
+ const baseOptions = {
513
+ openApi: {path: capturePath} as any,
514
+ permissions: {
515
+ create: [Permissions.IsAny],
516
+ delete: [Permissions.IsAny],
517
+ list: [Permissions.IsAny],
518
+ read: [Permissions.IsAny],
519
+ update: [Permissions.IsAny],
520
+ },
521
+ };
522
+
523
+ listOpenApiMiddleware(
524
+ FoodModel as any,
525
+ {
526
+ ...baseOptions,
527
+ sync: {scope: {field: "organizationId", type: "tenant"}},
528
+ },
529
+ "/projects"
530
+ );
531
+ expect(captured?.["x-terreno-sync"]).toEqual({collection: "projects", scope: "tenant"});
532
+
533
+ listOpenApiMiddleware(
534
+ FoodModel as any,
535
+ {
536
+ ...baseOptions,
537
+ sync: {scope: () => "workspace"},
538
+ },
539
+ "/notes"
540
+ );
541
+ expect(captured?.["x-terreno-sync"]).toEqual({collection: "notes", scope: "custom"});
542
+ });
543
+
437
544
  it("createOpenApiMiddleware returns noop when openApi not configured", () => {
438
545
  const mw = createOpenApiMiddleware(FoodModel as any, {});
439
546
  expect(mw.length).toBe(3);