@terreno/ai 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.
package/README.md CHANGED
@@ -36,6 +36,7 @@ This mounts GPT chat (`POST /gpt/prompt`), history CRUD (`/gpt/histories`), proj
36
36
  - `LangfuseApp` — optional Langfuse tracing and admin UI routes
37
37
  - `FileStorageService` — GCS uploads with signed URLs
38
38
  - `MCPService` — SSE MCP client for tool calling
39
+ - `getMCPTools` — wrap registered `modelRouter` MCP tools as Vercel AI SDK tools for in-process `streamText` / `generateText`
39
40
  - Gemini and Vertex helpers: `listGeminiApiModels`, `createVertexProvider`
40
41
 
41
42
  ## Documentation
@@ -0,0 +1,14 @@
1
+ import type { AdminContribution, TerrenoPlugin } from "@terreno/api";
2
+ import type express from "express";
3
+ export interface AIAdminAppOptions {
4
+ openApiOptions?: Record<string, unknown>;
5
+ }
6
+ /**
7
+ * Registers the AI request explorer API and contributes its admin screen metadata.
8
+ */
9
+ export declare class AIAdminApp implements TerrenoPlugin {
10
+ private options;
11
+ constructor(options?: AIAdminAppOptions);
12
+ adminContribution(): AdminContribution;
13
+ register(app: express.Application): void;
14
+ }
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AIAdminApp = void 0;
4
+ var aiRequestsExplorer_1 = require("./routes/aiRequestsExplorer");
5
+ /**
6
+ * Registers the AI request explorer API and contributes its admin screen metadata.
7
+ */
8
+ var AIAdminApp = /** @class */ (function () {
9
+ function AIAdminApp(options) {
10
+ if (options === void 0) { options = {}; }
11
+ this.options = options;
12
+ }
13
+ AIAdminApp.prototype.adminContribution = function () {
14
+ return {
15
+ customScreens: [{ displayName: "AI Requests", icon: "robot", name: "ai-requests" }],
16
+ };
17
+ };
18
+ AIAdminApp.prototype.register = function (app) {
19
+ (0, aiRequestsExplorer_1.addAiRequestsExplorerRoutes)(app, { openApiOptions: this.options.openApiOptions });
20
+ };
21
+ return AIAdminApp;
22
+ }());
23
+ exports.AIAdminApp = AIAdminApp;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  export type { FlexibleSchema, JSONValue } from "ai";
2
2
  export { jsonSchema, Output } from "ai";
3
+ export type { AIAdminAppOptions } from "./aiAdminApp";
4
+ export { AIAdminApp } from "./aiAdminApp";
3
5
  export type { AiAppOptions } from "./aiApp";
4
6
  export { AiApp } from "./aiApp";
5
7
  export { LangfuseApp } from "./langfuseApp";
@@ -23,6 +25,7 @@ export { AIService, TemperaturePresets } from "./service/aiService";
23
25
  export { FileStorageService } from "./service/fileStorage";
24
26
  export type { ListGeminiApiModelsOptions } from "./service/gemini";
25
27
  export { GEMINI_API_BASE_URL, listGeminiApiModels, normalizeGeminiModelId, } from "./service/gemini";
28
+ export { getMCPTools } from "./service/getMCPTools";
26
29
  export { MCPService } from "./service/mcpService";
27
30
  export type { ParseFailure, ParseResult, ParseSuccess } from "./service/parseAiJson";
28
31
  export { normalizeLlmJsonTextForStructuredOutput, parseAiJson, } from "./service/parseAiJson";
package/dist/index.js CHANGED
@@ -14,11 +14,13 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.listEnabledVertexModels = exports.isVertexModelAllowed = exports.DEFAULT_VERTEX_LOCATION = exports.createVertexProvider = exports.assertVertexModelsEnabled = exports.TRANSLATION_PROMPT = exports.TITLE_GENERATION_PROMPT = exports.REMIX_PROMPT = exports.JSON_VALUE_SYSTEM_PROMPT = exports.DEFAULT_GPT_MEMORY = exports.CONTENT_SUMMARY_PROMPT = exports.parseAiJson = exports.normalizeLlmJsonTextForStructuredOutput = exports.MCPService = exports.normalizeGeminiModelId = exports.listGeminiApiModels = exports.GEMINI_API_BASE_URL = exports.FileStorageService = exports.TemperaturePresets = exports.AIService = exports.addProjectRoutes = exports.addMcpRoutes = exports.addGptHistoryRoutes = exports.addGptRoutes = exports.addFileRoutes = exports.addAiRequestsExplorerRoutes = exports.Project = exports.GptHistory = exports.FileAttachment = exports.AIRequest = exports.preparePromptForAI = exports.createTelemetryConfig = exports.shutdownTracing = exports.initTracing = exports.invalidatePromptCache = exports.getPrompt = exports.createPrompt = exports.compilePrompt = exports.shutdownLangfuseClient = exports.isLangfuseInitialized = exports.initLangfuseClient = exports.getLangfuseClient = exports.setCached = exports.LangfuseCache = exports.invalidateCache = exports.getCached = exports.LangfuseApp = exports.AiApp = exports.Output = exports.jsonSchema = void 0;
18
- exports.verifyVertexModelsEnabled = exports.normalizeVertexModelId = void 0;
17
+ exports.DEFAULT_VERTEX_LOCATION = exports.createVertexProvider = exports.assertVertexModelsEnabled = exports.TRANSLATION_PROMPT = exports.TITLE_GENERATION_PROMPT = exports.REMIX_PROMPT = exports.JSON_VALUE_SYSTEM_PROMPT = exports.DEFAULT_GPT_MEMORY = exports.CONTENT_SUMMARY_PROMPT = exports.parseAiJson = exports.normalizeLlmJsonTextForStructuredOutput = exports.MCPService = exports.getMCPTools = exports.normalizeGeminiModelId = exports.listGeminiApiModels = exports.GEMINI_API_BASE_URL = exports.FileStorageService = exports.TemperaturePresets = exports.AIService = exports.addProjectRoutes = exports.addMcpRoutes = exports.addGptHistoryRoutes = exports.addGptRoutes = exports.addFileRoutes = exports.addAiRequestsExplorerRoutes = exports.Project = exports.GptHistory = exports.FileAttachment = exports.AIRequest = exports.preparePromptForAI = exports.createTelemetryConfig = exports.shutdownTracing = exports.initTracing = exports.invalidatePromptCache = exports.getPrompt = exports.createPrompt = exports.compilePrompt = exports.shutdownLangfuseClient = exports.isLangfuseInitialized = exports.initLangfuseClient = exports.getLangfuseClient = exports.setCached = exports.LangfuseCache = exports.invalidateCache = exports.getCached = exports.LangfuseApp = exports.AiApp = exports.AIAdminApp = exports.Output = exports.jsonSchema = void 0;
18
+ exports.verifyVertexModelsEnabled = exports.normalizeVertexModelId = exports.listEnabledVertexModels = exports.isVertexModelAllowed = void 0;
19
19
  var ai_1 = require("ai");
20
20
  Object.defineProperty(exports, "jsonSchema", { enumerable: true, get: function () { return ai_1.jsonSchema; } });
21
21
  Object.defineProperty(exports, "Output", { enumerable: true, get: function () { return ai_1.Output; } });
22
+ var aiAdminApp_1 = require("./aiAdminApp");
23
+ Object.defineProperty(exports, "AIAdminApp", { enumerable: true, get: function () { return aiAdminApp_1.AIAdminApp; } });
22
24
  var aiApp_1 = require("./aiApp");
23
25
  Object.defineProperty(exports, "AiApp", { enumerable: true, get: function () { return aiApp_1.AiApp; } });
24
26
  var langfuseApp_1 = require("./langfuseApp");
@@ -73,6 +75,8 @@ var gemini_1 = require("./service/gemini");
73
75
  Object.defineProperty(exports, "GEMINI_API_BASE_URL", { enumerable: true, get: function () { return gemini_1.GEMINI_API_BASE_URL; } });
74
76
  Object.defineProperty(exports, "listGeminiApiModels", { enumerable: true, get: function () { return gemini_1.listGeminiApiModels; } });
75
77
  Object.defineProperty(exports, "normalizeGeminiModelId", { enumerable: true, get: function () { return gemini_1.normalizeGeminiModelId; } });
78
+ var getMCPTools_1 = require("./service/getMCPTools");
79
+ Object.defineProperty(exports, "getMCPTools", { enumerable: true, get: function () { return getMCPTools_1.getMCPTools; } });
76
80
  var mcpService_1 = require("./service/mcpService");
77
81
  Object.defineProperty(exports, "MCPService", { enumerable: true, get: function () { return mcpService_1.MCPService; } });
78
82
  var parseAiJson_1 = require("./service/parseAiJson");
@@ -56,6 +56,18 @@ exports.addAiRequestsExplorerRoutes = void 0;
56
56
  var api_1 = require("@terreno/api");
57
57
  var luxon_1 = require("luxon");
58
58
  var aiRequest_1 = require("../models/aiRequest");
59
+ var parseRequestTypes = function (raw) {
60
+ if (Array.isArray(raw)) {
61
+ return raw.flatMap(function (item) { return parseRequestTypes(item); });
62
+ }
63
+ if (typeof raw !== "string") {
64
+ return [];
65
+ }
66
+ return raw
67
+ .split(",")
68
+ .map(function (token) { return token.trim(); })
69
+ .filter(function (token) { return token.length > 0; });
70
+ };
59
71
  var addAiRequestsExplorerRoutes = function (router, options) {
60
72
  var _a;
61
73
  router.get("/aiRequestsExplorer", [
@@ -78,7 +90,7 @@ var addAiRequestsExplorerRoutes = function (router, options) {
78
90
  })
79
91
  .build(),
80
92
  ], (0, api_1.asyncHandler)(function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
81
- var user, page, limit, skip, match, startDt, endDt, _a, results, totalCount;
93
+ var user, page, limit, skip, match, requestTypes, startDt, endDt, _a, results, totalCount;
82
94
  return __generator(this, function (_b) {
83
95
  switch (_b.label) {
84
96
  case 0:
@@ -92,8 +104,12 @@ var addAiRequestsExplorerRoutes = function (router, options) {
92
104
  match = {
93
105
  deleted: { $ne: true },
94
106
  };
95
- if (req.query.requestType) {
96
- match.requestType = req.query.requestType;
107
+ requestTypes = parseRequestTypes(req.query.requestType);
108
+ if (requestTypes.length === 1) {
109
+ match.requestType = requestTypes[0];
110
+ }
111
+ else if (requestTypes.length > 1) {
112
+ match.requestType = { $in: requestTypes };
97
113
  }
98
114
  if (req.query.model) {
99
115
  match.aiModel = req.query.model;
@@ -0,0 +1,7 @@
1
+ import { type User } from "@terreno/api";
2
+ import { type Tool } from "ai";
3
+ /**
4
+ * Returns all registered MCP tools as Vercel AI SDK tool objects.
5
+ * Pass the authenticated user so tool handlers can enforce permissions.
6
+ */
7
+ export declare const getMCPTools: (user?: User) => Record<string, Tool>;
@@ -0,0 +1,101 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
13
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ var __values = (this && this.__values) || function(o) {
39
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
40
+ if (m) return m.call(o);
41
+ if (o && typeof o.length === "number") return {
42
+ next: function () {
43
+ if (o && i >= o.length) o = void 0;
44
+ return { value: o && o[i++], done: !o };
45
+ }
46
+ };
47
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
48
+ };
49
+ Object.defineProperty(exports, "__esModule", { value: true });
50
+ exports.getMCPTools = void 0;
51
+ var api_1 = require("@terreno/api");
52
+ var ai_1 = require("ai");
53
+ /**
54
+ * Returns all registered MCP tools as Vercel AI SDK tool objects.
55
+ * Pass the authenticated user so tool handlers can enforce permissions.
56
+ */
57
+ var getMCPTools = function (user) {
58
+ var e_1, _a;
59
+ var toolDefs = (0, api_1.getAllMCPTools)();
60
+ var result = {};
61
+ var _loop_1 = function (toolDef) {
62
+ var coreTool = (0, ai_1.tool)({
63
+ description: toolDef.description,
64
+ execute: function (args) { return __awaiter(void 0, void 0, void 0, function () {
65
+ var response, text;
66
+ return __generator(this, function (_a) {
67
+ switch (_a.label) {
68
+ case 0: return [4 /*yield*/, toolDef.handler(args, user)];
69
+ case 1:
70
+ response = _a.sent();
71
+ text = response.content.map(function (c) { return c.text; }).join("\n");
72
+ try {
73
+ return [2 /*return*/, JSON.parse(text)];
74
+ }
75
+ catch (_b) {
76
+ return [2 /*return*/, text];
77
+ }
78
+ return [2 /*return*/];
79
+ }
80
+ });
81
+ }); },
82
+ parameters: toolDef.zodSchema,
83
+ });
84
+ result[toolDef.name] = coreTool;
85
+ };
86
+ try {
87
+ for (var toolDefs_1 = __values(toolDefs), toolDefs_1_1 = toolDefs_1.next(); !toolDefs_1_1.done; toolDefs_1_1 = toolDefs_1.next()) {
88
+ var toolDef = toolDefs_1_1.value;
89
+ _loop_1(toolDef);
90
+ }
91
+ }
92
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
93
+ finally {
94
+ try {
95
+ if (toolDefs_1_1 && !toolDefs_1_1.done && (_a = toolDefs_1.return)) _a.call(toolDefs_1);
96
+ }
97
+ finally { if (e_1) throw e_1.error; }
98
+ }
99
+ return result;
100
+ };
101
+ exports.getMCPTools = getMCPTools;
package/package.json CHANGED
@@ -18,9 +18,9 @@
18
18
  "description": "AI service layer for Terreno apps - GPT chat, request logging, and admin tools.",
19
19
  "devDependencies": {
20
20
  "@biomejs/biome": "^2.3.6",
21
- "@terreno/api": "57.0.0",
22
- "@terreno/test": "57.0.0",
23
- "@types/bun": "^1.3.8",
21
+ "@terreno/api": "57.2.0",
22
+ "@terreno/test": "57.2.0",
23
+ "@types/bun": "^1.4.0",
24
24
  "@types/express": "^5.0.6",
25
25
  "@types/luxon": "^3.7.1",
26
26
  "@types/multer": "^1.4.12",
@@ -71,7 +71,7 @@
71
71
  "access": "public"
72
72
  },
73
73
  "peerDependencies": {
74
- "@terreno/api": "57.0.0",
74
+ "@terreno/api": "57.2.0",
75
75
  "mongoose": "^8.0.0 || ^9.0.0"
76
76
  },
77
77
  "repository": {
@@ -86,9 +86,10 @@
86
86
  "lint:fix": "biome check --write ./src",
87
87
  "lint:unsafefix": "biome check --fix --unsafe ./src",
88
88
  "test": "bun test --preload ./src/tests/bunSetup.ts && for f in ./src/isolated/*.isolated.ts; do bun test --preload ./src/tests/bunSetup.ts \"$f\" || exit 1; done",
89
+ "test:agent": "AGENT=1 bun test --only-failures --preload ./src/tests/bunSetup.ts && for f in ./src/isolated/*.isolated.ts; do AGENT=1 bun test --only-failures --preload ./src/tests/bunSetup.ts \"$f\" || exit 1; done",
89
90
  "test:ci": "bun test --preload ./src/tests/bunSetup.ts && for f in ./src/isolated/*.isolated.ts; do bun test --preload ./src/tests/bunSetup.ts \"$f\" || exit 1; done",
90
91
  "test:coverage": "bun run ../scripts/check-coverage.ts"
91
92
  },
92
93
  "types": "dist/index.d.ts",
93
- "version": "57.0.0"
94
+ "version": "57.2.0"
94
95
  }
@@ -0,0 +1,21 @@
1
+ import {describe, expect, it} from "bun:test";
2
+ import express from "express";
3
+
4
+ import {AIAdminApp} from "./aiAdminApp";
5
+
6
+ describe("AIAdminApp", () => {
7
+ it("registers explorer routes and contributes the AI Requests screen", () => {
8
+ const app = express();
9
+ const plugin = new AIAdminApp({openApiOptions: {title: "Admin"}});
10
+
11
+ plugin.register(app);
12
+
13
+ const routePaths = (app.router.stack as Array<{route?: {path?: string}}>).flatMap((layer) =>
14
+ layer.route?.path ? [layer.route.path] : []
15
+ );
16
+ expect(routePaths).toContain("/aiRequestsExplorer");
17
+ expect(plugin.adminContribution()).toEqual({
18
+ customScreens: [{displayName: "AI Requests", icon: "robot", name: "ai-requests"}],
19
+ });
20
+ });
21
+ });
@@ -0,0 +1,29 @@
1
+ import type {AdminContribution, TerrenoPlugin} from "@terreno/api";
2
+ import type express from "express";
3
+
4
+ import {addAiRequestsExplorerRoutes} from "./routes/aiRequestsExplorer";
5
+
6
+ export interface AIAdminAppOptions {
7
+ openApiOptions?: Record<string, unknown>;
8
+ }
9
+
10
+ /**
11
+ * Registers the AI request explorer API and contributes its admin screen metadata.
12
+ */
13
+ export class AIAdminApp implements TerrenoPlugin {
14
+ private options: AIAdminAppOptions;
15
+
16
+ constructor(options: AIAdminAppOptions = {}) {
17
+ this.options = options;
18
+ }
19
+
20
+ adminContribution(): AdminContribution {
21
+ return {
22
+ customScreens: [{displayName: "AI Requests", icon: "robot", name: "ai-requests"}],
23
+ };
24
+ }
25
+
26
+ register(app: express.Application): void {
27
+ addAiRequestsExplorerRoutes(app, {openApiOptions: this.options.openApiOptions});
28
+ }
29
+ }
package/src/index.test.ts CHANGED
@@ -23,6 +23,7 @@ describe("@terreno/ai public exports", () => {
23
23
  "createTelemetryConfig",
24
24
  "createVertexProvider",
25
25
  "getCached",
26
+ "getMCPTools",
26
27
  "getLangfuseClient",
27
28
  "getPrompt",
28
29
  "initLangfuseClient",
package/src/index.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  export type {FlexibleSchema, JSONValue} from "ai";
2
2
  export {jsonSchema, Output} from "ai";
3
+ export type {AIAdminAppOptions} from "./aiAdminApp";
4
+ export {AIAdminApp} from "./aiAdminApp";
3
5
  export type {AiAppOptions} from "./aiApp";
4
6
  export {AiApp} from "./aiApp";
5
7
  export {LangfuseApp} from "./langfuseApp";
@@ -44,6 +46,7 @@ export {
44
46
  listGeminiApiModels,
45
47
  normalizeGeminiModelId,
46
48
  } from "./service/gemini";
49
+ export {getMCPTools} from "./service/getMCPTools";
47
50
  export {MCPService} from "./service/mcpService";
48
51
  export type {ParseFailure, ParseResult, ParseSuccess} from "./service/parseAiJson";
49
52
  export {
@@ -5,6 +5,19 @@ import {DateTime} from "luxon";
5
5
  import {AIRequest} from "../models/aiRequest";
6
6
  import type {AiRequestsExplorerRouteOptions} from "../types";
7
7
 
8
+ const parseRequestTypes = (raw: unknown): string[] => {
9
+ if (Array.isArray(raw)) {
10
+ return raw.flatMap((item) => parseRequestTypes(item));
11
+ }
12
+ if (typeof raw !== "string") {
13
+ return [];
14
+ }
15
+ return raw
16
+ .split(",")
17
+ .map((token) => token.trim())
18
+ .filter((token) => token.length > 0);
19
+ };
20
+
8
21
  export const addAiRequestsExplorerRoutes = (
9
22
  router: express.Router,
10
23
  options?: AiRequestsExplorerRouteOptions
@@ -48,8 +61,11 @@ export const addAiRequestsExplorerRoutes = (
48
61
  deleted: {$ne: true},
49
62
  };
50
63
 
51
- if (req.query.requestType) {
52
- match.requestType = req.query.requestType;
64
+ const requestTypes = parseRequestTypes(req.query.requestType);
65
+ if (requestTypes.length === 1) {
66
+ match.requestType = requestTypes[0];
67
+ } else if (requestTypes.length > 1) {
68
+ match.requestType = {$in: requestTypes};
53
69
  }
54
70
  if (req.query.model) {
55
71
  match.aiModel = req.query.model;
@@ -1526,6 +1526,35 @@ describe("AI Routes", () => {
1526
1526
  expect(res.body.data[0].requestType).toBe("remix");
1527
1527
  });
1528
1528
 
1529
+ it("filters by multiple requestType values", async () => {
1530
+ await AIRequest.create({
1531
+ aiModel: "gpt-4",
1532
+ prompt: "remix prompt",
1533
+ requestType: "remix",
1534
+ response: "remix response",
1535
+ });
1536
+ await AIRequest.create({
1537
+ aiModel: "gpt-4",
1538
+ prompt: "general prompt",
1539
+ requestType: "general",
1540
+ response: "general response",
1541
+ });
1542
+ await AIRequest.create({
1543
+ aiModel: "gpt-4",
1544
+ prompt: "json prompt",
1545
+ requestType: "json_object",
1546
+ response: "json response",
1547
+ });
1548
+
1549
+ const agent = await authAsUser(app, "admin");
1550
+ const res = await agent.get("/aiRequestsExplorer?requestType=remix,general");
1551
+
1552
+ expect(res.status).toBe(200);
1553
+ expect(res.body.total).toBe(2);
1554
+ const types = (res.body.data as {requestType: string}[]).map((row) => row.requestType).sort();
1555
+ expect(types).toEqual(["general", "remix"]);
1556
+ });
1557
+
1529
1558
  it("filters by model query parameter", async () => {
1530
1559
  await AIRequest.create({
1531
1560
  aiModel: "gpt-4",
@@ -0,0 +1,68 @@
1
+ import {beforeEach, describe, expect, it} from "bun:test";
2
+ import {clearMCPRegistry, Permissions, registerMCPModel, type User} from "@terreno/api";
3
+ import mongoose, {Schema} from "mongoose";
4
+
5
+ import {getMCPTools} from "./getMCPTools";
6
+
7
+ interface NoteFields {
8
+ _id: mongoose.Types.ObjectId;
9
+ title: string;
10
+ [key: string]: unknown;
11
+ }
12
+
13
+ const noteSchema = new Schema({
14
+ title: {required: true, type: String},
15
+ });
16
+
17
+ const getOrCreateModel = (): mongoose.Model<NoteFields> => {
18
+ try {
19
+ return mongoose.model<NoteFields>("AiMcpNote");
20
+ } catch {
21
+ return mongoose.model<NoteFields>("AiMcpNote", noteSchema);
22
+ }
23
+ };
24
+
25
+ const NoteModel = getOrCreateModel();
26
+
27
+ const asUser = (): User => {
28
+ const _id = new mongoose.Types.ObjectId();
29
+ return {_id, admin: false, id: _id.toString()} as unknown as User;
30
+ };
31
+
32
+ describe("getMCPTools", () => {
33
+ beforeEach(() => {
34
+ clearMCPRegistry();
35
+ });
36
+
37
+ it("returns an empty object when no MCP models are registered", () => {
38
+ expect(Object.keys(getMCPTools())).toEqual([]);
39
+ });
40
+
41
+ it("wraps registered MCP tools as Vercel AI SDK tools", async () => {
42
+ registerMCPModel(
43
+ NoteModel,
44
+ {methods: ["create", "list"], toolPrefix: "notes"},
45
+ {
46
+ permissions: {
47
+ create: [Permissions.IsAuthenticated],
48
+ delete: [],
49
+ list: [Permissions.IsAuthenticated],
50
+ read: [Permissions.IsAuthenticated],
51
+ update: [],
52
+ },
53
+ }
54
+ );
55
+
56
+ const user = asUser();
57
+ const tools = getMCPTools(user);
58
+
59
+ expect(Object.keys(tools).sort()).toEqual(["notes_create", "notes_list"]);
60
+
61
+ const created = await tools.notes_create.execute?.({title: "From AI tools"});
62
+ expect(created).toEqual(
63
+ expect.objectContaining({
64
+ data: expect.objectContaining({title: "From AI tools"}),
65
+ })
66
+ );
67
+ });
68
+ });
@@ -0,0 +1,30 @@
1
+ import {getAllMCPTools, type User} from "@terreno/api";
2
+ import {type Tool, tool} from "ai";
3
+
4
+ /**
5
+ * Returns all registered MCP tools as Vercel AI SDK tool objects.
6
+ * Pass the authenticated user so tool handlers can enforce permissions.
7
+ */
8
+ export const getMCPTools = (user?: User): Record<string, Tool> => {
9
+ const toolDefs = getAllMCPTools();
10
+ const result: Record<string, Tool> = {};
11
+
12
+ for (const toolDef of toolDefs) {
13
+ const coreTool = tool({
14
+ description: toolDef.description,
15
+ execute: async (args: Record<string, unknown>) => {
16
+ const response = await toolDef.handler(args, user);
17
+ const text = response.content.map((c) => c.text).join("\n");
18
+ try {
19
+ return JSON.parse(text) as unknown;
20
+ } catch {
21
+ return text;
22
+ }
23
+ },
24
+ parameters: toolDef.zodSchema,
25
+ } as never) as unknown as Tool;
26
+ result[toolDef.name] = coreTool;
27
+ }
28
+
29
+ return result;
30
+ };