@terreno/ai 0.3.2

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 (81) hide show
  1. package/.claude/CLAUDE.local.md +208 -0
  2. package/.cursor/rules/00-root.mdc +342 -0
  3. package/.cursorrules +221 -0
  4. package/.github/copilot-instructions.md +337 -0
  5. package/AGENTS.md +337 -0
  6. package/biome.jsonc +20 -0
  7. package/bunfig.toml +3 -0
  8. package/dist/aiApp.d.ts +59 -0
  9. package/dist/aiApp.js +67 -0
  10. package/dist/index.d.ts +6 -0
  11. package/dist/index.js +23 -0
  12. package/dist/models/aiRequest.d.ts +2 -0
  13. package/dist/models/aiRequest.js +76 -0
  14. package/dist/models/aiRequest.test.d.ts +1 -0
  15. package/dist/models/aiRequest.test.js +187 -0
  16. package/dist/models/fileAttachment.d.ts +2 -0
  17. package/dist/models/fileAttachment.js +25 -0
  18. package/dist/models/fileAttachment.test.d.ts +1 -0
  19. package/dist/models/fileAttachment.test.js +217 -0
  20. package/dist/models/gptHistory.d.ts +2 -0
  21. package/dist/models/gptHistory.js +56 -0
  22. package/dist/models/gptHistory.test.d.ts +1 -0
  23. package/dist/models/gptHistory.test.js +336 -0
  24. package/dist/models/index.d.ts +3 -0
  25. package/dist/models/index.js +9 -0
  26. package/dist/routes/aiRequestsExplorer.d.ts +2 -0
  27. package/dist/routes/aiRequestsExplorer.js +153 -0
  28. package/dist/routes/files.d.ts +5 -0
  29. package/dist/routes/files.js +168 -0
  30. package/dist/routes/gpt.d.ts +2 -0
  31. package/dist/routes/gpt.js +593 -0
  32. package/dist/routes/gptHistories.d.ts +3 -0
  33. package/dist/routes/gptHistories.js +29 -0
  34. package/dist/routes/index.d.ts +5 -0
  35. package/dist/routes/index.js +13 -0
  36. package/dist/routes/mcp.d.ts +2 -0
  37. package/dist/routes/mcp.js +133 -0
  38. package/dist/routes/routes.test.d.ts +1 -0
  39. package/dist/routes/routes.test.js +303 -0
  40. package/dist/service/aiService.d.ts +24 -0
  41. package/dist/service/aiService.js +453 -0
  42. package/dist/service/aiService.test.d.ts +1 -0
  43. package/dist/service/aiService.test.js +367 -0
  44. package/dist/service/fileStorage.d.ts +24 -0
  45. package/dist/service/fileStorage.js +143 -0
  46. package/dist/service/index.d.ts +4 -0
  47. package/dist/service/index.js +15 -0
  48. package/dist/service/mcpService.d.ts +14 -0
  49. package/dist/service/mcpService.js +271 -0
  50. package/dist/service/prompts.d.ts +4 -0
  51. package/dist/service/prompts.js +14 -0
  52. package/dist/tests/bunSetup.d.ts +1 -0
  53. package/dist/tests/bunSetup.js +227 -0
  54. package/dist/types/index.d.ts +170 -0
  55. package/dist/types/index.js +7 -0
  56. package/package.json +55 -0
  57. package/src/aiApp.ts +110 -0
  58. package/src/index.ts +6 -0
  59. package/src/models/aiRequest.test.ts +101 -0
  60. package/src/models/aiRequest.ts +45 -0
  61. package/src/models/fileAttachment.test.ts +119 -0
  62. package/src/models/fileAttachment.ts +31 -0
  63. package/src/models/gptHistory.test.ts +209 -0
  64. package/src/models/gptHistory.ts +71 -0
  65. package/src/models/index.ts +3 -0
  66. package/src/routes/aiRequestsExplorer.ts +107 -0
  67. package/src/routes/files.ts +128 -0
  68. package/src/routes/gpt.ts +503 -0
  69. package/src/routes/gptHistories.ts +31 -0
  70. package/src/routes/index.ts +5 -0
  71. package/src/routes/mcp.ts +76 -0
  72. package/src/routes/routes.test.ts +168 -0
  73. package/src/service/aiService.test.ts +242 -0
  74. package/src/service/aiService.ts +269 -0
  75. package/src/service/fileStorage.ts +74 -0
  76. package/src/service/index.ts +9 -0
  77. package/src/service/mcpService.ts +120 -0
  78. package/src/service/prompts.ts +18 -0
  79. package/src/tests/bunSetup.ts +163 -0
  80. package/src/types/index.ts +224 -0
  81. package/tsconfig.json +31 -0
@@ -0,0 +1,503 @@
1
+ import {
2
+ APIError,
3
+ asyncHandler,
4
+ authenticateMiddleware,
5
+ createOpenApiBuilder,
6
+ logger,
7
+ } from "@terreno/api";
8
+ import type {Tool} from "ai";
9
+ import {stepCountIs, streamText} from "ai";
10
+ import type express from "express";
11
+ import type mongoose from "mongoose";
12
+
13
+ import {AIRequest} from "../models/aiRequest";
14
+ import {GptHistory} from "../models/gptHistory";
15
+ import {AIService} from "../service/aiService";
16
+ import type {GptHistoryPrompt, GptRouteOptions, MessageContentPart} from "../types";
17
+
18
+ const DEMO_RESPONSE =
19
+ "This is demo mode. To use AI features, paste your Gemini API key in Settings.";
20
+
21
+ /** Send a canned SSE demo response when no AI service is available. */
22
+ const sendDemoResponse = (res: express.Response, historyId?: string): void => {
23
+ res.setHeader("Content-Type", "text/event-stream");
24
+ res.setHeader("Cache-Control", "no-cache");
25
+ res.setHeader("Connection", "keep-alive");
26
+ res.write(`data: ${JSON.stringify({text: DEMO_RESPONSE})}\n\n`);
27
+ res.write(`data: ${JSON.stringify({done: true, ...(historyId ? {historyId} : {})})}\n\n`);
28
+ res.end();
29
+ };
30
+
31
+ /**
32
+ * Resolve the AIService for a request. Priority:
33
+ * 1. Per-request API key via `x-ai-api-key` header (creates a temporary AIService)
34
+ * 2. Pre-configured aiService from route options
35
+ * 3. undefined (triggers demo mode response)
36
+ */
37
+ const resolveAiService = (
38
+ req: express.Request,
39
+ options: GptRouteOptions,
40
+ modelId?: string
41
+ ): AIService | undefined => {
42
+ const perRequestKey = req.headers["x-ai-api-key"] as string | undefined;
43
+ if (perRequestKey && options.createModelFn) {
44
+ return new AIService({model: options.createModelFn(perRequestKey, modelId)});
45
+ }
46
+ return options.aiService;
47
+ };
48
+
49
+ export const addGptRoutes = (router: any, options: GptRouteOptions): void => {
50
+ const {mcpService, tools: routeTools, createRequestTools, toolChoice, maxSteps} = options;
51
+
52
+ router.post(
53
+ "/gpt/prompt",
54
+ [
55
+ authenticateMiddleware(),
56
+ createOpenApiBuilder(options.openApiOptions ?? {})
57
+ .withTags(["gpt"])
58
+ .withSummary("Stream a GPT chat response")
59
+ .withRequestBody({
60
+ attachments: {
61
+ items: {
62
+ properties: {
63
+ filename: {type: "string"},
64
+ mimeType: {type: "string"},
65
+ type: {type: "string"},
66
+ url: {type: "string"},
67
+ },
68
+ type: "object",
69
+ },
70
+ type: "array",
71
+ },
72
+ historyId: {type: "string"},
73
+ model: {type: "string"},
74
+ prompt: {type: "string"},
75
+ systemPrompt: {type: "string"},
76
+ })
77
+ .withResponse(200, {data: {type: "string"}})
78
+ .build(),
79
+ ],
80
+ asyncHandler(async (req: express.Request, res: express.Response) => {
81
+ const {prompt, historyId, systemPrompt, attachments, model: requestModel} = req.body;
82
+ const userId = (req as any).user?._id as mongoose.Types.ObjectId | undefined;
83
+
84
+ if (!prompt || typeof prompt !== "string") {
85
+ throw new APIError({status: 400, title: "prompt is required"});
86
+ }
87
+
88
+ // Resolve AI service (per-request key takes priority, then configured service)
89
+ const hasPerRequestKey = !!req.headers["x-ai-api-key"];
90
+ const hasCreateModelFn = !!options.createModelFn;
91
+ const hasConfiguredService = !!options.aiService;
92
+ logger.debug("Resolving AI service", {
93
+ hasConfiguredService,
94
+ hasCreateModelFn,
95
+ hasPerRequestKey,
96
+ });
97
+
98
+ const aiService = resolveAiService(req, options, requestModel);
99
+ if (!aiService) {
100
+ logger.debug("No AI service available, sending demo response");
101
+ return sendDemoResponse(res);
102
+ }
103
+
104
+ // Load or create history
105
+ let history;
106
+ if (historyId) {
107
+ history = await GptHistory.findById(historyId);
108
+ if (!history) {
109
+ throw new APIError({status: 404, title: "History not found"});
110
+ }
111
+ if (history.userId.toString() !== userId?.toString()) {
112
+ throw new APIError({status: 403, title: "Not authorized to access this history"});
113
+ }
114
+ } else {
115
+ history = new GptHistory({prompts: [], userId});
116
+ }
117
+
118
+ // Build content parts from attachments
119
+ const contentParts: MessageContentPart[] = [{text: prompt, type: "text"}];
120
+ if (attachments && Array.isArray(attachments)) {
121
+ for (const attachment of attachments) {
122
+ if (attachment.type === "image") {
123
+ contentParts.push({
124
+ mimeType: attachment.mimeType,
125
+ type: "image",
126
+ url: attachment.url,
127
+ });
128
+ } else if (attachment.type === "file") {
129
+ contentParts.push({
130
+ filename: attachment.filename,
131
+ mimeType: attachment.mimeType,
132
+ type: "file",
133
+ url: attachment.url,
134
+ });
135
+ }
136
+ }
137
+ }
138
+
139
+ // Add user prompt to history
140
+ const hasAttachments = contentParts.length > 1;
141
+ const userPrompt: GptHistoryPrompt = {
142
+ text: prompt,
143
+ type: "user",
144
+ ...(hasAttachments ? {content: contentParts} : {}),
145
+ };
146
+ history.prompts.push(userPrompt);
147
+
148
+ // Build messages from history using AIService helper
149
+ const messages = aiService.buildMessages(history.prompts);
150
+
151
+ // Some models (e.g. gemini-2.5-flash-image) don't support tool calling
152
+ const modelId = aiService.modelId;
153
+ const supportsTools = !modelId?.includes("image");
154
+
155
+ // Merge tools from route config, per-request tools, and MCP service
156
+ let allTools: Record<string, Tool> | undefined;
157
+ const requestTools = createRequestTools ? createRequestTools(req) : undefined;
158
+ if (supportsTools && (routeTools || requestTools || mcpService)) {
159
+ allTools = {...(routeTools ?? {}), ...(requestTools ?? {})};
160
+ if (mcpService) {
161
+ try {
162
+ const mcpTools = await mcpService.getTools();
163
+ Object.assign(allTools, mcpTools);
164
+ } catch {
165
+ // MCP tool discovery failure should not block the request
166
+ }
167
+ }
168
+ }
169
+
170
+ // Stream response via SSE
171
+ res.setHeader("Content-Type", "text/event-stream");
172
+ res.setHeader("Cache-Control", "no-cache");
173
+ res.setHeader("Connection", "keep-alive");
174
+
175
+ let fullResponse = "";
176
+ const generatedImages: Array<{mimeType: string; url: string}> = [];
177
+ const startTime = Date.now();
178
+ try {
179
+ logger.debug("Starting streamText", {model: modelId, supportsTools});
180
+ const result = streamText({
181
+ messages,
182
+ model: (aiService as any).model,
183
+ providerOptions: !supportsTools
184
+ ? {google: {responseModalities: ["TEXT", "IMAGE"]}}
185
+ : undefined,
186
+ stopWhen: allTools ? stepCountIs(maxSteps ?? 5) : stepCountIs(1),
187
+ system: systemPrompt ?? undefined,
188
+ temperature: (aiService as any).defaultTemperature,
189
+ toolChoice: allTools ? (toolChoice ?? "auto") : undefined,
190
+ tools: allTools,
191
+ });
192
+
193
+ let partCount = 0;
194
+ // Buffer text per step so we can discard reasoning text when a tool call follows
195
+ let stepTextBuffer = "";
196
+ let stepHasToolCall = false;
197
+
198
+ for await (const part of result.fullStream as AsyncIterable<{
199
+ type: string;
200
+ [key: string]: any;
201
+ }>) {
202
+ partCount++;
203
+ if (partCount <= 5 || part.type === "error" || part.type === "file") {
204
+ logger.debug("Stream part", {
205
+ partCount,
206
+ type: part.type,
207
+ ...(part.type === "file" ? {mediaType: part.mediaType} : {}),
208
+ ...(part.type === "error" ? {error: String(part.error ?? part)} : {}),
209
+ });
210
+ }
211
+
212
+ // Track step boundaries to discard reasoning text from tool-call steps
213
+ if (part.type === "start-step") {
214
+ stepTextBuffer = "";
215
+ stepHasToolCall = false;
216
+ continue;
217
+ }
218
+ if (part.type === "finish-step") {
219
+ // Only emit buffered text if no tool call happened in this step
220
+ if (!stepHasToolCall && stepTextBuffer) {
221
+ // Strip model reasoning that leaks as JSON action blobs
222
+ const cleaned = stepTextBuffer
223
+ .replace(/\{[\s\S]*?"action"[\s\S]*?\}\s*$/g, "")
224
+ .trim();
225
+ if (cleaned) {
226
+ fullResponse += cleaned;
227
+ res.write(`data: ${JSON.stringify({text: cleaned})}\n\n`);
228
+ }
229
+ }
230
+ stepTextBuffer = "";
231
+ stepHasToolCall = false;
232
+ continue;
233
+ }
234
+
235
+ if (part.type === "error") {
236
+ const errMsg =
237
+ part.error instanceof Error
238
+ ? part.error.message
239
+ : String(part.error ?? "Unknown stream error");
240
+ logger.error("AI stream error part", {error: errMsg});
241
+ res.write(`data: ${JSON.stringify({error: errMsg})}\n\n`);
242
+ continue;
243
+ }
244
+ if (part.type === "file") {
245
+ const mediaType = part.mediaType as string | undefined;
246
+ if (mediaType?.startsWith("image/")) {
247
+ const dataUrl = `data:${mediaType};base64,${part.base64}`;
248
+ generatedImages.push({mimeType: mediaType, url: dataUrl});
249
+ res.write(
250
+ `data: ${JSON.stringify({image: {mimeType: mediaType, url: dataUrl}})}\n\n`
251
+ );
252
+ logger.debug("Sent inline image from stream");
253
+ }
254
+ continue;
255
+ }
256
+ if (part.type === "text-delta") {
257
+ const textChunk = (part.text ?? "") as string;
258
+ if (textChunk) {
259
+ stepTextBuffer += textChunk;
260
+ }
261
+ } else if (part.type === "tool-call") {
262
+ stepHasToolCall = true;
263
+ res.write(
264
+ `data: ${JSON.stringify({
265
+ toolCall: {
266
+ args: part.input,
267
+ toolCallId: part.toolCallId,
268
+ toolName: part.toolName,
269
+ },
270
+ })}\n\n`
271
+ );
272
+ // Persist tool call in history
273
+ history.prompts.push({
274
+ args: part.input as Record<string, unknown>,
275
+ text: `Tool call: ${part.toolName}`,
276
+ toolCallId: part.toolCallId,
277
+ toolName: part.toolName,
278
+ type: "tool-call",
279
+ });
280
+ } else if (part.type === "tool-result") {
281
+ const toolResult = part.output as Record<string, unknown> | undefined;
282
+
283
+ // If the tool result contains file data, send it as a separate file SSE event
284
+ if (toolResult?.fileData && typeof toolResult.fileData === "string") {
285
+ res.write(
286
+ `data: ${JSON.stringify({
287
+ file: {
288
+ filename: toolResult.filename ?? "document",
289
+ mimeType: toolResult.mimeType ?? "application/octet-stream",
290
+ url: toolResult.fileData,
291
+ },
292
+ })}\n\n`
293
+ );
294
+ logger.debug("Sent generated file from tool result", {
295
+ filename: toolResult.filename,
296
+ mimeType: toolResult.mimeType,
297
+ });
298
+ }
299
+
300
+ // Strip fileData from result before sending/storing to avoid bloating the SSE and DB
301
+ const {fileData: _fileData, ...cleanResult} = toolResult ?? {};
302
+
303
+ res.write(
304
+ `data: ${JSON.stringify({
305
+ toolResult: {
306
+ result: cleanResult,
307
+ toolCallId: part.toolCallId,
308
+ toolName: part.toolName,
309
+ },
310
+ })}\n\n`
311
+ );
312
+ // Persist tool result in history (without the large file data)
313
+ history.prompts.push({
314
+ result: cleanResult as unknown,
315
+ text: `Tool result: ${part.toolName}`,
316
+ toolCallId: part.toolCallId,
317
+ toolName: part.toolName,
318
+ type: "tool-result",
319
+ });
320
+ }
321
+ }
322
+
323
+ // Flush any remaining buffered text from the last step
324
+ if (!stepHasToolCall && stepTextBuffer) {
325
+ const cleaned = stepTextBuffer.replace(/\{[\s\S]*?"action"[\s\S]*?\}\s*$/g, "").trim();
326
+ if (cleaned) {
327
+ fullResponse += cleaned;
328
+ res.write(`data: ${JSON.stringify({text: cleaned})}\n\n`);
329
+ }
330
+ }
331
+
332
+ logger.debug("Stream completed", {fullResponseLength: fullResponse.length, partCount});
333
+
334
+ // Check for generated images (e.g. from gemini-2.5-flash-image)
335
+ try {
336
+ const files = await result.files;
337
+ if (files && files.length > 0) {
338
+ for (const file of files) {
339
+ if (file.mediaType.startsWith("image/")) {
340
+ const dataUrl = `data:${file.mediaType};base64,${file.base64}`;
341
+ generatedImages.push({mimeType: file.mediaType, url: dataUrl});
342
+ res.write(
343
+ `data: ${JSON.stringify({
344
+ image: {mimeType: file.mediaType, url: dataUrl},
345
+ })}\n\n`
346
+ );
347
+ }
348
+ }
349
+ logger.debug("Sent generated images", {count: files.length});
350
+ }
351
+ } catch (fileErr) {
352
+ logger.debug("No files in response", {
353
+ error: fileErr instanceof Error ? fileErr.message : String(fileErr),
354
+ });
355
+ }
356
+
357
+ // Save assistant response to history
358
+ if (fullResponse || generatedImages.length > 0) {
359
+ const contentParts: MessageContentPart[] = generatedImages.map((img) => ({
360
+ mimeType: img.mimeType,
361
+ type: "image" as const,
362
+ url: img.url,
363
+ }));
364
+ const assistantPrompt: GptHistoryPrompt = {
365
+ model: aiService.modelId,
366
+ text: fullResponse || "(image)",
367
+ type: "assistant",
368
+ ...(contentParts.length > 0 ? {content: contentParts} : {}),
369
+ };
370
+ history.prompts.push(assistantPrompt);
371
+ }
372
+ await history.save();
373
+
374
+ try {
375
+ await AIRequest.logRequest({
376
+ aiModel: modelId ?? "unknown",
377
+ prompt,
378
+ requestType: "general",
379
+ response: fullResponse,
380
+ responseTime: Date.now() - startTime,
381
+ userId: userId ?? undefined,
382
+ });
383
+ } catch (logErr) {
384
+ logger.warn("Failed to log AIRequest", {
385
+ error: logErr instanceof Error ? logErr.message : String(logErr),
386
+ });
387
+ }
388
+
389
+ logger.debug("Sending done event", {
390
+ fullResponseLength: fullResponse.length,
391
+ historyId: history._id.toString(),
392
+ });
393
+ res.write(`data: ${JSON.stringify({done: true, historyId: history._id.toString()})}\n\n`);
394
+ res.end();
395
+ } catch (error) {
396
+ logger.error("Error in GPT stream", {
397
+ error: error instanceof Error ? error.message : String(error),
398
+ });
399
+
400
+ try {
401
+ await AIRequest.logRequest({
402
+ aiModel: modelId ?? "unknown",
403
+ error: error instanceof Error ? error.message : String(error),
404
+ prompt,
405
+ requestType: "general",
406
+ responseTime: Date.now() - startTime,
407
+ userId: userId ?? undefined,
408
+ });
409
+ } catch (logErr) {
410
+ logger.warn("Failed to log AIRequest error", {
411
+ error: logErr instanceof Error ? logErr.message : String(logErr),
412
+ });
413
+ }
414
+
415
+ res.write(
416
+ `data: ${JSON.stringify({error: error instanceof Error ? error.message : "Unknown error"})}\n\n`
417
+ );
418
+ res.end();
419
+ }
420
+ })
421
+ );
422
+
423
+ router.patch(
424
+ "/gpt/histories/:id/rating",
425
+ [
426
+ authenticateMiddleware(),
427
+ createOpenApiBuilder(options.openApiOptions ?? {})
428
+ .withTags(["gpt"])
429
+ .withSummary("Rate a prompt in a GPT history")
430
+ .withPathParameter("id", {type: "string"})
431
+ .withRequestBody({
432
+ promptIndex: {type: "number"},
433
+ rating: {type: "string"},
434
+ })
435
+ .withResponse(200, {data: {type: "object"}})
436
+ .build(),
437
+ ],
438
+ asyncHandler(async (req: express.Request, res: express.Response) => {
439
+ const {id} = req.params;
440
+ const {promptIndex, rating} = req.body;
441
+ const userId = (req as any).user?._id as mongoose.Types.ObjectId | undefined;
442
+
443
+ if (typeof promptIndex !== "number" || promptIndex < 0) {
444
+ throw new APIError({status: 400, title: "promptIndex must be a non-negative number"});
445
+ }
446
+ if (rating !== null && rating !== "up" && rating !== "down") {
447
+ throw new APIError({status: 400, title: "rating must be 'up', 'down', or null"});
448
+ }
449
+
450
+ const history = await GptHistory.findById(id);
451
+ if (!history) {
452
+ throw new APIError({status: 404, title: "History not found"});
453
+ }
454
+ if (history.userId.toString() !== userId?.toString()) {
455
+ throw new APIError({status: 403, title: "Not authorized to access this history"});
456
+ }
457
+ if (promptIndex >= history.prompts.length) {
458
+ throw new APIError({status: 400, title: "promptIndex out of range"});
459
+ }
460
+
461
+ if (rating === null) {
462
+ history.prompts[promptIndex].rating = undefined;
463
+ } else {
464
+ history.prompts[promptIndex].rating = rating;
465
+ }
466
+ history.markModified("prompts");
467
+ await history.save();
468
+
469
+ return res.json({data: {promptIndex, rating: history.prompts[promptIndex].rating ?? null}});
470
+ })
471
+ );
472
+
473
+ router.post(
474
+ "/gpt/remix",
475
+ [
476
+ authenticateMiddleware(),
477
+ createOpenApiBuilder(options.openApiOptions ?? {})
478
+ .withTags(["gpt"])
479
+ .withSummary("Remix text")
480
+ .withRequestBody({
481
+ text: {type: "string"},
482
+ })
483
+ .withResponse(200, {data: {type: "string"}})
484
+ .build(),
485
+ ],
486
+ asyncHandler(async (req: express.Request, res: express.Response) => {
487
+ const {text} = req.body;
488
+ const userId = (req as any).user?._id as mongoose.Types.ObjectId | undefined;
489
+
490
+ if (!text || typeof text !== "string") {
491
+ throw new APIError({status: 400, title: "text is required"});
492
+ }
493
+
494
+ const aiService = resolveAiService(req, options);
495
+ if (!aiService) {
496
+ return res.json({data: DEMO_RESPONSE});
497
+ }
498
+
499
+ const result = await aiService.generateRemix({text, userId});
500
+ return res.json({data: result});
501
+ })
502
+ );
503
+ };
@@ -0,0 +1,31 @@
1
+ import {type ModelRouterOptions, modelRouter, Permissions} from "@terreno/api";
2
+ import {GptHistory} from "../models/gptHistory";
3
+ import type {GptHistoryDocument, GptHistoryRouteOptions} from "../types";
4
+
5
+ export const addGptHistoryRoutes = (
6
+ router: any,
7
+ options?: Partial<ModelRouterOptions<GptHistoryDocument>> & GptHistoryRouteOptions
8
+ ): void => {
9
+ router.use(
10
+ "/gpt/histories",
11
+ modelRouter(GptHistory, {
12
+ ...options,
13
+ permissions: {
14
+ create: [Permissions.IsAuthenticated],
15
+ delete: [Permissions.IsOwner],
16
+ list: [Permissions.IsAuthenticated],
17
+ read: [Permissions.IsOwner],
18
+ update: [Permissions.IsOwner],
19
+ },
20
+ preCreate: (body, req) => {
21
+ return {
22
+ ...body,
23
+ userId: (req.user as {_id: unknown})?._id,
24
+ } as GptHistoryDocument;
25
+ },
26
+ queryFields: ["userId"],
27
+ queryFilter: (user) => ({userId: user?.id}),
28
+ sort: "-updated",
29
+ })
30
+ );
31
+ };
@@ -0,0 +1,5 @@
1
+ export {addAiRequestsExplorerRoutes} from "./aiRequestsExplorer";
2
+ export {addFileRoutes} from "./files";
3
+ export {addGptRoutes} from "./gpt";
4
+ export {addGptHistoryRoutes} from "./gptHistories";
5
+ export {addMcpRoutes} from "./mcp";
@@ -0,0 +1,76 @@
1
+ import {APIError, asyncHandler, authenticateMiddleware, createOpenApiBuilder} from "@terreno/api";
2
+ import type express from "express";
3
+
4
+ import type {McpRouteOptions} from "../types";
5
+
6
+ export const addMcpRoutes = (router: any, options: McpRouteOptions): void => {
7
+ const {mcpService} = options;
8
+
9
+ router.get(
10
+ "/mcp/servers",
11
+ [
12
+ authenticateMiddleware(),
13
+ createOpenApiBuilder(options.openApiOptions ?? {})
14
+ .withTags(["mcp"])
15
+ .withSummary("List MCP servers and their status")
16
+ .withArrayResponse(200, {
17
+ connected: {type: "boolean"},
18
+ name: {type: "string"},
19
+ })
20
+ .build(),
21
+ ],
22
+ asyncHandler(async (req: express.Request, res: express.Response) => {
23
+ const user = (req as any).user;
24
+ if (!user?.admin) {
25
+ throw new APIError({status: 403, title: "Admin access required"});
26
+ }
27
+
28
+ const servers = mcpService.getServerStatus();
29
+ return res.json({data: servers});
30
+ })
31
+ );
32
+
33
+ router.get(
34
+ "/mcp/tools",
35
+ [
36
+ authenticateMiddleware(),
37
+ createOpenApiBuilder(options.openApiOptions ?? {})
38
+ .withTags(["mcp"])
39
+ .withSummary("List available MCP tools")
40
+ .withResponse(200, {tools: {items: {type: "object"}, type: "array"}})
41
+ .build(),
42
+ ],
43
+ asyncHandler(async (_req: express.Request, res: express.Response) => {
44
+ const tools = await mcpService.getTools();
45
+ const toolList = Object.entries(tools).map(([name, tool]) => ({
46
+ description: (tool as any).description,
47
+ name,
48
+ parameters: (tool as any).parameters,
49
+ }));
50
+ return res.json({data: toolList});
51
+ })
52
+ );
53
+
54
+ router.post(
55
+ "/mcp/servers/:name/reconnect",
56
+ [
57
+ authenticateMiddleware(),
58
+ createOpenApiBuilder(options.openApiOptions ?? {})
59
+ .withTags(["mcp"])
60
+ .withSummary("Reconnect an MCP server")
61
+ .withPathParameter("name", {type: "string"})
62
+ .withResponse(200, {connected: {type: "boolean"}, name: {type: "string"}})
63
+ .build(),
64
+ ],
65
+ asyncHandler(async (req: express.Request, res: express.Response) => {
66
+ const user = (req as any).user;
67
+ if (!user?.admin) {
68
+ throw new APIError({status: 403, title: "Admin access required"});
69
+ }
70
+
71
+ const {name} = req.params;
72
+ const connected = await mcpService.reconnectServer(name);
73
+ return res.json({data: {connected, name}});
74
+ })
75
+ );
76
+ };