@terreno/api 57.20.0 → 57.22.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 +81 -0
  2. package/biome.jsonc +3 -2
  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
package/CHANGELOG.md CHANGED
@@ -20,6 +20,87 @@ Upgrade notes for consumer action live in [`mcp-server/src/docs/upgrades/`](mcp-
20
20
 
21
21
  Unreleased changes live in [`changelog/unreleased/`](changelog/unreleased/). Add one Markdown file per feature (see that directory's README) instead of editing this section.
22
22
 
23
+ ## [57.22.0] - 2026-11-03
24
+
25
+ Upgrade note: [`mcp-server/src/docs/upgrades/57.22.0.md`](mcp-server/src/docs/upgrades/57.22.0.md).
26
+
27
+ ### Breaking
28
+
29
+ - `@terreno/ai` no longer integrates with Langfuse. The built-in observability prompt registry, traces, and review queue (`ObservabilityApp` with `createLocalObservabilityPlugin()`) replace it. Removed exports: `LangfuseApp`, `LangfuseCache`, `getCached`, `setCached`, `invalidateCache`, `initLangfuseClient`, `getLangfuseClient`, `isLangfuseInitialized`, `shutdownLangfuseClient`, `compilePrompt`, `createPrompt`, `getPrompt`, `invalidatePromptCache`, `initTracing`, `shutdownTracing`, `createTelemetryConfig`, `preparePromptForAI`, and the types `ChatMessage`, `GetPromptOptions`, `LangfuseAppOptions`, `LangfuseCachedPrompt`, `PaginatedResult`, `PreparePromptResult`, `PromptListItem`, `ScoreSubmission`, `ScoringFunction`, `TelemetrySettings`, `TraceListItem`. The `@terreno/ai/langfuseApp` and `@terreno/ai/langfuseClient` subpath exports are gone, along with the `@langfuse/client`, `@langfuse/otel`, and `@opentelemetry/*` dependencies of `@terreno/ai`.
30
+ - `addGptRoutes` drops `langfuseSystemPromptName`; use `systemPromptName` (a registry prompt) instead. Chat turns no longer set `experimental_telemetry`.
31
+ - `ControlPrimary` is now only `"local"`.
32
+ - The example backend no longer reads `LANGFUSE_SECRET_KEY`, `LANGFUSE_PUBLIC_KEY`, `LANGFUSE_BASE_URL`, `LANGFUSE_ORGANIZATION`, `LANGFUSE_PROJECT`, or `LANGFUSE_PROJECT_ID`. Deploys (`.github/workflows/cd.yml`, `scripts/ci/gcp-deploy.sh`) no longer mount the Langfuse secrets, and `infra/flourish/main.tf` drops the `backend_secret_langfuse_secret_key` and `backend_secret_langfuse_public_key` modules, so the next `terraform apply` deletes those two Secret Manager secrets. Deploy a revision without the mounts before applying.
33
+
34
+ ### Added
35
+
36
+ - `addGptRoutes` accepts `systemPromptName` and `systemPromptLabel`. A chat turn prepends that observability registry prompt to the system prompt and records its version on the trace.
37
+ - The example chat reads `chat-assistant` and the `generate_joke` tool reads `joke-generator` from the observability prompt registry.
38
+ - `bun run backend:seed` fills every AI Observability screen: labelled prompt versions for `example-summarize`, `joke-generator`, and `chat-assistant`, golden datasets, finished experiments, traces with scores, and review items in every status. Run it on an existing database with the `seedAiObservabilityDemo` admin script.
39
+ - Review batches: pick a human question set and press **Grab 10 recent traces** to give reviewers a fixed set of inputs and outputs (`POST /ai/observability/review/batches`).
40
+ - The review item screen shows one input, one output, and every question as Yes / No rows. On web, `Y` / `N` answer the highlighted question, `Enter` submits and moves to the next batch item, and `S` skips. Evaluator dimensions accept a reviewer `question`.
41
+ - Run any LLM judge over a batch and see overall and per-question agreement with the human answers, plus a list of disagreements (`POST /ai/observability/review/batches/:id/judgeRuns`).
42
+ - The AI observability seed adds the `summary-review-questions` question set, two judges for it, and a 10-item batch with 8 answers where one judge agrees 97% and the other 78%.
43
+ - Observability registry prompts can reference other prompts with `{{> base-rules}}`, `{{> base-rules label=staging}}`, or `{{> base-rules version=3}}` (default label `production`). Shared instructions live in one prompt; `PromptRegistry.get`, the playground, experiments, and judges use the resolved text.
44
+ - Every reference must resolve when it is saved. Creating a prompt, saving a version, and moving a label return 400 `Invalid prompt reference` for a malformed tag, an unknown prompt or version, or a label the referenced prompt does not have yet, 400 `Prompt reference cycle` when the change would make prompts include each other, and 400 `Prompt references nested too deeply` when it would nest the prompt, or any prompt that includes it, more than 5 levels.
45
+ - Traces stay named after the called prompt. `ObsTrace.prompts` lists it first, then each shared prompt version it pulled in, marked with `includedBy`. `PromptVersionRef.includes` and harness prompt refs carry the same list.
46
+
47
+ ### Fixed
48
+
49
+ - Review queue: `Y` and `N` answer the highlighted question when a Yes/No segment is focused. **What the AI was given** and **What the AI wrote** are headings above the field cards.
50
+ - Review batches: **Save batch** sits on the New batch card. Search and **More filters** share a baseline.
51
+ - Prompt hub: description, folder, and tags sit on the Versions screen with the editor. System and template fields explain what to write.
52
+ - Evaluator detail loads the judge prompt `outputSchema` (so helpfulness no longer reports a missing dimension) and experiment rows open that experiment.
53
+
54
+ ## [57.21.0] - 2026-11-01
55
+
56
+ Upgrade note: [`mcp-server/src/docs/upgrades/57.21.0.md`](mcp-server/src/docs/upgrades/57.21.0.md).
57
+
58
+ ### Breaking
59
+
60
+ - The `terreno-scan` plugin is now `terreno-loop`, and its skills are renamed from `terreno-scan-*` to `terreno-loop-*`. The resident loop `terreno-scan-loop` is now `terreno-loop-run`: `/terreno-loop:run` in Claude Code, `/terreno-loop-run` in Cursor, `$terreno-loop-run` in Codex. Claude Code moves existing installs over through the marketplace `renames` entry. In Cursor and Codex, uninstall `terreno-scan` and install `terreno-loop`. Campaign state stays at `.terreno/scan/<goal>.json`, so campaigns already in progress resume.
61
+
62
+ ### Added
63
+
64
+ - `@terreno/admin-spa` serves an MCP OAuth consent screen at `/console/oauth/consent`, so a backend with no product frontend can set `mcpOAuth.consentUrl` to `${issuer}/console/oauth/consent`. Any signed-in user can approve or deny a request with their Better Auth session; signed-out users sign in and return through the login screen's new `returnTo` parameter, which accepts only in-app paths.
65
+ - Claude Code plugins now publish to npm with every release, as `@terreno/agent-plugin` and `@terreno/agent-plugin-loop`. A new `terreno-releases` marketplace installs them at the latest stable release. To pin one release, add `TerrenoLabs/terreno#<version>` instead. See [Install agent skills](docs/how-to/install-agent-skills.md#pick-a-channel).
66
+ - The generated Claude plugin manifest no longer pins `version`. Before this change, plugins installed from the `TerrenoLabs/terreno` marketplace stayed on the `2.12.0` copy, because their version never changed. They now update on every commit. Run `/plugin update terreno@terreno-plugins` once to leave `2.12.0`.
67
+ - The `terreno-planning` lifecycle plugin (2.13.0) plans e2e tests and manual regression cases in every IP:
68
+
69
+ - Grow requires `## E2E tests` and `## Regression cases` sections (either may be `None — <reason>`), read from the e2e guide at `docs/testing/e2e.md` or a `## Testing conventions` override in AGENTS.md or CLAUDE.md.
70
+ - Regression cases stay minimal: most features add none. A case is only for what a developer or QA must check by hand, such as push notifications, and Roast fails one that repeats an existing case.
71
+ - Pick writes each planned spec in the task that delivers it, and Roast runs it; a missing or failing row is `FAIL`.
72
+ - Brew gates on every planned spec and merges regression cases into `docs/regression/<area>.md` with the next free ID.
73
+ - Taste re-checks both sections after behaviour-changing fixes and renumbers regression ID collisions with `master`.
74
+ - `bun run check:lifecycle-skills` enforces these phrases in every stage.
75
+ - New `backfill-regression` skill proposes manual regression cases one area at a time and writes only the sets the human approves.
76
+ - A consumer opts out of manual regression suites with `Regression suites | none` in its `## Testing conventions` table.
77
+ - The `terreno-planning` lifecycle plugin (2.14.0) grows an end-user guide with every feature:
78
+
79
+ - Every IP has a `## User guide` section listing the guide pages it adds, updates, or retires, or `None — <reason>`. Pages live in `docs/user-guide/<area>/<feature>.md`, one feature per page, with `title`, `audience`, `platforms`, and `questions` frontmatter that chat agents use to answer "how do I…" questions.
80
+ - Pick writes each page in the task that ships the feature, Roast checks it against the shipped screens, Brew gates on it and the index, and Taste keeps it current after fixes.
81
+ - A repo opts out with `| User guide | none — <reason> |` in a `## User guide conventions` table in AGENTS.md or CLAUDE.md.
82
+ - New `backfill-user-guide` skill drafts pages for features that shipped without one, one area at a time, and writes only the pages the human approves.
83
+ - `bun run check:user-guide` validates the pages and index (CI `repo-policies`); `--uncovered <app dir>` lists screens no page names.
84
+ - Terreno's own guide covers the example app's main features.
85
+ - `@terreno/api`: opt-in `mcpRequestLog` on `TerrenoApp` records one metadata-only `McpRequestLog` row per MCP tool call (tool, user, credential, service token or OAuth client, duration, outcome, error class; never arguments, results, or error text), expiring after `retentionDays` (default 30).
86
+ - `@terreno/api`: opt-in `mcpToolSettings` on `TerrenoApp` registers every MCP tool in `McpToolSetting` at startup; tools an admin switches off are hidden from `tools/list` and rejected by `tools/call`.
87
+ - `@terreno/api`: deleting an `McpOAuthToken` row revokes its whole connection (token family) and keeps the rows. New `McpOAuthToken.revokeAllForUser` and `McpServiceToken.revokeAllForUser`.
88
+ - `@terreno/admin-backend`: `mcpAdminModels()` adds MCP admin screens (service tokens, OAuth clients, OAuth connections, request log, tool switches), `mcpAdminStatements` for RBAC, and `mcpAdminScripts()` adds `mcp-sign-out-everywhere`. See [Manage MCP from the admin panel](docs/how-to/manage-mcp-in-admin.md).
89
+ - Docs: [Expose an MCP server safely](docs/how-to/expose-mcp-server-safely.md) (OAuth, service tokens, Cloudflare Tunnel, Access) and the `bootstrap-mcp-server` skill for a single-binary MCP server with the admin console embedded.
90
+ - Every workspace package has a real-process smoke test and an e2e page:
91
+
92
+ - Each package's `e2e/smoke.ts` (or `smoke.spec.ts` for browser packages) runs its built output through its public entry: a server on a real port, the compiled binary, or a page in Chromium. `bun run --cwd <package> smoke` runs one; `bun run smoke` runs them all and prints each package's time. The CircleCI `smoke` job runs them on every package change.
93
+ - `@terreno/test` adds the smoke helpers `smokeMongoUri()`, `spawnUntilReady()`, `spawnExampleBackend()`, `runBin()`, and `freePort()`.
94
+ - The [E2E testing guide](docs/testing/e2e.md) explains the test tiers and links one page per package under `docs/testing/e2e/`.
95
+ - Manual regression cases live in `docs/regression/<area>.md`, one file per area, and `bun run check:regression-suites` validates them.
96
+ - example-frontend's smoke serves a web export that `bun run --cwd example-frontend export:smoke` builds once with a placeholder API URL; the smoke swaps in a `freePort()` API URL as it serves the bundle, so the 30 s smoke no longer rebuilds the export. `spawnUntilReady()` takes `stopGraceMs`, and `spawnExampleBackend()` stops example-backend after 0.5 s instead of 5 s.
97
+ - Every workspace package has a `typecheck` script that runs `tsc` over source and test files through a new `tsconfig.typecheck.json`. Root `bun run lint` ends with `bun run typecheck`, and CircleCI runs it in a new `typecheck` job. Test files that had type errors were fixed.
98
+
99
+ ### Changed
100
+
101
+ - `@terreno/api`: deleting an `McpOAuthToken` row with document or query `deleteOne` now revokes that row's whole token family (the connection) and keeps the rows instead of removing one pair. `deleteMany` is unchanged.
102
+ - `@terreno/ui`: new `theme.field` tokens (`background`, `backgroundDisabled`, `border`, `borderFocus`, `borderError`, `borderDisabled`) style form inputs. `TextField`, `SelectField`, `DateTimeField`, `HeightField`, and `OtpField` read them instead of `surface.base` and `border.dark`. Defaults equal the old colors, but overriding `surface` or `border` no longer recolors those fields; use `setTheme({field: ...})`.
103
+
23
104
  ## [57.20.0] - 2026-10-30
24
105
 
25
106
  Upgrade note: [`mcp-server/src/docs/upgrades/57.20.0.md`](mcp-server/src/docs/upgrades/57.20.0.md).
package/biome.jsonc CHANGED
@@ -1,5 +1,4 @@
1
1
  {
2
- "root": true,
3
2
  "$schema": "./node_modules/@biomejs/biome/configuration_schema.json",
4
3
  "extends": ["../biome.jsonc"],
5
4
  "files": {
@@ -7,6 +6,7 @@
7
6
  "package.json",
8
7
  "src/**/*.ts",
9
8
  "src/**/*.tsx",
9
+ "e2e/**/*.ts",
10
10
  "!!src/populate.ts",
11
11
  "!!**/node_modules",
12
12
  "!!node_modules",
@@ -17,5 +17,6 @@
17
17
  "!!**/coverage",
18
18
  "!!coverage"
19
19
  ]
20
- }
20
+ },
21
+ "root": true
21
22
  }
package/dist/api.d.ts CHANGED
@@ -163,7 +163,7 @@ export interface ModelRouterOptions<T> {
163
163
  * Return null to return a generic 403 error. Throw an APIError to return a 400 with specific
164
164
  * error information.
165
165
  */
166
- preCreate?: (value: Partial<T> | (Partial<T> | undefined)[] | null | undefined, request: express.Request) => T | Promise<T> | null;
166
+ preCreate?: (value: Partial<T> | (Partial<T> | undefined)[] | null | undefined, request: express.Request) => T | null | Promise<T | null>;
167
167
  /**
168
168
  * Hook that runs after `transformer.transform` but before changes are made for update operations.
169
169
  * Can update the body fields based on the request or the user.
@@ -173,7 +173,7 @@ export interface ModelRouterOptions<T> {
173
173
  * @param value - The request body relative to the model update (type: Partial<T>). Note: this does not contain the entire document to be updated, only the fields being updated.
174
174
  * @param request - The Express request object.
175
175
  */
176
- preUpdate?: (value: Partial<T>, request: express.Request) => T | Promise<T> | null;
176
+ preUpdate?: (value: Partial<T>, request: express.Request) => T | null | Promise<T | null>;
177
177
  /**
178
178
  * Hook that runs after `transformer.transform` but before the object is deleted.
179
179
  * Return null to return a generic 403 error.
@@ -182,7 +182,7 @@ export interface ModelRouterOptions<T> {
182
182
  * @param value - The document to be deleted, before the soft update of deleted: true (type: T).
183
183
  * @param request - The Express request object.
184
184
  */
185
- preDelete?: (value: T, request: express.Request) => T | Promise<T> | null;
185
+ preDelete?: (value: T, request: express.Request) => T | null | Promise<T | null>;
186
186
  /**
187
187
  * Hook that runs after the object is created but before the responseHandler serializes and
188
188
  * returned. This is a good spot to perform dependent changes to other models or performing async
@@ -9,7 +9,11 @@ export declare const FRAMEWORK_MODEL_PUBLIC_NAMES: {
9
9
  readonly TerrenoInboxNotification: "Notification";
10
10
  readonly TerrenoJob: "Job";
11
11
  readonly TerrenoJobSchedule: "JobSchedule";
12
+ readonly TerrenoMcpOAuthClient: "McpOAuthClient";
13
+ readonly TerrenoMcpOAuthToken: "McpOAuthToken";
14
+ readonly TerrenoMcpRequestLog: "McpRequestLog";
12
15
  readonly TerrenoMcpServiceToken: "McpServiceToken";
16
+ readonly TerrenoMcpToolSetting: "McpToolSetting";
13
17
  readonly TerrenoMembership: "Membership";
14
18
  readonly TerrenoNotificationPreference: "NotificationPreference";
15
19
  readonly TerrenoOrganization: "Organization";
@@ -12,7 +12,11 @@ exports.FRAMEWORK_MODEL_PUBLIC_NAMES = {
12
12
  TerrenoInboxNotification: "Notification",
13
13
  TerrenoJob: "Job",
14
14
  TerrenoJobSchedule: "JobSchedule",
15
+ TerrenoMcpOAuthClient: "McpOAuthClient",
16
+ TerrenoMcpOAuthToken: "McpOAuthToken",
17
+ TerrenoMcpRequestLog: "McpRequestLog",
15
18
  TerrenoMcpServiceToken: "McpServiceToken",
19
+ TerrenoMcpToolSetting: "McpToolSetting",
16
20
  TerrenoMembership: "Membership",
17
21
  TerrenoNotificationPreference: "NotificationPreference",
18
22
  TerrenoOrganization: "Organization",
package/dist/index.d.ts CHANGED
@@ -36,6 +36,7 @@ export { FRAMEWORK_MODEL_PUBLIC_NAMES, type FrameworkModelCompiledName, type Fra
36
36
  export * from "./githubAuth";
37
37
  export * from "./httpClient";
38
38
  export * from "./logger";
39
+ export { type McpRequestLogAppOption, type ResolvedMcpRequestLogOptions, resolveMcpRequestLogOption, } from "./mcp/adminTracking";
39
40
  export { extractAuthFromHeaders, extractUserFromHeaders, type MCPAuthContext, type MCPAuthResult, } from "./mcp/auth";
40
41
  export { addMcpOAuthRoutes, type McpOAuthRoutesOptions } from "./mcp/oauth";
41
42
  export { buildAuthorizationServerMetadata, buildProtectedResourceMetadata, type McpOAuthAppOption, type McpOAuthOptions, type ResolvedMcpOAuthOptions, resolveMcpOAuthOption, sendMcpOAuthChallenge, } from "./mcp/oauthMetadata";
@@ -59,7 +60,9 @@ export { McpOAuthAuthorization } from "./models/mcpOAuthAuthorization";
59
60
  export { McpOAuthClient } from "./models/mcpOAuthClient";
60
61
  export { McpOAuthRevokedFamily } from "./models/mcpOAuthRevokedFamily";
61
62
  export { McpOAuthFamilyRevokedError, McpOAuthToken } from "./models/mcpOAuthToken";
63
+ export { McpRequestLog } from "./models/mcpRequestLog";
62
64
  export * from "./models/mcpServiceToken";
65
+ export { McpToolSetting } from "./models/mcpToolSetting";
63
66
  export * from "./models/notification";
64
67
  export * from "./models/notificationPreference";
65
68
  export * from "./models/versionConfig";
@@ -137,6 +140,7 @@ export * from "./terrenoPlugin";
137
140
  export * from "./transformers";
138
141
  export * from "./types/consentForm";
139
142
  export * from "./types/consentResponse";
143
+ export type * from "./types/mcpAdmin";
140
144
  export type { McpOAuthAuthorizationDocument, McpOAuthAuthorizationStatus, McpOAuthClientDocument, McpOAuthConfidentialClientOptions, McpOAuthRevokedFamilyDocument, McpOAuthTokenDocument, McpOAuthTokenEndpointAuthMethod, } from "./types/mcpOAuth";
141
145
  export * from "./utils";
142
146
  export * from "./versionCheckPlugin";
package/dist/index.js CHANGED
@@ -14,9 +14,9 @@ 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.createNotificationService = exports.configureNotificationService = exports.McpOAuthToken = exports.McpOAuthFamilyRevokedError = exports.McpOAuthRevokedFamily = exports.McpOAuthClient = exports.McpOAuthAuthorization = exports.getAllMCPTools = exports.generateToolsForEntry = exports.generateAllTools = exports.resolveMcpServiceTokensOption = exports.MAX_ACTIVE_MCP_SERVICE_TOKENS = exports.addMcpServiceTokenRoutes = exports.mountMCPServer = exports.generateToolDescription = exports.generateInputSchema = exports.updateMCPRegistryOptions = exports.registerMCPTool = exports.registerMCPModel = exports.getMCPRegistry = exports.clearMCPRegistry = exports.sendMcpOAuthChallenge = exports.resolveMcpOAuthOption = exports.buildProtectedResourceMetadata = exports.buildAuthorizationServerMetadata = exports.addMcpOAuthRoutes = exports.extractUserFromHeaders = exports.extractAuthFromHeaders = exports.publicFrameworkModelName = exports.FRAMEWORK_MODEL_PUBLIC_NAMES = exports.getConsentStatuses = exports.resetAuditRecorderForTests = exports.recordAuditEvent = exports.persistEnqueuedAuditEvent = exports.maybeRecordAdminAudit = exports.isAuditRecorderInstalled = exports.flushAuditRecorderForTests = exports.persistRbacAuditToAuditEvent = exports.createCloudTasksAuditEnqueue = exports.auditEnqueueFromEnv = exports.AUDIT_SECRET_HEADER = exports.createAuditEventModel = exports.AUDIT_EVENT_SOURCES = exports.AuditApp = exports.recordSelfSecurityAction = exports.createSecurityEventsPlugin = exports.mountOrgSecurityRoutes = exports.createOrgSecurityAuthorizer = exports.suspendMembershipAction = exports.ISSUE_SIGN_IN_LINK_PERMISSION = void 0;
18
- exports.loadFullUserForSocket = exports.DEFAULT_SESSION_REVALIDATION_INTERVAL_MS = exports.updateRealtimeRegistryOptions = exports.registerRealtime = exports.getRealtimeRegistry = exports.findRegistryEntryByRoutePath = exports.findRegistryEntryByCollection = exports.clearRealtimeRegistry = exports.RealtimeApp = exports.MAX_QUERY_SUBSCRIPTIONS = exports.MAX_MODEL_SUBSCRIPTIONS = exports.MAX_DOCUMENT_SUBSCRIPTIONS = exports.installRealtimeSocketHandlers = exports.removeQuerySubscription = exports.removeAllSocketQueries = exports.getQuerySubscriptionsForCollection = exports.computeQueryId = exports.clearQueryStore = exports.addQuerySubscription = exports.matchesQuery = exports.stopChangeStreamWatcher = exports.startChangeStreamWatcher = exports.emitSyncDeltaForChange = exports.emitPayloadToAuthorizedRoom = exports.USER_UPDATE_IDENTITY_ACTION = exports.USER_IDENTITY_FIELDS = exports.isWriteKeyForField = exports.isRbacUserModelName = exports.assertCanWriteUserIdentity = exports.assertCanWriteTargetUser = exports.rbacRouter = exports.terrenoDefaultRoles = exports.READ_ONLY_ROLE_PERMISSIONS = exports.organizationOperatorRole = exports.expandRolePermissions = exports.createRbacRoleModel = exports.ORG_ADMIN_PERMISSION_BUNDLE = exports.membershipOrgAdminPermissionSource = exports.MEMBERSHIP_ORG_ADMIN_PERMISSION_SOURCE_NAME = exports.backfillAdmins = exports.recordRbacAudit = exports.createRbacAuditModel = exports.assertAllowed = exports.DEFAULT_WINDOW_MS = exports.DEFAULT_AUTH_MAX = exports.DEFAULT_API_MAX = exports.createRouteRateLimitMiddleware = exports.notificationsBeforeSend = exports.NotificationsApp = exports.getNotificationService = void 0;
19
- exports.z = exports.WebhooksApp = exports.twilioSignature = exports.stripeSignature = exports.sendgridEventSignature = exports.hmacSignature = exports.createMemoryIdempotencyStore = exports.stripAdminBodyFields = exports.scrubAdminFields = exports.adminBodyFieldsToStrip = exports.SYSTEM_FIELD_PATHS = exports.nestDottedFieldDescriptions = exports.modelDescriptionToOpenApiSpec = exports.modelDescriptionToAdminFields = exports.fieldDescriptionToZodType = exports.fieldDescriptionToOpenApiProperty = exports.fieldDescriptionToAdminMeta = exports.describeModelForRouter = exports.describeModel = exports.getSocketUser = exports.createSocketAuthMiddleware = exports.createLegacyJwtValidator = exports.createBetterAuthValidator = exports.startSessionRevalidationSweep = exports.runSessionRevalidationSweep = exports.revalidateSocketSession = exports.reresolveSyncRoomsForSocket = void 0;
17
+ exports.McpRequestLog = exports.McpOAuthToken = exports.McpOAuthFamilyRevokedError = exports.McpOAuthRevokedFamily = exports.McpOAuthClient = exports.McpOAuthAuthorization = exports.getAllMCPTools = exports.generateToolsForEntry = exports.generateAllTools = exports.resolveMcpServiceTokensOption = exports.MAX_ACTIVE_MCP_SERVICE_TOKENS = exports.addMcpServiceTokenRoutes = exports.mountMCPServer = exports.generateToolDescription = exports.generateInputSchema = exports.updateMCPRegistryOptions = exports.registerMCPTool = exports.registerMCPModel = exports.getMCPRegistry = exports.clearMCPRegistry = exports.sendMcpOAuthChallenge = exports.resolveMcpOAuthOption = exports.buildProtectedResourceMetadata = exports.buildAuthorizationServerMetadata = exports.addMcpOAuthRoutes = exports.extractUserFromHeaders = exports.extractAuthFromHeaders = exports.resolveMcpRequestLogOption = exports.publicFrameworkModelName = exports.FRAMEWORK_MODEL_PUBLIC_NAMES = exports.getConsentStatuses = exports.resetAuditRecorderForTests = exports.recordAuditEvent = exports.persistEnqueuedAuditEvent = exports.maybeRecordAdminAudit = exports.isAuditRecorderInstalled = exports.flushAuditRecorderForTests = exports.persistRbacAuditToAuditEvent = exports.createCloudTasksAuditEnqueue = exports.auditEnqueueFromEnv = exports.AUDIT_SECRET_HEADER = exports.createAuditEventModel = exports.AUDIT_EVENT_SOURCES = exports.AuditApp = exports.recordSelfSecurityAction = exports.createSecurityEventsPlugin = exports.mountOrgSecurityRoutes = exports.createOrgSecurityAuthorizer = exports.suspendMembershipAction = exports.ISSUE_SIGN_IN_LINK_PERMISSION = void 0;
18
+ exports.registerRealtime = exports.getRealtimeRegistry = exports.findRegistryEntryByRoutePath = exports.findRegistryEntryByCollection = exports.clearRealtimeRegistry = exports.RealtimeApp = exports.MAX_QUERY_SUBSCRIPTIONS = exports.MAX_MODEL_SUBSCRIPTIONS = exports.MAX_DOCUMENT_SUBSCRIPTIONS = exports.installRealtimeSocketHandlers = exports.removeQuerySubscription = exports.removeAllSocketQueries = exports.getQuerySubscriptionsForCollection = exports.computeQueryId = exports.clearQueryStore = exports.addQuerySubscription = exports.matchesQuery = exports.stopChangeStreamWatcher = exports.startChangeStreamWatcher = exports.emitSyncDeltaForChange = exports.emitPayloadToAuthorizedRoom = exports.USER_UPDATE_IDENTITY_ACTION = exports.USER_IDENTITY_FIELDS = exports.isWriteKeyForField = exports.isRbacUserModelName = exports.assertCanWriteUserIdentity = exports.assertCanWriteTargetUser = exports.rbacRouter = exports.terrenoDefaultRoles = exports.READ_ONLY_ROLE_PERMISSIONS = exports.organizationOperatorRole = exports.expandRolePermissions = exports.createRbacRoleModel = exports.ORG_ADMIN_PERMISSION_BUNDLE = exports.membershipOrgAdminPermissionSource = exports.MEMBERSHIP_ORG_ADMIN_PERMISSION_SOURCE_NAME = exports.backfillAdmins = exports.recordRbacAudit = exports.createRbacAuditModel = exports.assertAllowed = exports.DEFAULT_WINDOW_MS = exports.DEFAULT_AUTH_MAX = exports.DEFAULT_API_MAX = exports.createRouteRateLimitMiddleware = exports.notificationsBeforeSend = exports.NotificationsApp = exports.getNotificationService = exports.createNotificationService = exports.configureNotificationService = exports.McpToolSetting = void 0;
19
+ exports.z = exports.WebhooksApp = exports.twilioSignature = exports.stripeSignature = exports.sendgridEventSignature = exports.hmacSignature = exports.createMemoryIdempotencyStore = exports.stripAdminBodyFields = exports.scrubAdminFields = exports.adminBodyFieldsToStrip = exports.SYSTEM_FIELD_PATHS = exports.nestDottedFieldDescriptions = exports.modelDescriptionToOpenApiSpec = exports.modelDescriptionToAdminFields = exports.fieldDescriptionToZodType = exports.fieldDescriptionToOpenApiProperty = exports.fieldDescriptionToAdminMeta = exports.describeModelForRouter = exports.describeModel = exports.getSocketUser = exports.createSocketAuthMiddleware = exports.createLegacyJwtValidator = exports.createBetterAuthValidator = exports.startSessionRevalidationSweep = exports.runSessionRevalidationSweep = exports.revalidateSocketSession = exports.reresolveSyncRoomsForSocket = exports.loadFullUserForSocket = exports.DEFAULT_SESSION_REVALIDATION_INTERVAL_MS = exports.updateRealtimeRegistryOptions = void 0;
20
20
  var accessActions_1 = require("./accountSecurity/accessActions");
21
21
  Object.defineProperty(exports, "ISSUE_SIGN_IN_LINK_PERMISSION", { enumerable: true, get: function () { return accessActions_1.ISSUE_SIGN_IN_LINK_PERMISSION; } });
22
22
  __exportStar(require("./accountSecurity/accountSecurityApp"), exports);
@@ -77,6 +77,8 @@ Object.defineProperty(exports, "publicFrameworkModelName", { enumerable: true, g
77
77
  __exportStar(require("./githubAuth"), exports);
78
78
  __exportStar(require("./httpClient"), exports);
79
79
  __exportStar(require("./logger"), exports);
80
+ var adminTracking_1 = require("./mcp/adminTracking");
81
+ Object.defineProperty(exports, "resolveMcpRequestLogOption", { enumerable: true, get: function () { return adminTracking_1.resolveMcpRequestLogOption; } });
80
82
  var auth_1 = require("./mcp/auth");
81
83
  Object.defineProperty(exports, "extractAuthFromHeaders", { enumerable: true, get: function () { return auth_1.extractAuthFromHeaders; } });
82
84
  Object.defineProperty(exports, "extractUserFromHeaders", { enumerable: true, get: function () { return auth_1.extractUserFromHeaders; } });
@@ -124,7 +126,11 @@ Object.defineProperty(exports, "McpOAuthRevokedFamily", { enumerable: true, get:
124
126
  var mcpOAuthToken_1 = require("./models/mcpOAuthToken");
125
127
  Object.defineProperty(exports, "McpOAuthFamilyRevokedError", { enumerable: true, get: function () { return mcpOAuthToken_1.McpOAuthFamilyRevokedError; } });
126
128
  Object.defineProperty(exports, "McpOAuthToken", { enumerable: true, get: function () { return mcpOAuthToken_1.McpOAuthToken; } });
129
+ var mcpRequestLog_1 = require("./models/mcpRequestLog");
130
+ Object.defineProperty(exports, "McpRequestLog", { enumerable: true, get: function () { return mcpRequestLog_1.McpRequestLog; } });
127
131
  __exportStar(require("./models/mcpServiceToken"), exports);
132
+ var mcpToolSetting_1 = require("./models/mcpToolSetting");
133
+ Object.defineProperty(exports, "McpToolSetting", { enumerable: true, get: function () { return mcpToolSetting_1.McpToolSetting; } });
128
134
  __exportStar(require("./models/notification"), exports);
129
135
  __exportStar(require("./models/notificationPreference"), exports);
130
136
  __exportStar(require("./models/versionConfig"), exports);
@@ -0,0 +1,28 @@
1
+ import type { McpRequestLogOutcome } from "../types/mcpAdmin";
2
+ import type { MCPAuthResult } from "./auth";
3
+ import type { MCPToolDefinition } from "./toolGenerator";
4
+ /** `true` is `{enabled: true}`. Rows keep metadata only and expire after `retentionDays`. */
5
+ export type McpRequestLogAppOption = boolean | {
6
+ enabled: boolean;
7
+ retentionDays?: number;
8
+ };
9
+ export interface ResolvedMcpRequestLogOptions {
10
+ retentionDays: number;
11
+ }
12
+ export declare const resolveMcpRequestLogOption: (option: McpRequestLogAppOption | undefined) => ResolvedMcpRequestLogOptions | undefined;
13
+ export interface McpToolCallRecord {
14
+ auth?: MCPAuthResult;
15
+ durationMs: number;
16
+ errorName?: string;
17
+ outcome: McpRequestLogOutcome;
18
+ toolName: string;
19
+ }
20
+ /**
21
+ * Write one request-log row without blocking or failing the tool call. A failed write is
22
+ * logged at debug level and dropped.
23
+ */
24
+ export declare const recordMcpToolCall: (record: McpToolCallRecord, options: ResolvedMcpRequestLogOptions) => void;
25
+ /** Register every tool in `McpToolSetting` so admins can see and switch them. */
26
+ export declare const syncMcpToolSettings: (tools: MCPToolDefinition[]) => Promise<void>;
27
+ /** Tools an admin left on. A tool without a settings row counts as on. */
28
+ export declare const filterEnabledMcpTools: (tools: MCPToolDefinition[]) => Promise<MCPToolDefinition[]>;
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.filterEnabledMcpTools = exports.syncMcpToolSettings = exports.recordMcpToolCall = exports.resolveMcpRequestLogOption = void 0;
7
+ const luxon_1 = require("luxon");
8
+ const mongoose_1 = __importDefault(require("mongoose"));
9
+ const errors_1 = require("../errors");
10
+ const logger_1 = require("../logger");
11
+ const mcpRequestLog_1 = require("../models/mcpRequestLog");
12
+ const mcpToolSetting_1 = require("../models/mcpToolSetting");
13
+ const registry_1 = require("./registry");
14
+ const DEFAULT_REQUEST_LOG_RETENTION_DAYS = 30;
15
+ const resolveMcpRequestLogOption = (option) => {
16
+ if (option === true) {
17
+ return { retentionDays: DEFAULT_REQUEST_LOG_RETENTION_DAYS };
18
+ }
19
+ if (!option || typeof option !== "object" || option.enabled !== true) {
20
+ return undefined;
21
+ }
22
+ const retentionDays = option.retentionDays ?? DEFAULT_REQUEST_LOG_RETENTION_DAYS;
23
+ if (!Number.isFinite(retentionDays) || retentionDays <= 0) {
24
+ throw new errors_1.APIError({
25
+ code: "mcp-request-log-misconfigured",
26
+ detail: `mcpRequestLog.retentionDays must be a positive number, got ${retentionDays}`,
27
+ status: 500,
28
+ title: "MCP request log is misconfigured",
29
+ });
30
+ }
31
+ return { retentionDays };
32
+ };
33
+ exports.resolveMcpRequestLogOption = resolveMcpRequestLogOption;
34
+ const toObjectId = (value) => {
35
+ if (!value || !mongoose_1.default.isValidObjectId(value)) {
36
+ return undefined;
37
+ }
38
+ return new mongoose_1.default.Types.ObjectId(value);
39
+ };
40
+ /**
41
+ * Write one request-log row without blocking or failing the tool call. A failed write is
42
+ * logged at debug level and dropped.
43
+ */
44
+ const recordMcpToolCall = (record, options) => {
45
+ const { auth } = record;
46
+ void mcpRequestLog_1.McpRequestLog.create({
47
+ credential: auth?.credential,
48
+ durationMs: Math.round(record.durationMs),
49
+ errorName: record.errorName,
50
+ expiresAt: luxon_1.DateTime.now().plus({ days: options.retentionDays }).toJSDate(),
51
+ oauthClientId: auth?.oauthClientId,
52
+ oauthFamilyId: auth?.oauthFamilyId,
53
+ outcome: record.outcome,
54
+ serviceTokenId: toObjectId(auth?.serviceTokenId),
55
+ toolName: record.toolName,
56
+ userId: toObjectId(auth?.user?.id ? String(auth.user.id) : undefined),
57
+ }).catch((error) => {
58
+ logger_1.logger.debug(`[mcp] Request log write failed: ${String(error)}`);
59
+ });
60
+ };
61
+ exports.recordMcpToolCall = recordMcpToolCall;
62
+ /** Register every tool in `McpToolSetting` so admins can see and switch them. */
63
+ const syncMcpToolSettings = async (tools) => {
64
+ const customNames = new Set((0, registry_1.getMCPCustomTools)().map((tool) => tool.name));
65
+ await mcpToolSetting_1.McpToolSetting.syncRegistered(tools.map((tool) => ({
66
+ description: tool.description,
67
+ name: tool.name,
68
+ source: (customNames.has(tool.name) ? "custom" : "model"),
69
+ })));
70
+ };
71
+ exports.syncMcpToolSettings = syncMcpToolSettings;
72
+ /** Tools an admin left on. A tool without a settings row counts as on. */
73
+ const filterEnabledMcpTools = async (tools) => {
74
+ const disabled = await mcpToolSetting_1.McpToolSetting.disabledNames();
75
+ if (disabled.size === 0) {
76
+ return tools;
77
+ }
78
+ return tools.filter((tool) => !disabled.has(tool.name));
79
+ };
80
+ exports.filterEnabledMcpTools = filterEnabledMcpTools;
@@ -11,6 +11,12 @@ export interface MCPAuthContext {
11
11
  /** The authenticated user plus the credential type that proved it. */
12
12
  export interface MCPAuthResult {
13
13
  credential: RequestCredential;
14
+ /** OAuth client id for an MCP OAuth access token. Never a secret. */
15
+ oauthClientId?: string;
16
+ /** OAuth rotation-chain id for an MCP OAuth access token. Never a secret. */
17
+ oauthFamilyId?: string;
18
+ /** `McpServiceToken` document id for a service token. Never the token or its hash. */
19
+ serviceTokenId?: string;
14
20
  /** Scopes granted to an MCP OAuth access token; unset for other credentials. */
15
21
  scopes?: string[];
16
22
  user: User;
package/dist/mcp/auth.js CHANGED
@@ -66,7 +66,11 @@ const authenticateServiceToken = async (token, userModel) => {
66
66
  void mcpServiceToken_1.McpServiceToken.updateOne({ _id: serviceToken._id }, { $set: { lastUsedAt: luxon_1.DateTime.now().toJSDate() } }).catch((error) => {
67
67
  logger_1.logger.debug(`MCP service token last-used update failed: ${error}`);
68
68
  });
69
- return { credential: "mcp-service-token", user: activeUser };
69
+ return {
70
+ credential: "mcp-service-token",
71
+ serviceTokenId: String(serviceToken._id),
72
+ user: activeUser,
73
+ };
70
74
  };
71
75
  const authenticateOAuthAccessToken = async (token, userModel) => {
72
76
  const accessToken = await mcpOAuthToken_1.McpOAuthToken.verifyAccessToken(token);
@@ -84,7 +88,13 @@ const authenticateOAuthAccessToken = async (token, userModel) => {
84
88
  return undefined;
85
89
  }
86
90
  const scopes = (accessToken.scope ?? "").split(" ").filter((scope) => scope.length > 0);
87
- return { credential: "oauth", scopes, user: activeUser };
91
+ return {
92
+ credential: "oauth",
93
+ oauthClientId: accessToken.clientId,
94
+ oauthFamilyId: accessToken.familyId,
95
+ scopes,
96
+ user: activeUser,
97
+ };
88
98
  };
89
99
  /**
90
100
  * Resolve the caller and the credential type from raw headers using whichever auth providers
@@ -1,6 +1,7 @@
1
1
  import type { Application } from "express";
2
2
  import type { UserModel } from "../auth";
3
3
  import type { BetterAuthInstance } from "../betterAuthSetup";
4
+ import { type ResolvedMcpRequestLogOptions } from "./adminTracking";
4
5
  import { type ResolvedMcpOAuthOptions } from "./oauthMetadata";
5
6
  export interface MCPServerOptions {
6
7
  userModel: UserModel;
@@ -11,5 +12,12 @@ export interface MCPServerOptions {
11
12
  * request without valid credentials with a 401 RFC 9728 challenge.
12
13
  */
13
14
  mcpOAuth?: ResolvedMcpOAuthOptions;
15
+ /** When set, each tool call writes a metadata-only `McpRequestLog` row. */
16
+ requestLog?: ResolvedMcpRequestLogOptions;
17
+ /**
18
+ * When true, tools are registered in `McpToolSetting` on mount and tools an admin turned off
19
+ * are left out of `tools/list` and `tools/call`.
20
+ */
21
+ toolSettings?: boolean;
14
22
  }
15
23
  export declare const mountMCPServer: (app: Application, options: MCPServerOptions) => void;
@@ -6,6 +6,7 @@ const node_1 = require("@modelcontextprotocol/node");
6
6
  const server_1 = require("@modelcontextprotocol/server");
7
7
  const logger_1 = require("../logger");
8
8
  const requestContext_1 = require("../requestContext");
9
+ const adminTracking_1 = require("./adminTracking");
9
10
  const auth_1 = require("./auth");
10
11
  const oauthMetadata_1 = require("./oauthMetadata");
11
12
  const toolGenerator_1 = require("./toolGenerator");
@@ -24,12 +25,26 @@ const mountMCPServer = (app, options) => {
24
25
  userModel: options.userModel,
25
26
  };
26
27
  logger_1.logger.info(`Mounting MCP server with ${tools.length} tools at /mcp`);
28
+ if (options.toolSettings) {
29
+ void (0, adminTracking_1.syncMcpToolSettings)(tools).catch((error) => {
30
+ logger_1.logger.warn(`[mcp] Could not register tools in McpToolSetting: ${String(error)}`);
31
+ });
32
+ }
33
+ const buildServer = async (auth) => {
34
+ const served = options.toolSettings ? await (0, adminTracking_1.filterEnabledMcpTools)(tools) : tools;
35
+ const onToolCall = options.requestLog
36
+ ? (record) => {
37
+ (0, adminTracking_1.recordMcpToolCall)({ ...record, auth }, options.requestLog);
38
+ }
39
+ : undefined;
40
+ return createMcpServerInstance(served, auth?.user, onToolCall);
41
+ };
27
42
  // The 2026-07-28 handler is stateless: it creates one server per request and also serves
28
43
  // 2025-era clients through the SDK's stateless legacy fallback.
29
44
  const handler = (0, server_1.createMcpHandler)(async ({ requestInfo }) => {
30
45
  const stored = mcpAuthStorage.getStore();
31
46
  if (stored) {
32
- return createMcpServerInstance(tools, stored.auth?.user);
47
+ return buildServer(stored.auth);
33
48
  }
34
49
  const headers = {};
35
50
  requestInfo?.headers.forEach((value, key) => {
@@ -37,7 +52,7 @@ const mountMCPServer = (app, options) => {
37
52
  });
38
53
  const auth = await (0, auth_1.extractAuthFromHeaders)(headers, authContext);
39
54
  recordMcpAuth(auth);
40
- return createMcpServerInstance(tools, auth?.user);
55
+ return buildServer(auth);
41
56
  }, {
42
57
  legacy: "stateless",
43
58
  onerror: (error) => logger_1.logger.catch(error),
@@ -79,7 +94,13 @@ const recordMcpAuth = (auth) => {
79
94
  userId: auth.user.id,
80
95
  });
81
96
  };
82
- const createMcpServerInstance = (tools, user) => {
97
+ const errorName = (error) => {
98
+ if (error instanceof Error) {
99
+ return error.name;
100
+ }
101
+ return typeof error;
102
+ };
103
+ const createMcpServerInstance = (tools, user, onToolCall) => {
83
104
  const server = new server_1.McpServer({
84
105
  name: "terreno-api-mcp",
85
106
  version: "1.0.0",
@@ -93,7 +114,30 @@ const createMcpServerInstance = (tools, user) => {
93
114
  server.registerTool(tool.name, {
94
115
  description: tool.description,
95
116
  inputSchema: tool.zodSchema,
96
- }, async (args) => tool.handler(args, user));
117
+ }, async (args) => {
118
+ if (!onToolCall) {
119
+ return tool.handler(args, user);
120
+ }
121
+ const startedAt = performance.now();
122
+ try {
123
+ const result = await tool.handler(args, user);
124
+ onToolCall({
125
+ durationMs: performance.now() - startedAt,
126
+ outcome: result.isError ? "tool_error" : "ok",
127
+ toolName: tool.name,
128
+ });
129
+ return result;
130
+ }
131
+ catch (error) {
132
+ onToolCall({
133
+ durationMs: performance.now() - startedAt,
134
+ errorName: errorName(error),
135
+ outcome: "exception",
136
+ toolName: tool.name,
137
+ });
138
+ throw error;
139
+ }
140
+ });
97
141
  }
98
142
  return server;
99
143
  };
@@ -144,6 +144,17 @@ mcpOAuthTokenSchema.statics = {
144
144
  refreshToken: includeRefreshToken ? refreshSecret : undefined,
145
145
  };
146
146
  },
147
+ async revokeAllForUser(userId) {
148
+ const tokens = await this.find({
149
+ revokedAt: { $exists: false },
150
+ userId: new mongoose_1.default.Types.ObjectId(String(userId)),
151
+ }).select({ familyId: 1 });
152
+ const familyIds = new Set(tokens.map((token) => token.familyId));
153
+ for (const familyId of familyIds) {
154
+ await this.revokeFamily(familyId);
155
+ }
156
+ return familyIds.size;
157
+ },
147
158
  async revokeClient(clientId) {
148
159
  const tokens = await this.find({ clientId, revokedAt: { $exists: false } }).select({ familyId: 1 });
149
160
  const familyIds = new Set(tokens.map((token) => token.familyId));
@@ -179,5 +190,21 @@ mcpOAuthTokenSchema.statics = {
179
190
  });
180
191
  },
181
192
  };
193
+ // Deleting a token row (for example from the admin panel) revokes its whole rotation chain and
194
+ // keeps the rows, so the connection ends and its history stays visible.
195
+ mcpOAuthTokenSchema.methods = {
196
+ ...mcpOAuthTokenSchema.methods,
197
+ async deleteOne() {
198
+ await this.constructor.revokeFamily(this.familyId);
199
+ return this;
200
+ },
201
+ };
202
+ mcpOAuthTokenSchema.pre("deleteOne", { document: false, query: true }, async function () {
203
+ const [existing] = await this.model.find(this.getFilter()).limit(1).select({ familyId: 1 });
204
+ if (existing) {
205
+ await this.model.revokeFamily(existing.familyId);
206
+ }
207
+ this.setQuery({ _id: { $exists: false } });
208
+ });
182
209
  exports.McpOAuthToken = mongoose_1.default.models.TerrenoMcpOAuthToken ??
183
210
  mongoose_1.default.model("TerrenoMcpOAuthToken", mcpOAuthTokenSchema, "mcpoauthtokens");
@@ -0,0 +1,2 @@
1
+ import type { McpRequestLogModel } from "../types/mcpAdmin";
2
+ export declare const McpRequestLog: McpRequestLogModel;
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.McpRequestLog = void 0;
7
+ const mongoose_1 = __importDefault(require("mongoose"));
8
+ const plugins_1 = require("../plugins");
9
+ /**
10
+ * One row per MCP tool call when `mcpRequestLog` is on. Metadata only: tool arguments, results,
11
+ * and error messages are never stored. Rows expire at `expiresAt`.
12
+ */
13
+ const mcpRequestLogSchema = new mongoose_1.default.Schema({
14
+ credential: {
15
+ description: "Credential type that authenticated the call",
16
+ enum: ["jwt", "better-auth-session", "mcp-service-token", "oauth"],
17
+ type: String,
18
+ },
19
+ durationMs: {
20
+ description: "Time the tool handler took, in milliseconds",
21
+ required: true,
22
+ type: Number,
23
+ },
24
+ errorName: {
25
+ description: "Error class name when the tool threw; never the error message",
26
+ type: String,
27
+ },
28
+ expiresAt: {
29
+ description: "When this log row is removed",
30
+ required: true,
31
+ type: Date,
32
+ },
33
+ oauthClientId: {
34
+ description: "OAuth client id when the call used an MCP OAuth access token",
35
+ index: true,
36
+ type: String,
37
+ },
38
+ oauthFamilyId: {
39
+ description: "OAuth token family (one approved connection) when the call used OAuth",
40
+ type: String,
41
+ },
42
+ outcome: {
43
+ description: "ok, tool_error (the tool returned isError), or exception (the tool threw)",
44
+ enum: ["ok", "tool_error", "exception"],
45
+ required: true,
46
+ type: String,
47
+ },
48
+ serviceTokenId: {
49
+ description: "Service token used for the call, when the credential was a service token",
50
+ index: true,
51
+ ref: "TerrenoMcpServiceToken",
52
+ type: mongoose_1.default.Schema.Types.ObjectId,
53
+ },
54
+ toolName: {
55
+ description: "Name of the MCP tool that was called",
56
+ index: true,
57
+ required: true,
58
+ type: String,
59
+ },
60
+ userId: {
61
+ description: "User the call acted as",
62
+ index: true,
63
+ ref: "User",
64
+ type: mongoose_1.default.Schema.Types.ObjectId,
65
+ },
66
+ }, { strict: "throw", toJSON: { virtuals: true }, toObject: { virtuals: true } });
67
+ mcpRequestLogSchema.index({ expiresAt: 1 }, { expireAfterSeconds: 0 });
68
+ mcpRequestLogSchema.index({ created: -1 });
69
+ mcpRequestLogSchema.plugin(plugins_1.createdUpdatedPlugin);
70
+ mcpRequestLogSchema.plugin(plugins_1.findOneOrNone);
71
+ mcpRequestLogSchema.plugin(plugins_1.findExactlyOne);
72
+ exports.McpRequestLog = mongoose_1.default.models.TerrenoMcpRequestLog ??
73
+ mongoose_1.default.model("TerrenoMcpRequestLog", mcpRequestLogSchema, "mcprequestlogs");