@terreno/api 57.20.0 → 57.21.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 (116) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/biome.jsonc +1 -0
  3. package/dist/api.d.ts +3 -3
  4. package/dist/frameworkModelNames.d.ts +4 -0
  5. package/dist/frameworkModelNames.js +4 -0
  6. package/dist/index.d.ts +4 -0
  7. package/dist/index.js +9 -3
  8. package/dist/mcp/adminTracking.d.ts +28 -0
  9. package/dist/mcp/adminTracking.js +80 -0
  10. package/dist/mcp/auth.d.ts +6 -0
  11. package/dist/mcp/auth.js +12 -2
  12. package/dist/mcp/server.d.ts +8 -0
  13. package/dist/mcp/server.js +48 -4
  14. package/dist/models/mcpOAuthToken.js +27 -0
  15. package/dist/models/mcpRequestLog.d.ts +2 -0
  16. package/dist/models/mcpRequestLog.js +73 -0
  17. package/dist/models/mcpServiceToken.js +4 -0
  18. package/dist/models/mcpToolSetting.d.ts +2 -0
  19. package/dist/models/mcpToolSetting.js +119 -0
  20. package/dist/models/versionConfig.d.ts +2 -0
  21. package/dist/rbac/auditModel.d.ts +2 -1
  22. package/dist/terrenoApp.d.ts +12 -0
  23. package/dist/terrenoApp.js +3 -0
  24. package/dist/tests/models.d.ts +17 -22
  25. package/dist/tests/models.js +7 -1
  26. package/dist/tests/testHelper.d.ts +6 -12
  27. package/dist/tests.d.ts +1 -0
  28. package/dist/tests.js +3 -1
  29. package/dist/types/mcpAdmin.d.ts +58 -0
  30. package/dist/types/mcpAdmin.js +2 -0
  31. package/dist/types/mcpOAuth.d.ts +2 -0
  32. package/dist/types/mcpServiceToken.d.ts +2 -0
  33. package/e2e/smoke.ts +193 -0
  34. package/package.json +7 -5
  35. package/src/adminModelRouter.test.ts +8 -6
  36. package/src/api.arrayOperations.test.ts +31 -22
  37. package/src/api.hooks.test.ts +12 -11
  38. package/src/api.query.test.ts +2 -2
  39. package/src/api.test.ts +8 -7
  40. package/src/api.ts +3 -3
  41. package/src/audit/auditApp.test.ts +1 -1
  42. package/src/audit/cloudTasksEnqueue.test.ts +19 -14
  43. package/src/auth.test.ts +21 -7
  44. package/src/authRecovery.test.ts +10 -10
  45. package/src/authVerification.test.ts +7 -7
  46. package/src/betterAuthFeatures.test.ts +3 -2
  47. package/src/betterAuthLinking.test.ts +3 -1
  48. package/src/betterAuthSetup.test.ts +77 -51
  49. package/src/collectionRegistry.test.ts +4 -4
  50. package/src/frameworkModelNames.test.ts +8 -0
  51. package/src/frameworkModelNames.ts +4 -0
  52. package/src/githubAuth.test.ts +11 -11
  53. package/src/index.ts +8 -0
  54. package/src/isolated/migrateCliConnect.isolated.ts +3 -2
  55. package/src/mcp/actionTools.test.ts +11 -5
  56. package/src/mcp/adminTracking.test.ts +272 -0
  57. package/src/mcp/adminTracking.ts +104 -0
  58. package/src/mcp/auth.ts +18 -2
  59. package/src/mcp/oauth.test.ts +1 -1
  60. package/src/mcp/server.ts +67 -4
  61. package/src/mcp/serviceTokens.test.ts +2 -1
  62. package/src/mcp/toolGenerator.test.ts +9 -5
  63. package/src/migrations/cli.test.ts +15 -14
  64. package/src/migrations/cli.ts +1 -1
  65. package/src/migrations/generate.test.ts +2 -2
  66. package/src/migrations/load.test.ts +1 -1
  67. package/src/migrations/lock.test.ts +8 -3
  68. package/src/migrations/runner.test.ts +16 -5
  69. package/src/migrations/schemaCatalog.test.ts +4 -1
  70. package/src/models/mcpOAuthToken.test.ts +42 -0
  71. package/src/models/mcpOAuthToken.ts +32 -0
  72. package/src/models/mcpRequestLog.ts +81 -0
  73. package/src/models/mcpServiceToken.test.ts +23 -0
  74. package/src/models/mcpServiceToken.ts +10 -0
  75. package/src/models/mcpToolSetting.test.ts +69 -0
  76. package/src/models/mcpToolSetting.ts +138 -0
  77. package/src/models/versionConfig.ts +2 -0
  78. package/src/notifications/notificationsApp.test.ts +5 -8
  79. package/src/notifiers/slackWebApi.test.ts +30 -8
  80. package/src/openApi.test.ts +4 -4
  81. package/src/openApiValidator.test.ts +3 -3
  82. package/src/orgs/orgPermissions.test.ts +2 -2
  83. package/src/orgs/orgPlugin.test.ts +4 -3
  84. package/src/orgs/orgSecurityDefects.test.ts +3 -1
  85. package/src/orgs/organizationSettings.test.ts +1 -1
  86. package/src/orgs/orgsApp.test.ts +5 -3
  87. package/src/permissions.test.ts +2 -2
  88. package/src/rateLimit/redisStore.ioredis.test.ts +3 -2
  89. package/src/rbac/assertAllowed.test.ts +1 -1
  90. package/src/rbac/auditModel.ts +10 -2
  91. package/src/rbac/realtimeAccess.test.ts +3 -2
  92. package/src/rbac/routes.test.ts +1 -1
  93. package/src/rbac/userWriteGuards.test.ts +8 -5
  94. package/src/realtime/realtime.test.ts +35 -31
  95. package/src/scrubAdminFields.test.ts +1 -1
  96. package/src/sync/adminWindowMutation.test.ts +4 -3
  97. package/src/sync/executors.test.ts +1 -1
  98. package/src/sync/scripts/compactTombstones.test.ts +4 -3
  99. package/src/sync/sync.test.ts +1 -1
  100. package/src/sync/syncPhaseC.test.ts +14 -11
  101. package/src/sync/syncRoutes.test.ts +8 -8
  102. package/src/sync/syncSeqPlugin.test.ts +1 -2
  103. package/src/sync/syncSocket.test.ts +5 -4
  104. package/src/terrenoApp.mcpServiceTokens.test.ts +2 -2
  105. package/src/terrenoApp.migrations.test.ts +8 -7
  106. package/src/terrenoApp.ts +14 -0
  107. package/src/tests/betterAuthStubs.ts +3 -2
  108. package/src/tests/bunSetup.ts +1 -1
  109. package/src/tests/models.ts +10 -0
  110. package/src/tests/testEnv.ts +7 -0
  111. package/src/tests.ts +1 -0
  112. package/src/types/mcpAdmin.ts +80 -0
  113. package/src/types/mcpOAuth.ts +5 -0
  114. package/src/types/mcpServiceToken.ts +5 -0
  115. package/src/webhooks/verifiers/hmac.test.ts +1 -1
  116. package/tsconfig.typecheck.json +14 -0
@@ -0,0 +1,272 @@
1
+ import {beforeEach, describe, expect, it, spyOn} from "bun:test";
2
+ import express from "express";
3
+ import mongoose from "mongoose";
4
+ import supertest from "supertest";
5
+ import {z} from "zod";
6
+
7
+ import type {UserModel as AuthUserModel} from "../auth";
8
+ import {logger} from "../logger";
9
+ import {McpRequestLog} from "../models/mcpRequestLog";
10
+ import {McpServiceToken} from "../models/mcpServiceToken";
11
+ import {McpToolSetting} from "../models/mcpToolSetting";
12
+ import {TerrenoApp} from "../terrenoApp";
13
+ import {setupDb, UserModel} from "../tests";
14
+ import type {McpRequestLogOutcome} from "../types/mcpAdmin";
15
+ import {recordMcpToolCall, resolveMcpRequestLogOption} from "./adminTracking";
16
+ import {clearMCPRegistry, registerMCPTool} from "./registry";
17
+ import {mountMCPServer} from "./server";
18
+
19
+ const ACCEPT = "application/json, text/event-stream";
20
+
21
+ const registerTools = (): void => {
22
+ registerMCPTool({
23
+ description: "Echo a secret message",
24
+ handler: async (args) => {
25
+ return {content: [{text: `echo ${String(args.message)}`, type: "text"}]};
26
+ },
27
+ name: "echo_message",
28
+ zodSchema: z.object({message: z.string()}).strict(),
29
+ });
30
+ registerMCPTool({
31
+ description: "Always fails",
32
+ handler: async () => {
33
+ throw new TypeError("patient 123 not found");
34
+ },
35
+ name: "always_throws",
36
+ zodSchema: z.object({}).strict(),
37
+ });
38
+ };
39
+
40
+ const buildApp = (options: {requestLog?: boolean; toolSettings?: boolean}): express.Application => {
41
+ const app = express();
42
+ app.use(express.json());
43
+ mountMCPServer(app, {
44
+ mcpServiceTokens: true,
45
+ requestLog: options.requestLog ? {retentionDays: 7} : undefined,
46
+ toolSettings: options.toolSettings,
47
+ userModel: UserModel as unknown as AuthUserModel,
48
+ });
49
+ return app;
50
+ };
51
+
52
+ const callTool = (
53
+ app: express.Application,
54
+ name: string,
55
+ args: Record<string, unknown>,
56
+ token?: string
57
+ ): supertest.Test => {
58
+ const request = supertest(app).post("/mcp").set("accept", ACCEPT);
59
+ if (token) {
60
+ request.set("authorization", `Bearer ${token}`);
61
+ }
62
+ return request.send({
63
+ id: 1,
64
+ jsonrpc: "2.0",
65
+ method: "tools/call",
66
+ params: {arguments: args, name},
67
+ });
68
+ };
69
+
70
+ const listTools = (app: express.Application): supertest.Test =>
71
+ supertest(app)
72
+ .post("/mcp")
73
+ .set("accept", ACCEPT)
74
+ .send({id: 2, jsonrpc: "2.0", method: "tools/list", params: {}});
75
+
76
+ // Request-log writes are fire-and-forget, so poll briefly for the row.
77
+ const waitForLogs = async (count: number): Promise<void> => {
78
+ for (let attempt = 0; attempt < 50; attempt++) {
79
+ if ((await McpRequestLog.countDocuments({})) >= count) {
80
+ return;
81
+ }
82
+ await new Promise((resolve) => setTimeout(resolve, 10));
83
+ }
84
+ };
85
+
86
+ const waitForSettings = async (count: number): Promise<void> => {
87
+ for (let attempt = 0; attempt < 50; attempt++) {
88
+ if ((await McpToolSetting.countDocuments({})) >= count) {
89
+ return;
90
+ }
91
+ await new Promise((resolve) => setTimeout(resolve, 10));
92
+ }
93
+ };
94
+
95
+ describe("resolveMcpRequestLogOption", () => {
96
+ it("is off unless enabled", () => {
97
+ expect(resolveMcpRequestLogOption(undefined)).toBeUndefined();
98
+ expect(resolveMcpRequestLogOption(false)).toBeUndefined();
99
+ expect(resolveMcpRequestLogOption({enabled: false})).toBeUndefined();
100
+ });
101
+
102
+ it("defaults retention to 30 days", () => {
103
+ expect(resolveMcpRequestLogOption(true)).toEqual({retentionDays: 30});
104
+ expect(resolveMcpRequestLogOption({enabled: true, retentionDays: 3})).toEqual({
105
+ retentionDays: 3,
106
+ });
107
+ });
108
+
109
+ it("rejects a non-positive retention", () => {
110
+ expect(() => resolveMcpRequestLogOption({enabled: true, retentionDays: 0})).toThrow();
111
+ });
112
+ });
113
+
114
+ describe("MCP request log", () => {
115
+ let notAdmin: {_id: mongoose.Types.ObjectId};
116
+ beforeEach(async () => {
117
+ clearMCPRegistry();
118
+ registerTools();
119
+ const users = await setupDb();
120
+ notAdmin = users[1];
121
+ await McpRequestLog.deleteMany({});
122
+ await McpServiceToken.deleteMany({});
123
+ });
124
+
125
+ it("records the tool, user, and service token but never the arguments or result", async () => {
126
+ const user = notAdmin;
127
+ const {mcpServiceToken, token} = await McpServiceToken.issueFor(user, {name: "Laptop"});
128
+ const app = buildApp({requestLog: true});
129
+
130
+ const res = await callTool(app, "echo_message", {message: "very secret"}, token);
131
+
132
+ expect(res.text).toContain("echo very secret");
133
+ await waitForLogs(1);
134
+ const [row] = await McpRequestLog.find({}).lean();
135
+ expect(row.toolName).toBe("echo_message");
136
+ expect(row.outcome).toBe("ok");
137
+ expect(row.credential).toBe("mcp-service-token");
138
+ expect(String(row.userId)).toBe(String(user._id));
139
+ expect(String(row.serviceTokenId)).toBe(String(mcpServiceToken._id));
140
+ expect(row.durationMs).toBeGreaterThanOrEqual(0);
141
+ expect(row.expiresAt.getTime()).toBeGreaterThan(Date.now() + 6 * 24 * 60 * 60 * 1000);
142
+ const stored = JSON.stringify(row);
143
+ expect(stored).not.toContain("very secret");
144
+ expect(stored).not.toContain(token);
145
+ });
146
+
147
+ it("records an exception by class name without the message", async () => {
148
+ const app = buildApp({requestLog: true});
149
+
150
+ await callTool(app, "always_throws", {});
151
+
152
+ await waitForLogs(1);
153
+ const [row] = await McpRequestLog.find({}).lean();
154
+ expect(row.outcome).toBe("exception");
155
+ expect(row.errorName).toBe("TypeError");
156
+ expect(row.userId).toBeUndefined();
157
+ expect(JSON.stringify(row)).not.toContain("patient 123");
158
+ });
159
+
160
+ it("writes nothing when the log is off", async () => {
161
+ const app = buildApp({});
162
+
163
+ await callTool(app, "echo_message", {message: "hi"});
164
+
165
+ expect(await McpRequestLog.countDocuments({})).toBe(0);
166
+ });
167
+
168
+ it("drops a failed write with a debug log instead of failing the call", async () => {
169
+ const debug = spyOn(logger, "debug");
170
+ try {
171
+ // An outcome outside the schema enum makes the insert fail validation.
172
+ expect(() =>
173
+ recordMcpToolCall(
174
+ {durationMs: 1, outcome: "bogus" as McpRequestLogOutcome, toolName: "echo_message"},
175
+ {retentionDays: 1}
176
+ )
177
+ ).not.toThrow();
178
+ for (let attempt = 0; attempt < 50 && debug.mock.calls.length === 0; attempt++) {
179
+ await new Promise((resolve) => setTimeout(resolve, 10));
180
+ }
181
+ expect(String(debug.mock.calls[0]?.[0])).toContain("Request log write failed");
182
+ expect(await McpRequestLog.countDocuments({})).toBe(0);
183
+ } finally {
184
+ debug.mockRestore();
185
+ }
186
+ });
187
+ });
188
+
189
+ describe("MCP tool settings", () => {
190
+ beforeEach(async () => {
191
+ clearMCPRegistry();
192
+ registerTools();
193
+ await McpToolSetting.deleteMany({});
194
+ });
195
+
196
+ it("registers every tool as enabled on mount", async () => {
197
+ buildApp({toolSettings: true});
198
+
199
+ await waitForSettings(2);
200
+ const rows = await McpToolSetting.find({}).sort({name: 1}).lean();
201
+ expect(rows.map((row) => [row.name, row.enabled, row.source, row.registered])).toEqual([
202
+ ["always_throws", true, "custom", true],
203
+ ["echo_message", true, "custom", true],
204
+ ]);
205
+ });
206
+
207
+ it("keeps an admin's switch across restarts and marks tools that are gone", async () => {
208
+ await McpToolSetting.create({enabled: false, name: "echo_message", source: "custom"});
209
+ await McpToolSetting.create({name: "retired_tool", source: "custom"});
210
+
211
+ await McpToolSetting.syncRegistered([
212
+ {description: "Echo", name: "echo_message", source: "custom"},
213
+ ]);
214
+
215
+ const echo = await McpToolSetting.findExactlyOne({name: "echo_message"});
216
+ expect(echo.enabled).toBe(false);
217
+ expect(echo.registered).toBe(true);
218
+ const retired = await McpToolSetting.findExactlyOne({name: "retired_tool"});
219
+ expect(retired.registered).toBe(false);
220
+ });
221
+
222
+ it("hides a disabled tool from tools/list and rejects tools/call", async () => {
223
+ await McpToolSetting.create({enabled: false, name: "echo_message", source: "custom"});
224
+ const app = buildApp({toolSettings: true});
225
+
226
+ const list = await listTools(app);
227
+ expect(list.text).not.toContain("echo_message");
228
+ expect(list.text).toContain("always_throws");
229
+
230
+ const call = await callTool(app, "echo_message", {message: "hi"});
231
+ expect(call.text).not.toContain("echo hi");
232
+ expect(call.text).toContain("echo_message");
233
+ });
234
+
235
+ it("serves every tool when settings are off, even with a disabled row", async () => {
236
+ await McpToolSetting.create({enabled: false, name: "echo_message", source: "custom"});
237
+ const app = buildApp({});
238
+
239
+ const list = await listTools(app);
240
+
241
+ expect(list.text).toContain("echo_message");
242
+ expect(await McpToolSetting.countDocuments({})).toBe(1);
243
+ expect(mongoose.connection.readyState).toBe(1);
244
+ });
245
+ });
246
+
247
+ describe("TerrenoApp MCP admin options", () => {
248
+ beforeEach(async () => {
249
+ clearMCPRegistry();
250
+ registerTools();
251
+ await McpToolSetting.deleteMany({});
252
+ await McpRequestLog.deleteMany({});
253
+ });
254
+
255
+ it("passes mcpToolSettings and mcpRequestLog through to /mcp", async () => {
256
+ await McpToolSetting.create({enabled: false, name: "always_throws", source: "custom"});
257
+ const app = new TerrenoApp({
258
+ mcpRequestLog: true,
259
+ mcpToolSettings: true,
260
+ skipListen: true,
261
+ userModel: UserModel as unknown as AuthUserModel,
262
+ }).build();
263
+
264
+ const list = await listTools(app);
265
+ expect(list.text).not.toContain("always_throws");
266
+ await callTool(app, "echo_message", {message: "hi"});
267
+
268
+ await waitForLogs(1);
269
+ await waitForSettings(2);
270
+ expect(await McpRequestLog.countDocuments({toolName: "echo_message"})).toBe(1);
271
+ });
272
+ });
@@ -0,0 +1,104 @@
1
+ import {DateTime} from "luxon";
2
+ import mongoose from "mongoose";
3
+
4
+ import {APIError} from "../errors";
5
+ import {logger} from "../logger";
6
+ import {McpRequestLog} from "../models/mcpRequestLog";
7
+ import {McpToolSetting} from "../models/mcpToolSetting";
8
+ import type {McpRequestLogOutcome, McpToolSource} from "../types/mcpAdmin";
9
+ import type {MCPAuthResult} from "./auth";
10
+ import {getMCPCustomTools} from "./registry";
11
+ import type {MCPToolDefinition} from "./toolGenerator";
12
+
13
+ const DEFAULT_REQUEST_LOG_RETENTION_DAYS = 30;
14
+
15
+ /** `true` is `{enabled: true}`. Rows keep metadata only and expire after `retentionDays`. */
16
+ export type McpRequestLogAppOption = boolean | {enabled: boolean; retentionDays?: number};
17
+
18
+ export interface ResolvedMcpRequestLogOptions {
19
+ retentionDays: number;
20
+ }
21
+
22
+ export const resolveMcpRequestLogOption = (
23
+ option: McpRequestLogAppOption | undefined
24
+ ): ResolvedMcpRequestLogOptions | undefined => {
25
+ if (option === true) {
26
+ return {retentionDays: DEFAULT_REQUEST_LOG_RETENTION_DAYS};
27
+ }
28
+ if (!option || typeof option !== "object" || option.enabled !== true) {
29
+ return undefined;
30
+ }
31
+ const retentionDays = option.retentionDays ?? DEFAULT_REQUEST_LOG_RETENTION_DAYS;
32
+ if (!Number.isFinite(retentionDays) || retentionDays <= 0) {
33
+ throw new APIError({
34
+ code: "mcp-request-log-misconfigured",
35
+ detail: `mcpRequestLog.retentionDays must be a positive number, got ${retentionDays}`,
36
+ status: 500,
37
+ title: "MCP request log is misconfigured",
38
+ });
39
+ }
40
+ return {retentionDays};
41
+ };
42
+
43
+ export interface McpToolCallRecord {
44
+ auth?: MCPAuthResult;
45
+ durationMs: number;
46
+ errorName?: string;
47
+ outcome: McpRequestLogOutcome;
48
+ toolName: string;
49
+ }
50
+
51
+ const toObjectId = (value: string | undefined): mongoose.Types.ObjectId | undefined => {
52
+ if (!value || !mongoose.isValidObjectId(value)) {
53
+ return undefined;
54
+ }
55
+ return new mongoose.Types.ObjectId(value);
56
+ };
57
+
58
+ /**
59
+ * Write one request-log row without blocking or failing the tool call. A failed write is
60
+ * logged at debug level and dropped.
61
+ */
62
+ export const recordMcpToolCall = (
63
+ record: McpToolCallRecord,
64
+ options: ResolvedMcpRequestLogOptions
65
+ ): void => {
66
+ const {auth} = record;
67
+ void McpRequestLog.create({
68
+ credential: auth?.credential,
69
+ durationMs: Math.round(record.durationMs),
70
+ errorName: record.errorName,
71
+ expiresAt: DateTime.now().plus({days: options.retentionDays}).toJSDate(),
72
+ oauthClientId: auth?.oauthClientId,
73
+ oauthFamilyId: auth?.oauthFamilyId,
74
+ outcome: record.outcome,
75
+ serviceTokenId: toObjectId(auth?.serviceTokenId),
76
+ toolName: record.toolName,
77
+ userId: toObjectId(auth?.user?.id ? String(auth.user.id) : undefined),
78
+ }).catch((error: unknown) => {
79
+ logger.debug(`[mcp] Request log write failed: ${String(error)}`);
80
+ });
81
+ };
82
+
83
+ /** Register every tool in `McpToolSetting` so admins can see and switch them. */
84
+ export const syncMcpToolSettings = async (tools: MCPToolDefinition[]): Promise<void> => {
85
+ const customNames = new Set(getMCPCustomTools().map((tool) => tool.name));
86
+ await McpToolSetting.syncRegistered(
87
+ tools.map((tool) => ({
88
+ description: tool.description,
89
+ name: tool.name,
90
+ source: (customNames.has(tool.name) ? "custom" : "model") as McpToolSource,
91
+ }))
92
+ );
93
+ };
94
+
95
+ /** Tools an admin left on. A tool without a settings row counts as on. */
96
+ export const filterEnabledMcpTools = async (
97
+ tools: MCPToolDefinition[]
98
+ ): Promise<MCPToolDefinition[]> => {
99
+ const disabled = await McpToolSetting.disabledNames();
100
+ if (disabled.size === 0) {
101
+ return tools;
102
+ }
103
+ return tools.filter((tool) => !disabled.has(tool.name));
104
+ };
package/src/mcp/auth.ts CHANGED
@@ -20,6 +20,12 @@ export interface MCPAuthContext {
20
20
  /** The authenticated user plus the credential type that proved it. */
21
21
  export interface MCPAuthResult {
22
22
  credential: RequestCredential;
23
+ /** OAuth client id for an MCP OAuth access token. Never a secret. */
24
+ oauthClientId?: string;
25
+ /** OAuth rotation-chain id for an MCP OAuth access token. Never a secret. */
26
+ oauthFamilyId?: string;
27
+ /** `McpServiceToken` document id for a service token. Never the token or its hash. */
28
+ serviceTokenId?: string;
23
29
  /** Scopes granted to an MCP OAuth access token; unset for other credentials. */
24
30
  scopes?: string[];
25
31
  user: User;
@@ -97,7 +103,11 @@ const authenticateServiceToken = async (
97
103
  ).catch((error) => {
98
104
  logger.debug(`MCP service token last-used update failed: ${error}`);
99
105
  });
100
- return {credential: "mcp-service-token", user: activeUser};
106
+ return {
107
+ credential: "mcp-service-token",
108
+ serviceTokenId: String(serviceToken._id),
109
+ user: activeUser,
110
+ };
101
111
  };
102
112
 
103
113
  const authenticateOAuthAccessToken = async (
@@ -121,7 +131,13 @@ const authenticateOAuthAccessToken = async (
121
131
  return undefined;
122
132
  }
123
133
  const scopes = (accessToken.scope ?? "").split(" ").filter((scope) => scope.length > 0);
124
- return {credential: "oauth", scopes, user: activeUser};
134
+ return {
135
+ credential: "oauth",
136
+ oauthClientId: accessToken.clientId,
137
+ oauthFamilyId: accessToken.familyId,
138
+ scopes,
139
+ user: activeUser,
140
+ };
125
141
  };
126
142
 
127
143
  /**
@@ -949,7 +949,7 @@ describe("MCP OAuth authorization server", () => {
949
949
  })
950
950
  .addMiddleware((req, _res, next) => {
951
951
  if (req.path.startsWith("/oauth/authorize/")) {
952
- req.user = user ?? undefined;
952
+ req.user = (user ?? undefined) as unknown as typeof req.user;
953
953
  }
954
954
  next();
955
955
  })
package/src/mcp/server.ts CHANGED
@@ -7,6 +7,13 @@ import type {User, UserModel} from "../auth";
7
7
  import type {BetterAuthInstance} from "../betterAuthSetup";
8
8
  import {logger} from "../logger";
9
9
  import {setRequestContext} from "../requestContext";
10
+ import {
11
+ filterEnabledMcpTools,
12
+ type McpToolCallRecord,
13
+ type ResolvedMcpRequestLogOptions,
14
+ recordMcpToolCall,
15
+ syncMcpToolSettings,
16
+ } from "./adminTracking";
10
17
  import {extractAuthFromHeaders, type MCPAuthContext, type MCPAuthResult} from "./auth";
11
18
  import {type ResolvedMcpOAuthOptions, sendMcpOAuthChallenge} from "./oauthMetadata";
12
19
  import {getAllMCPTools, type MCPToolDefinition} from "./toolGenerator";
@@ -20,6 +27,13 @@ export interface MCPServerOptions {
20
27
  * request without valid credentials with a 401 RFC 9728 challenge.
21
28
  */
22
29
  mcpOAuth?: ResolvedMcpOAuthOptions;
30
+ /** When set, each tool call writes a metadata-only `McpRequestLog` row. */
31
+ requestLog?: ResolvedMcpRequestLogOptions;
32
+ /**
33
+ * When true, tools are registered in `McpToolSetting` on mount and tools an admin turned off
34
+ * are left out of `tools/list` and `tools/call`.
35
+ */
36
+ toolSettings?: boolean;
23
37
  }
24
38
 
25
39
  // Auth is resolved once in the Express handler (which may answer 401) and read back by the
@@ -40,13 +54,29 @@ export const mountMCPServer = (app: Application, options: MCPServerOptions): voi
40
54
 
41
55
  logger.info(`Mounting MCP server with ${tools.length} tools at /mcp`);
42
56
 
57
+ if (options.toolSettings) {
58
+ void syncMcpToolSettings(tools).catch((error: unknown) => {
59
+ logger.warn(`[mcp] Could not register tools in McpToolSetting: ${String(error)}`);
60
+ });
61
+ }
62
+
63
+ const buildServer = async (auth: MCPAuthResult | undefined): Promise<McpServer> => {
64
+ const served = options.toolSettings ? await filterEnabledMcpTools(tools) : tools;
65
+ const onToolCall = options.requestLog
66
+ ? (record: Omit<McpToolCallRecord, "auth">): void => {
67
+ recordMcpToolCall({...record, auth}, options.requestLog as ResolvedMcpRequestLogOptions);
68
+ }
69
+ : undefined;
70
+ return createMcpServerInstance(served, auth?.user, onToolCall);
71
+ };
72
+
43
73
  // The 2026-07-28 handler is stateless: it creates one server per request and also serves
44
74
  // 2025-era clients through the SDK's stateless legacy fallback.
45
75
  const handler = createMcpHandler(
46
76
  async ({requestInfo}) => {
47
77
  const stored = mcpAuthStorage.getStore();
48
78
  if (stored) {
49
- return createMcpServerInstance(tools, stored.auth?.user);
79
+ return buildServer(stored.auth);
50
80
  }
51
81
  const headers: Record<string, string> = {};
52
82
  requestInfo?.headers.forEach((value, key) => {
@@ -54,7 +84,7 @@ export const mountMCPServer = (app: Application, options: MCPServerOptions): voi
54
84
  });
55
85
  const auth = await extractAuthFromHeaders(headers, authContext);
56
86
  recordMcpAuth(auth);
57
- return createMcpServerInstance(tools, auth?.user);
87
+ return buildServer(auth);
58
88
  },
59
89
  {
60
90
  legacy: "stateless",
@@ -99,7 +129,18 @@ const recordMcpAuth = (auth: MCPAuthResult | undefined): void => {
99
129
  });
100
130
  };
101
131
 
102
- const createMcpServerInstance = (tools: MCPToolDefinition[], user?: User): McpServer => {
132
+ const errorName = (error: unknown): string => {
133
+ if (error instanceof Error) {
134
+ return error.name;
135
+ }
136
+ return typeof error;
137
+ };
138
+
139
+ const createMcpServerInstance = (
140
+ tools: MCPToolDefinition[],
141
+ user?: User,
142
+ onToolCall?: (record: Omit<McpToolCallRecord, "auth">) => void
143
+ ): McpServer => {
103
144
  const server = new McpServer(
104
145
  {
105
146
  name: "terreno-api-mcp",
@@ -120,7 +161,29 @@ const createMcpServerInstance = (tools: MCPToolDefinition[], user?: User): McpSe
120
161
  description: tool.description,
121
162
  inputSchema: tool.zodSchema,
122
163
  },
123
- async (args: unknown) => tool.handler(args as Record<string, unknown>, user)
164
+ async (args: unknown) => {
165
+ if (!onToolCall) {
166
+ return tool.handler(args as Record<string, unknown>, user);
167
+ }
168
+ const startedAt = performance.now();
169
+ try {
170
+ const result = await tool.handler(args as Record<string, unknown>, user);
171
+ onToolCall({
172
+ durationMs: performance.now() - startedAt,
173
+ outcome: result.isError ? "tool_error" : "ok",
174
+ toolName: tool.name,
175
+ });
176
+ return result;
177
+ } catch (error) {
178
+ onToolCall({
179
+ durationMs: performance.now() - startedAt,
180
+ errorName: errorName(error),
181
+ outcome: "exception",
182
+ toolName: tool.name,
183
+ });
184
+ throw error;
185
+ }
186
+ }
124
187
  );
125
188
  }
126
189
 
@@ -303,7 +303,8 @@ describe("MCP service token OpenAPI", () => {
303
303
  it("documents create, list, and revoke on /openapi.json", async () => {
304
304
  const app = new TerrenoApp({
305
305
  configureApp: (router, options) => {
306
- addMcpServiceTokenRoutes(router, {
306
+ // The routes only call get/post/delete, which the configureApp router provides.
307
+ addMcpServiceTokenRoutes(router as unknown as express.Application, {
307
308
  openApi: options?.openApi,
308
309
  publicMcpUrl: PUBLIC_MCP_URL,
309
310
  });
@@ -3,23 +3,23 @@ import {Writable} from "node:stream";
3
3
  import * as Sentry from "@sentry/bun";
4
4
  import mongoose, {Schema} from "mongoose";
5
5
  import winston from "winston";
6
-
6
+ import type {User} from "../auth";
7
7
  import {winstonLogger} from "../logger";
8
8
  import {Permissions} from "../permissions";
9
9
  import {getCurrentRequestContext, runWithRequestContext} from "../requestContext";
10
10
  import {generateAllTools, generateToolsForEntry} from "./toolGenerator";
11
11
  import type {MCPRegistryEntry} from "./types";
12
12
 
13
- const createTestModel = () => {
13
+ const createTestModel = (): mongoose.Model<unknown> => {
14
14
  try {
15
- return mongoose.model("MCPToolGenTest");
15
+ return mongoose.model<unknown>("MCPToolGenTest");
16
16
  } catch {
17
17
  const schema = new Schema({
18
18
  completed: {default: false, description: "Whether the item is complete", type: Boolean},
19
19
  name: {description: "The name", required: true, type: String},
20
20
  ownerId: {description: "Owner", ref: "User", type: Schema.Types.ObjectId},
21
21
  });
22
- return mongoose.model("MCPToolGenTest", schema);
22
+ return mongoose.model<unknown>("MCPToolGenTest", schema);
23
23
  }
24
24
  };
25
25
 
@@ -264,7 +264,11 @@ describe("tool-call observability", () => {
264
264
  },
265
265
  });
266
266
  const [tool] = generateToolsForEntry(entry);
267
- const user = {_id: new mongoose.Types.ObjectId(), admin: false, id: "user-123"};
267
+ const user: User = {
268
+ _id: new mongoose.Types.ObjectId() as unknown as User["_id"],
269
+ admin: false,
270
+ id: "user-123",
271
+ };
268
272
 
269
273
  await runWithRequestContext({}, async () => {
270
274
  const result = await tool.handler({}, user);