@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,354 @@
1
+ import type {Model} from "mongoose";
2
+ import {type ZodType, z} from "zod";
3
+
4
+ import type {PopulatePath} from "../populate";
5
+ import type {MCPConfig, MCPMethod} from "./types";
6
+
7
+ const SYSTEM_FIELDS = new Set(["_id", "id", "__v", "created", "updated", "deleted"]);
8
+
9
+ /** Shown to the calling LLM so it knows filters accept Mongo comparison operators. */
10
+ const OPERATOR_HINT = `{"$in": [...]} or {"$gte": ...}`;
11
+
12
+ /** Operators an LLM may use in a list filter, kept in sync with ALLOWED_FIELD_OPERATORS. */
13
+ const DOCUMENTED_FIELD_OPERATORS = "$eq, $ne, $gt, $gte, $lt, $lte, $in, $nin, $exists, $regex";
14
+
15
+ /** The subset of Mongoose SchemaType internals used to derive MCP tool schemas. */
16
+ interface MongooseSchemaPath {
17
+ caster?: {instance?: string; options?: {description?: string; ref?: string}};
18
+ enumValues?: string[];
19
+ instance?: string;
20
+ isRequired?: boolean;
21
+ options?: {description?: string; ref?: string};
22
+ schema?: unknown;
23
+ }
24
+
25
+ interface ModelField {
26
+ path: string;
27
+ schemaPath: MongooseSchemaPath;
28
+ required: boolean;
29
+ description?: string;
30
+ }
31
+
32
+ const mongooseTypeToZod = (schemaPath: MongooseSchemaPath): ZodType => {
33
+ const instance = schemaPath.instance;
34
+
35
+ switch (instance) {
36
+ case "String":
37
+ if (schemaPath.enumValues?.length) {
38
+ const values = schemaPath.enumValues as string[];
39
+ return z.enum(values as [string, ...string[]]);
40
+ }
41
+ return z.string();
42
+ case "Number":
43
+ return z.number();
44
+ case "Boolean":
45
+ return z.boolean();
46
+ case "Date":
47
+ return z.string().describe("ISO 8601 date string");
48
+ case "ObjectId":
49
+ case "ObjectID":
50
+ return z
51
+ .string()
52
+ .describe(
53
+ schemaPath.options?.ref ? `ObjectId reference to ${schemaPath.options.ref}` : "ObjectId"
54
+ );
55
+ case "Array": {
56
+ if (schemaPath.schema) {
57
+ // Array of subdocuments
58
+ return z.array(z.record(z.string(), z.any())).describe("Array of subdocuments");
59
+ }
60
+ // Array of primitives
61
+ const caster = schemaPath.caster;
62
+ if (caster) {
63
+ const innerType = mongooseTypeToZod({
64
+ instance: caster.instance,
65
+ options: caster.options,
66
+ });
67
+ return z.array(innerType);
68
+ }
69
+ return z.array(z.any());
70
+ }
71
+ case "Mixed":
72
+ case "Map":
73
+ return z.record(z.string(), z.any());
74
+ case "Embedded":
75
+ return z.record(z.string(), z.any()).describe("Embedded document");
76
+ default:
77
+ return z.any();
78
+ }
79
+ };
80
+
81
+ export const isFieldExcluded = (fieldPath: string, excludeFields: string[]): boolean => {
82
+ return excludeFields.some((excluded) => {
83
+ if (fieldPath === excluded) {
84
+ return true;
85
+ }
86
+ // Support dot-notation parent matching: excluding "metadata" excludes "metadata.secretKey"
87
+ if (fieldPath.startsWith(`${excluded}.`)) {
88
+ return true;
89
+ }
90
+ return false;
91
+ });
92
+ };
93
+
94
+ /**
95
+ * REST write denylist from `validation.excludeFromCreate` / `excludeFromUpdate`.
96
+ * MCP create/update must apply the same keys REST strips in `validateModelRequestBody`.
97
+ */
98
+ export const restWriteExcludeFields = (method: MCPMethod, validation: unknown): string[] => {
99
+ if (typeof validation !== "object" || validation === null) {
100
+ return [];
101
+ }
102
+ const options = validation as {
103
+ excludeFromCreate?: string[];
104
+ excludeFromUpdate?: string[];
105
+ };
106
+ if (method === "create") {
107
+ return options.excludeFromCreate ?? [];
108
+ }
109
+ if (method === "update") {
110
+ return options.excludeFromUpdate ?? [];
111
+ }
112
+ return [];
113
+ };
114
+
115
+ /** MCP `excludeFields` plus REST write denylist — used for tool schemas and persist. */
116
+ export const writeExcludeFields = (config: MCPConfig, restExcludeFields: string[]): string[] => {
117
+ return [...(config.excludeFields ?? []), ...restExcludeFields];
118
+ };
119
+
120
+ const getModelFields = (
121
+ // noExplicitAny: Mongoose's invariant generics require any to accept arbitrary consumer models
122
+ // biome-ignore lint/suspicious/noExplicitAny: Mongoose's invariant generics require any to accept arbitrary consumer models
123
+ model: Model<any>,
124
+ excludeFields: string[]
125
+ ): ModelField[] => {
126
+ const fields: ModelField[] = [];
127
+ const schemaPaths = model.schema.paths;
128
+
129
+ for (const [path, rawSchemaPath] of Object.entries(schemaPaths)) {
130
+ if (SYSTEM_FIELDS.has(path)) {
131
+ continue;
132
+ }
133
+ if (isFieldExcluded(path, excludeFields)) {
134
+ continue;
135
+ }
136
+
137
+ const schemaPath = rawSchemaPath as unknown as MongooseSchemaPath;
138
+ fields.push({
139
+ description: schemaPath.options?.description,
140
+ path,
141
+ required: Boolean(schemaPath.isRequired),
142
+ schemaPath,
143
+ });
144
+ }
145
+
146
+ return fields;
147
+ };
148
+
149
+ export const generateInputSchema = (
150
+ // noExplicitAny: Mongoose's invariant generics require any to accept arbitrary consumer models
151
+ // biome-ignore lint/suspicious/noExplicitAny: Mongoose's invariant generics require any to accept arbitrary consumer models
152
+ model: Model<any>,
153
+ method: MCPMethod,
154
+ config: MCPConfig,
155
+ queryFields?: string[],
156
+ populatePaths?: PopulatePath[],
157
+ restExcludeFields: string[] = []
158
+ ): ZodType => {
159
+ const excludeFields = writeExcludeFields(config, restExcludeFields);
160
+ const populatable = (populatePaths ?? []).map((populatePath) => populatePath.path);
161
+ // Only the model router's declared paths can be populated, so omit the parameter
162
+ // entirely when there are none rather than inviting a request that must be refused.
163
+ const populateParam = populatable.length
164
+ ? z
165
+ .string()
166
+ .optional()
167
+ .describe(`Comma-separated subset of the populate-able paths: ${populatable.join(", ")}`)
168
+ : undefined;
169
+
170
+ switch (method) {
171
+ case "create": {
172
+ const fields = getModelFields(model, excludeFields);
173
+ const shape: Record<string, ZodType> = {};
174
+ for (const field of fields) {
175
+ let zodType = mongooseTypeToZod(field.schemaPath);
176
+ if (field.description) {
177
+ zodType = zodType.describe(field.description);
178
+ }
179
+ shape[field.path] = field.required ? zodType : zodType.optional();
180
+ }
181
+ return z.object(shape);
182
+ }
183
+
184
+ case "update": {
185
+ const fields = getModelFields(model, excludeFields);
186
+ const shape: Record<string, ZodType> = {
187
+ id: z.string().describe("Document ID to update"),
188
+ };
189
+ for (const field of fields) {
190
+ let zodType = mongooseTypeToZod(field.schemaPath);
191
+ if (field.description) {
192
+ zodType = zodType.describe(field.description);
193
+ }
194
+ shape[field.path] = zodType.optional();
195
+ }
196
+ return z.object(shape);
197
+ }
198
+
199
+ case "read": {
200
+ const shape: Record<string, ZodType> = {
201
+ id: z.string().describe("Document ID to read"),
202
+ };
203
+ if (populateParam) {
204
+ shape.populate = populateParam;
205
+ }
206
+ return z.object(shape);
207
+ }
208
+
209
+ case "list": {
210
+ const shape: Record<string, ZodType> = {
211
+ limit: z
212
+ .number()
213
+ .optional()
214
+ .describe(`Max items to return (default: ${config.maxLimit ?? 50})`),
215
+ page: z.number().optional().describe("Page number (1-based)"),
216
+ sort: z.string().optional().describe("Sort field (prefix with - for descending)"),
217
+ };
218
+ if (populateParam) {
219
+ shape.populate = populateParam;
220
+ }
221
+ // Add queryFields as optional filter parameters
222
+ const filterableFields = (queryFields ?? []).filter(
223
+ (field) => !isFieldExcluded(field, excludeFields)
224
+ );
225
+ for (const field of filterableFields) {
226
+ shape[field] = z
227
+ .any()
228
+ .optional()
229
+ .describe(
230
+ `Filter by ${field}: an exact value or an operator object, e.g. ${OPERATOR_HINT}`
231
+ );
232
+ }
233
+ if (filterableFields.length) {
234
+ const logicalDescription = `Combine filters on ${filterableFields.join(", ")}, e.g. [{"${filterableFields[0]}": ...}]`;
235
+ shape.$and = z
236
+ .array(z.record(z.string(), z.any()))
237
+ .optional()
238
+ .describe(`Match all of these filters. ${logicalDescription}`);
239
+ shape.$or = z
240
+ .array(z.record(z.string(), z.any()))
241
+ .optional()
242
+ .describe(`Match any of these filters. ${logicalDescription}`);
243
+ }
244
+ return z.object(shape);
245
+ }
246
+
247
+ case "delete":
248
+ return z.object({
249
+ id: z.string().describe("Document ID to delete"),
250
+ });
251
+
252
+ default:
253
+ return z.object({});
254
+ }
255
+ };
256
+
257
+ const describeField = (field: ModelField): string => {
258
+ const parts = [field.path];
259
+ const instance = field.schemaPath.instance;
260
+
261
+ // Type info
262
+ if (instance === "ObjectId" || instance === "ObjectID") {
263
+ const ref = field.schemaPath.options?.ref;
264
+ parts.push(ref ? `(ref: ${ref})` : "(ObjectId)");
265
+ } else if (instance === "Array") {
266
+ if (field.schemaPath.caster?.instance) {
267
+ parts.push(`(${field.schemaPath.caster.instance}[])`);
268
+ } else {
269
+ parts.push("(Array)");
270
+ }
271
+ } else if (instance === "String" && field.schemaPath.enumValues?.length) {
272
+ parts.push(`(enum: ${field.schemaPath.enumValues.join("|")})`);
273
+ } else {
274
+ parts.push(`(${instance})`);
275
+ }
276
+
277
+ if (field.required) {
278
+ parts.push("required");
279
+ }
280
+
281
+ return parts.join(" ");
282
+ };
283
+
284
+ export const generateToolDescription = (
285
+ // noExplicitAny: Mongoose's invariant generics require any to accept arbitrary consumer models
286
+ // biome-ignore lint/suspicious/noExplicitAny: Mongoose's invariant generics require any to accept arbitrary consumer models
287
+ model: Model<any>,
288
+ method: MCPMethod,
289
+ config: MCPConfig,
290
+ queryFields?: string[],
291
+ populatePaths?: PopulatePath[],
292
+ restExcludeFields: string[] = []
293
+ ): string => {
294
+ if (config.description) {
295
+ const methodPrefix = `${method.charAt(0).toUpperCase()}${method.slice(1)}`;
296
+ return `${methodPrefix}: ${config.description}`;
297
+ }
298
+
299
+ const modelName = model.modelName;
300
+ const excludeFields = writeExcludeFields(config, restExcludeFields);
301
+ const maxLimit = config.maxLimit ?? 50;
302
+
303
+ switch (method) {
304
+ case "list": {
305
+ const parts = [`List ${modelName} items.`];
306
+ const availableQueryFields = queryFields?.filter((f) => !isFieldExcluded(f, excludeFields));
307
+ if (availableQueryFields?.length) {
308
+ parts.push(`Filterable by: ${availableQueryFields.join(", ")}.`);
309
+ parts.push(
310
+ `Filters accept an exact value or an operator object (${DOCUMENTED_FIELD_OPERATORS}), and can be combined with $and/$or.`
311
+ );
312
+ }
313
+ parts.push(`Sortable. Paginated (max ${maxLimit}).`);
314
+ return parts.join(" ");
315
+ }
316
+ case "read": {
317
+ const parts = [`Read a single ${modelName} by ID.`];
318
+ // Only the model router's declared paths can be populated, so advertising every ref
319
+ // field would point the model at requests that are refused.
320
+ const fields = getModelFields(model, excludeFields);
321
+ const refFields = (populatePaths ?? [])
322
+ .map((populatePath) => fields.find((field) => field.path === populatePath.path))
323
+ .filter((field): field is ModelField => Boolean(field?.schemaPath.options?.ref));
324
+ if (refFields.length) {
325
+ parts.push(
326
+ `Populate-able refs: ${refFields.map((f) => `${f.path} (${f.schemaPath.options?.ref})`).join(", ")}.`
327
+ );
328
+ }
329
+ return parts.join(" ");
330
+ }
331
+ case "create": {
332
+ const fields = getModelFields(model, excludeFields);
333
+ const parts = [`Create a new ${modelName}.`];
334
+ const fieldDescs = fields.map(describeField);
335
+ if (fieldDescs.length) {
336
+ parts.push(`Fields: ${fieldDescs.join(", ")}.`);
337
+ }
338
+ return parts.join(" ");
339
+ }
340
+ case "update": {
341
+ const fields = getModelFields(model, excludeFields);
342
+ const parts = [`Update an existing ${modelName} by ID. Send only the fields to change.`];
343
+ const fieldNames = fields.map((f) => f.path);
344
+ if (fieldNames.length) {
345
+ parts.push(`Updatable fields: ${fieldNames.join(", ")}.`);
346
+ }
347
+ return parts.join(" ");
348
+ }
349
+ case "delete":
350
+ return `Delete a ${modelName} by ID.`;
351
+ default:
352
+ return `${method} on ${modelName}`;
353
+ }
354
+ };
@@ -0,0 +1,226 @@
1
+ import {beforeEach, describe, expect, it} from "bun:test";
2
+ import type {Server as HttpServer} from "node:http";
3
+ import type {AddressInfo} from "node:net";
4
+ import {Client, StreamableHTTPClientTransport} from "@modelcontextprotocol/client";
5
+ import express from "express";
6
+ import mongoose, {Schema} from "mongoose";
7
+ import supertest from "supertest";
8
+
9
+ import type {UserModel} from "../auth";
10
+ import {Permissions} from "../permissions";
11
+ import {clearMCPRegistry, registerMCPModel} from "./registry";
12
+ import {mountMCPServer} from "./server";
13
+
14
+ interface MCPServerDocFields {
15
+ _id: mongoose.Types.ObjectId;
16
+ title?: string;
17
+ }
18
+
19
+ const getModel = (name: string, schema: Schema): mongoose.Model<MCPServerDocFields> => {
20
+ try {
21
+ return mongoose.model<MCPServerDocFields>(name);
22
+ } catch {
23
+ return mongoose.model<MCPServerDocFields>(name, schema);
24
+ }
25
+ };
26
+
27
+ const NoteModel = getModel(
28
+ "MCPServerNote",
29
+ new Schema({title: {description: "Note title", type: String}})
30
+ );
31
+ const userModel = getModel(
32
+ "MCPServerUser",
33
+ new Schema({email: {type: String}})
34
+ ) as unknown as UserModel;
35
+
36
+ const registerNoteModel = (): void => {
37
+ registerMCPModel(
38
+ NoteModel,
39
+ {methods: ["list", "read"]},
40
+ {
41
+ permissions: {
42
+ create: [Permissions.IsAuthenticated],
43
+ delete: [],
44
+ list: [Permissions.IsAuthenticated],
45
+ read: [Permissions.IsAuthenticated],
46
+ update: [Permissions.IsAuthenticated],
47
+ },
48
+ queryFields: ["title"],
49
+ }
50
+ );
51
+ };
52
+
53
+ const buildApp = (): express.Application => {
54
+ const app = express();
55
+ app.use(express.json());
56
+ mountMCPServer(app, {userModel});
57
+ return app;
58
+ };
59
+
60
+ const listen = async (
61
+ app: express.Application
62
+ ): Promise<{baseURL: string; close: () => Promise<void>}> => {
63
+ const server = await new Promise<HttpServer>((resolve) => {
64
+ const listener = app.listen(0, () => resolve(listener));
65
+ });
66
+ const address = server.address() as AddressInfo;
67
+ return {
68
+ baseURL: `http://127.0.0.1:${address.port}`,
69
+ close: async (): Promise<void> => {
70
+ await new Promise<void>((resolve, reject) => {
71
+ server.close((error) => {
72
+ if (error) {
73
+ reject(error);
74
+ return;
75
+ }
76
+ resolve();
77
+ });
78
+ });
79
+ },
80
+ };
81
+ };
82
+
83
+ const initializeBody = {
84
+ id: 1,
85
+ jsonrpc: "2.0",
86
+ method: "initialize",
87
+ params: {
88
+ capabilities: {},
89
+ clientInfo: {name: "test-client", version: "1.0.0"},
90
+ protocolVersion: "2024-11-05",
91
+ },
92
+ };
93
+
94
+ describe("mountMCPServer", () => {
95
+ beforeEach(() => {
96
+ clearMCPRegistry();
97
+ });
98
+
99
+ it("does not mount any routes when no models opt in", async () => {
100
+ const app = buildApp();
101
+
102
+ const res = await supertest(app).post("/mcp").send(initializeBody);
103
+
104
+ expect(res.status).toBe(404);
105
+ });
106
+
107
+ it("serves an initialize handshake when a model opts in", async () => {
108
+ registerNoteModel();
109
+ const app = buildApp();
110
+
111
+ const res = await supertest(app)
112
+ .post("/mcp")
113
+ .set("accept", "application/json, text/event-stream")
114
+ .send(initializeBody);
115
+
116
+ expect(res.status).toBe(200);
117
+ expect(res.text).toContain("terreno-api-mcp");
118
+ });
119
+
120
+ it("lists the generated tools", async () => {
121
+ registerNoteModel();
122
+ const app = buildApp();
123
+
124
+ const res = await supertest(app)
125
+ .post("/mcp")
126
+ .set("accept", "application/json, text/event-stream")
127
+ .send({id: 2, jsonrpc: "2.0", method: "tools/list", params: {}});
128
+
129
+ expect(res.text).toContain("mcpservernotes_list");
130
+ expect(res.text).toContain("mcpservernotes_read");
131
+ });
132
+
133
+ it("negotiates the 2026-07-28 protocol with the official v2 client", async () => {
134
+ registerNoteModel();
135
+ const server = await listen(buildApp());
136
+ const client = new Client(
137
+ {name: "terreno-api-test", version: "1.0.0"},
138
+ {versionNegotiation: {mode: "auto"}}
139
+ );
140
+
141
+ try {
142
+ await client.connect(new StreamableHTTPClientTransport(new URL(`${server.baseURL}/mcp`)));
143
+ const {tools} = await client.listTools();
144
+
145
+ expect(client.getProtocolEra()).toBe("modern");
146
+ expect(client.getNegotiatedProtocolVersion()).toBe("2026-07-28");
147
+ expect(tools.map((tool) => tool.name)).toContain("mcpservernotes_list");
148
+ expect(tools.map((tool) => tool.name)).toContain("mcpservernotes_read");
149
+ } finally {
150
+ await client.close();
151
+ await server.close();
152
+ }
153
+ });
154
+
155
+ it("invokes a tool handler with the user from the request headers", async () => {
156
+ await NoteModel.deleteMany({});
157
+ await NoteModel.create({title: "Visible note"});
158
+ registerNoteModel();
159
+ const app = buildApp();
160
+
161
+ const res = await supertest(app)
162
+ .post("/mcp")
163
+ .set("accept", "application/json, text/event-stream")
164
+ .send({
165
+ id: 3,
166
+ jsonrpc: "2.0",
167
+ method: "tools/call",
168
+ params: {arguments: {}, name: "mcpservernotes_list"},
169
+ });
170
+
171
+ // No credentials are sent, so the list permission check denies the call
172
+ expect(res.text).toContain("Permission denied");
173
+ });
174
+
175
+ it("returns a JSON-RPC 405 for GET", async () => {
176
+ registerNoteModel();
177
+ const app = buildApp();
178
+
179
+ const res = await supertest(app).get("/mcp");
180
+
181
+ expect(res.status).toBe(405);
182
+ expect(res.body.error.message).toBe("Method not allowed.");
183
+ expect(res.body.jsonrpc).toBe("2.0");
184
+ });
185
+
186
+ it("returns a JSON-RPC 405 for DELETE", async () => {
187
+ registerNoteModel();
188
+ const app = buildApp();
189
+
190
+ const res = await supertest(app).delete("/mcp");
191
+
192
+ expect(res.status).toBe(405);
193
+ expect(res.body.error.code).toBe(-32000);
194
+ });
195
+
196
+ it("returns a JSON-RPC 405 for PATCH", async () => {
197
+ registerNoteModel();
198
+ const app = buildApp();
199
+
200
+ const res = await supertest(app).patch("/mcp").send({});
201
+
202
+ expect(res.status).toBe(405);
203
+ expect(res.body.error.code).toBe(-32000);
204
+ });
205
+
206
+ it("returns a JSON-RPC 405 for PUT", async () => {
207
+ registerNoteModel();
208
+ const app = buildApp();
209
+
210
+ const res = await supertest(app).put("/mcp").send({});
211
+
212
+ expect(res.status).toBe(405);
213
+ expect(res.body.error.code).toBe(-32000);
214
+ });
215
+
216
+ it("returns a JSON-RPC error body when the request cannot be handled", async () => {
217
+ registerNoteModel();
218
+ const app = buildApp();
219
+
220
+ // Missing the SSE accept header the streamable transport requires
221
+ const res = await supertest(app).post("/mcp").set("accept", "text/plain").send(initializeBody);
222
+
223
+ expect(res.status).toBeGreaterThanOrEqual(400);
224
+ expect(res.body.jsonrpc).toBe("2.0");
225
+ });
226
+ });
@@ -0,0 +1,86 @@
1
+ import {toNodeHandler} from "@modelcontextprotocol/node";
2
+ import {createMcpHandler, McpServer} from "@modelcontextprotocol/server";
3
+ import type {Application, Request, Response} from "express";
4
+
5
+ import type {UserModel} from "../auth";
6
+ import type {BetterAuthInstance} from "../betterAuthSetup";
7
+ import {logger} from "../logger";
8
+ import {setRequestContext} from "../requestContext";
9
+ import {extractUserFromHeaders, type MCPAuthContext} from "./auth";
10
+ import {getAllMCPTools, type MCPToolDefinition} from "./toolGenerator";
11
+
12
+ export interface MCPServerOptions {
13
+ userModel: UserModel;
14
+ betterAuth?: BetterAuthInstance;
15
+ }
16
+
17
+ export const mountMCPServer = (app: Application, options: MCPServerOptions): void => {
18
+ const tools = getAllMCPTools();
19
+ if (tools.length === 0) {
20
+ return;
21
+ }
22
+ const authContext: MCPAuthContext = {
23
+ betterAuth: options.betterAuth,
24
+ userModel: options.userModel,
25
+ };
26
+
27
+ logger.info(`Mounting MCP server with ${tools.length} tools at /mcp`);
28
+
29
+ // The 2026-07-28 handler is stateless: it creates one server per request and also serves
30
+ // 2025-era clients through the SDK's stateless legacy fallback.
31
+ const handler = createMcpHandler(
32
+ async ({requestInfo}) => {
33
+ const headers: Record<string, string> = {};
34
+ requestInfo?.headers.forEach((value, key) => {
35
+ headers[key] = value;
36
+ });
37
+ const user = await extractUserFromHeaders(headers, authContext);
38
+ if (user?.id) {
39
+ setRequestContext({userId: user.id});
40
+ }
41
+ return createMcpServerInstance(tools, user);
42
+ },
43
+ {
44
+ legacy: "stateless",
45
+ onerror: (error) => logger.catch(error),
46
+ responseMode: "auto",
47
+ }
48
+ );
49
+ const nodeHandler = toNodeHandler(handler);
50
+
51
+ app.all("/mcp", (req: Request, res: Response) => {
52
+ // express.json() consumed the request stream, so pass its parsed body explicitly.
53
+ void nodeHandler(req, res, req.body);
54
+ });
55
+ };
56
+
57
+ const createMcpServerInstance = (
58
+ tools: MCPToolDefinition[],
59
+ user?: Awaited<ReturnType<typeof extractUserFromHeaders>>
60
+ ): McpServer => {
61
+ const server = new McpServer(
62
+ {
63
+ name: "terreno-api-mcp",
64
+ version: "1.0.0",
65
+ },
66
+ {
67
+ capabilities: {
68
+ tools: {},
69
+ },
70
+ }
71
+ );
72
+
73
+ // Register each tool with the MCP server
74
+ for (const tool of tools) {
75
+ server.registerTool(
76
+ tool.name,
77
+ {
78
+ description: tool.description,
79
+ inputSchema: tool.zodSchema,
80
+ },
81
+ async (args: unknown) => tool.handler(args as Record<string, unknown>, user)
82
+ );
83
+ }
84
+
85
+ return server;
86
+ };