@terreno/api 57.16.1 → 57.17.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 (184) hide show
  1. package/dist/actions.d.ts +26 -3
  2. package/dist/actions.js +102 -16
  3. package/dist/api.d.ts +7 -0
  4. package/dist/api.js +59 -3
  5. package/dist/auth.d.ts +28 -4
  6. package/dist/auth.js +140 -15
  7. package/dist/authRecovery.d.ts +31 -0
  8. package/dist/authRecovery.js +86 -6
  9. package/dist/betterAuth.d.ts +86 -0
  10. package/dist/betterAuthApp.d.ts +17 -0
  11. package/dist/betterAuthApp.js +12 -1
  12. package/dist/betterAuthOAuthHandoff.d.ts +24 -0
  13. package/dist/betterAuthOAuthHandoff.js +305 -0
  14. package/dist/betterAuthSetup.d.ts +37 -2
  15. package/dist/betterAuthSetup.js +304 -24
  16. package/dist/expressServer.d.ts +16 -0
  17. package/dist/expressServer.js +61 -14
  18. package/dist/githubAuth.d.ts +9 -0
  19. package/dist/githubAuth.js +230 -31
  20. package/dist/index.d.ts +9 -1
  21. package/dist/index.js +27 -3
  22. package/dist/mcp/actionTools.d.ts +4 -0
  23. package/dist/mcp/actionTools.js +158 -0
  24. package/dist/mcp/auth.d.ts +30 -0
  25. package/dist/mcp/auth.js +83 -28
  26. package/dist/mcp/createMCPRequest.d.ts +5 -1
  27. package/dist/mcp/createMCPRequest.js +3 -3
  28. package/dist/mcp/handlers.d.ts +3 -0
  29. package/dist/mcp/handlers.js +43 -27
  30. package/dist/mcp/oauth.d.ts +14 -0
  31. package/dist/mcp/oauth.js +618 -0
  32. package/dist/mcp/oauthMetadata.d.ts +89 -0
  33. package/dist/mcp/oauthMetadata.js +137 -0
  34. package/dist/mcp/registry.d.ts +5 -0
  35. package/dist/mcp/registry.js +9 -1
  36. package/dist/mcp/server.d.ts +6 -0
  37. package/dist/mcp/server.js +44 -7
  38. package/dist/mcp/serviceTokens.js +12 -2
  39. package/dist/mcp/toolExecution.d.ts +12 -0
  40. package/dist/mcp/toolExecution.js +60 -0
  41. package/dist/mcp/toolGenerator.d.ts +4 -1
  42. package/dist/mcp/toolGenerator.js +26 -60
  43. package/dist/mcp/types.d.ts +4 -4
  44. package/dist/models/mcpOAuthAuthorization.d.ts +2 -0
  45. package/dist/models/mcpOAuthAuthorization.js +86 -0
  46. package/dist/models/mcpOAuthClient.d.ts +2 -0
  47. package/dist/models/mcpOAuthClient.js +42 -0
  48. package/dist/models/mcpOAuthRevokedFamily.d.ts +2 -0
  49. package/dist/models/mcpOAuthRevokedFamily.js +36 -0
  50. package/dist/models/mcpOAuthToken.d.ts +12 -0
  51. package/dist/models/mcpOAuthToken.js +159 -0
  52. package/dist/models/mcpServiceToken.d.ts +1 -0
  53. package/dist/models/mcpServiceToken.js +21 -4
  54. package/dist/permissions.d.ts +7 -0
  55. package/dist/permissions.js +18 -1
  56. package/dist/rateLimit/policies.d.ts +4 -0
  57. package/dist/rateLimit/policies.js +46 -7
  58. package/dist/rbac/access.js +1 -0
  59. package/dist/rbac/membershipOrgAdminSource.d.ts +4 -0
  60. package/dist/rbac/membershipOrgAdminSource.js +5 -0
  61. package/dist/rbac/modelRouterAccess.d.ts +7 -1
  62. package/dist/rbac/modelRouterAccess.js +37 -24
  63. package/dist/rbac/realtimeAccess.js +17 -3
  64. package/dist/rbac/resolve.js +66 -9
  65. package/dist/rbac/roleManager.js +60 -5
  66. package/dist/rbac/roleModel.js +1 -1
  67. package/dist/rbac/statements.d.ts +1 -1
  68. package/dist/rbac/statements.js +13 -1
  69. package/dist/rbac/types.d.ts +12 -0
  70. package/dist/rbac/userWriteGuards.d.ts +50 -0
  71. package/dist/rbac/userWriteGuards.js +156 -0
  72. package/dist/realtime/changeStreamWatcher.d.ts +4 -1
  73. package/dist/realtime/changeStreamWatcher.js +157 -73
  74. package/dist/realtime/queryMatcher.d.ts +3 -0
  75. package/dist/realtime/queryMatcher.js +25 -10
  76. package/dist/realtime/realtimeApp.d.ts +16 -1
  77. package/dist/realtime/realtimeApp.js +76 -8
  78. package/dist/realtime/socketAuth.d.ts +17 -6
  79. package/dist/realtime/socketAuth.js +77 -16
  80. package/dist/realtime/types.d.ts +8 -5
  81. package/dist/requestContext.d.ts +22 -0
  82. package/dist/requestContext.js +22 -1
  83. package/dist/seedRunner.js +3 -1
  84. package/dist/sortFields.d.ts +33 -0
  85. package/dist/sortFields.js +55 -0
  86. package/dist/sync/executors.js +140 -2
  87. package/dist/sync/models.d.ts +2 -0
  88. package/dist/sync/models.js +5 -0
  89. package/dist/sync/mutationHandler.js +70 -7
  90. package/dist/sync/routes.js +4 -2
  91. package/dist/sync/syncSeqPlugin.js +6 -5
  92. package/dist/terrenoApp.d.ts +14 -0
  93. package/dist/terrenoApp.js +21 -6
  94. package/dist/types/mcpOAuth.d.ts +101 -0
  95. package/dist/types/mcpOAuth.js +2 -0
  96. package/dist/types/mcpServiceToken.d.ts +8 -0
  97. package/package.json +3 -3
  98. package/src/actions.test.ts +118 -0
  99. package/src/actions.ts +139 -17
  100. package/src/api.arrayOperations.test.ts +78 -0
  101. package/src/api.test.ts +36 -0
  102. package/src/api.ts +76 -4
  103. package/src/auth.test.ts +521 -3
  104. package/src/auth.ts +171 -17
  105. package/src/authRecovery.test.ts +99 -0
  106. package/src/authRecovery.ts +117 -5
  107. package/src/authVerification.test.ts +3 -3
  108. package/src/betterAuth.ts +104 -1
  109. package/src/betterAuthApp.test.ts +634 -1
  110. package/src/betterAuthApp.ts +28 -0
  111. package/src/betterAuthOAuthHandoff.test.ts +946 -0
  112. package/src/betterAuthOAuthHandoff.ts +375 -0
  113. package/src/betterAuthSetup.test.ts +393 -4
  114. package/src/betterAuthSetup.ts +402 -29
  115. package/src/expressServer.test.ts +93 -0
  116. package/src/expressServer.ts +81 -14
  117. package/src/githubAuth.test.ts +448 -6
  118. package/src/githubAuth.ts +276 -34
  119. package/src/index.ts +35 -1
  120. package/src/mcp/actionTools.test.ts +498 -0
  121. package/src/mcp/actionTools.ts +220 -0
  122. package/src/mcp/auth.test.ts +114 -1
  123. package/src/mcp/auth.ts +122 -35
  124. package/src/mcp/createMCPRequest.ts +8 -2
  125. package/src/mcp/handlers.test.ts +27 -0
  126. package/src/mcp/handlers.ts +21 -6
  127. package/src/mcp/oauth.test.ts +1026 -0
  128. package/src/mcp/oauth.ts +798 -0
  129. package/src/mcp/oauthMetadata.ts +234 -0
  130. package/src/mcp/registry.ts +11 -0
  131. package/src/mcp/server.ts +54 -14
  132. package/src/mcp/serviceTokens.ts +16 -3
  133. package/src/mcp/toolExecution.ts +67 -0
  134. package/src/mcp/toolGenerator.ts +27 -83
  135. package/src/mcp/types.ts +4 -4
  136. package/src/models/mcpOAuthAuthorization.ts +97 -0
  137. package/src/models/mcpOAuthClient.ts +49 -0
  138. package/src/models/mcpOAuthRevokedFamily.ts +47 -0
  139. package/src/models/mcpOAuthToken.test.ts +82 -0
  140. package/src/models/mcpOAuthToken.ts +195 -0
  141. package/src/models/mcpServiceToken.ts +26 -2
  142. package/src/permissions.ts +17 -0
  143. package/src/rateLimit/policies.ts +54 -10
  144. package/src/rateLimit/rateLimit.test.ts +41 -0
  145. package/src/rbac/access.ts +1 -0
  146. package/src/rbac/membershipOrgAdminSource.ts +5 -0
  147. package/src/rbac/modelRouterAccess.ts +40 -23
  148. package/src/rbac/realtimeAccess.test.ts +43 -0
  149. package/src/rbac/realtimeAccess.ts +23 -3
  150. package/src/rbac/resolve.test.ts +179 -1
  151. package/src/rbac/resolve.ts +78 -9
  152. package/src/rbac/roleManager.test.ts +132 -0
  153. package/src/rbac/roleManager.ts +69 -5
  154. package/src/rbac/roleModel.ts +1 -1
  155. package/src/rbac/statements.ts +14 -1
  156. package/src/rbac/types.ts +12 -0
  157. package/src/rbac/userWriteGuards.test.ts +407 -0
  158. package/src/rbac/userWriteGuards.ts +185 -0
  159. package/src/realtime/changeStreamWatcher.ts +203 -75
  160. package/src/realtime/queryMatcher.ts +30 -13
  161. package/src/realtime/realtime.test.ts +132 -0
  162. package/src/realtime/realtimeApp.ts +94 -10
  163. package/src/realtime/realtimeAppSetup.test.ts +282 -1
  164. package/src/realtime/socketAuth.test.ts +140 -8
  165. package/src/realtime/socketAuth.ts +90 -19
  166. package/src/realtime/types.ts +8 -5
  167. package/src/requestContext.ts +52 -1
  168. package/src/requestCredential.test.ts +89 -0
  169. package/src/seedRunner.test.ts +21 -0
  170. package/src/seedRunner.ts +3 -1
  171. package/src/sortFields.ts +69 -0
  172. package/src/sync/executors.test.ts +382 -3
  173. package/src/sync/executors.ts +179 -4
  174. package/src/sync/models.ts +8 -0
  175. package/src/sync/mutationHandler.test.ts +166 -2
  176. package/src/sync/mutationHandler.ts +97 -5
  177. package/src/sync/routes.ts +4 -2
  178. package/src/sync/syncFrontier.test.ts +11 -0
  179. package/src/sync/syncPhaseC.test.ts +18 -0
  180. package/src/sync/syncSeqPlugin.ts +6 -5
  181. package/src/sync/syncSocket.test.ts +92 -0
  182. package/src/terrenoApp.ts +36 -21
  183. package/src/types/mcpOAuth.ts +129 -0
  184. package/src/types/mcpServiceToken.ts +6 -1
@@ -0,0 +1,234 @@
1
+ /**
2
+ * Option resolution, RFC 9728 / RFC 8414 discovery documents, and the `/mcp` 401 challenge for
3
+ * MCP OAuth. Kept apart from the authorization-server routes in `oauth.ts` so any auth stack
4
+ * can serve the same metadata and challenge.
5
+ */
6
+ import type {Response} from "express";
7
+
8
+ import {APIError} from "../errors";
9
+
10
+ const DEFAULT_ACCESS_TOKEN_TTL_SECONDS = 60 * 60;
11
+ const DEFAULT_REFRESH_TOKEN_TTL_SECONDS = 30 * 24 * 60 * 60;
12
+ const DEFAULT_AUTHORIZATION_REQUEST_TTL_SECONDS = 10 * 60;
13
+ const DEFAULT_AUTHORIZATION_CODE_TTL_SECONDS = 60;
14
+ const DEFAULT_SCOPES = ["mcp"];
15
+
16
+ export const SUPPORTED_GRANT_TYPES = ["authorization_code", "refresh_token"];
17
+ export const SUPPORTED_RESPONSE_TYPES = ["code"];
18
+ export const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);
19
+
20
+ export interface McpOAuthOptions {
21
+ /** Turns the authorization server on. Every other field is ignored while false. */
22
+ enabled: boolean;
23
+ /**
24
+ * Public origin of this API, for example `https://api.example.com`. It is the RFC 8414
25
+ * `issuer`, and every endpoint URL in the metadata is built from it. It must be an origin with
26
+ * no path, because the well-known documents are served from the root of this app.
27
+ */
28
+ issuer: string;
29
+ /**
30
+ * App page that hosts the consent screen. `/oauth/authorize` redirects the browser here with
31
+ * `?request=<id>` added. The page reads the request with `GET /oauth/authorize/:request` and
32
+ * posts the user's decision to `/oauth/authorize/:request/approve` or `/deny`.
33
+ */
34
+ consentUrl: string;
35
+ /**
36
+ * Mount RFC 7591 dynamic client registration at `POST /oauth/register` and advertise it in the
37
+ * metadata. Default: false. The endpoint is unauthenticated, so anyone who can reach the API
38
+ * can create a client; the consent screen is then the only gate. While off, only clients you
39
+ * create as `McpOAuthClient` documents can run the flow, and `/oauth/register` returns 404.
40
+ */
41
+ dynamicClientRegistration?: boolean;
42
+ /**
43
+ * Hostnames a registering client may put redirect URIs on, for example
44
+ * `["claude.ai", "chatgpt.com"]`. Required with `dynamicClientRegistration`, unused without it.
45
+ * `*.example.com` matches any subdomain. Add `localhost` to allow loopback `http://` redirects
46
+ * for local clients.
47
+ */
48
+ allowedRedirectHosts?: string[];
49
+ /** RFC 8707 resource identifier for `/mcp`. Default: `${issuer}/mcp`. */
50
+ resource?: string;
51
+ /** Scopes advertised and accepted. Default: `["mcp"]`. */
52
+ scopesSupported?: string[];
53
+ /** Access token lifetime. Default: 3600 (one hour). */
54
+ accessTokenTtlSeconds?: number;
55
+ /** Refresh token lifetime. Default: 30 days. */
56
+ refreshTokenTtlSeconds?: number;
57
+ /** How long a pending authorization request waits for a consent decision. Default: 600. */
58
+ authorizationRequestTtlSeconds?: number;
59
+ /** How long an issued authorization code can be exchanged. Default: 60. */
60
+ authorizationCodeTtlSeconds?: number;
61
+ }
62
+
63
+ export type McpOAuthAppOption = McpOAuthOptions;
64
+
65
+ export interface ResolvedMcpOAuthOptions {
66
+ accessTokenTtlSeconds: number;
67
+ allowedRedirectHosts: string[];
68
+ authorizationCodeTtlSeconds: number;
69
+ authorizationRequestTtlSeconds: number;
70
+ consentUrl: string;
71
+ dynamicClientRegistration: boolean;
72
+ issuer: string;
73
+ refreshTokenTtlSeconds: number;
74
+ resource: string;
75
+ /** URL of the RFC 9728 protected-resource metadata for {@link resource}. */
76
+ resourceMetadataUrl: string;
77
+ scopesSupported: string[];
78
+ }
79
+
80
+ const misconfigured = (detail: string): APIError =>
81
+ new APIError({
82
+ code: "mcp-oauth-misconfigured",
83
+ detail,
84
+ status: 500,
85
+ title: "MCP OAuth is misconfigured",
86
+ });
87
+
88
+ const parseAbsoluteUrl = (value: string, field: string): URL => {
89
+ try {
90
+ return new URL(value);
91
+ } catch {
92
+ throw misconfigured(`mcpOAuth.${field} must be an absolute URL, got "${value}"`);
93
+ }
94
+ };
95
+
96
+ const positiveInteger = (value: number | undefined, fallback: number, field: string): number => {
97
+ if (value === undefined) {
98
+ return fallback;
99
+ }
100
+ if (!Number.isInteger(value) || value <= 0) {
101
+ throw misconfigured(`mcpOAuth.${field} must be a positive integer`);
102
+ }
103
+ return value;
104
+ };
105
+
106
+ /** RFC 9728 §3.1: the well-known segment goes between the host and the resource's path. */
107
+ export const protectedResourceMetadataPath = (resource: string): string => {
108
+ const {pathname} = new URL(resource);
109
+ const suffix = pathname === "/" ? "" : pathname.replace(/\/$/, "");
110
+ return `/.well-known/oauth-protected-resource${suffix}`;
111
+ };
112
+
113
+ /**
114
+ * Validate and default the `mcpOAuth` TerrenoApp option. Returns undefined while disabled.
115
+ * Misconfiguration throws at boot rather than failing the first client's flow.
116
+ */
117
+ export const resolveMcpOAuthOption = (
118
+ option: McpOAuthAppOption | undefined
119
+ ): ResolvedMcpOAuthOptions | undefined => {
120
+ if (!option?.enabled) {
121
+ return undefined;
122
+ }
123
+ const issuerUrl = parseAbsoluteUrl(option.issuer, "issuer");
124
+ if (issuerUrl.pathname !== "/" || issuerUrl.search || issuerUrl.hash) {
125
+ throw misconfigured("mcpOAuth.issuer must be an origin with no path, query, or fragment");
126
+ }
127
+ if (issuerUrl.protocol !== "https:" && !LOOPBACK_HOSTS.has(issuerUrl.hostname)) {
128
+ throw misconfigured("mcpOAuth.issuer must use https outside localhost");
129
+ }
130
+ parseAbsoluteUrl(option.consentUrl, "consentUrl");
131
+ const dynamicClientRegistration = option.dynamicClientRegistration === true;
132
+ const allowedRedirectHosts = option.allowedRedirectHosts ?? [];
133
+ if (dynamicClientRegistration && allowedRedirectHosts.length === 0) {
134
+ throw misconfigured(
135
+ "mcpOAuth.allowedRedirectHosts must list at least one host when dynamicClientRegistration is on"
136
+ );
137
+ }
138
+ const issuer = issuerUrl.origin;
139
+ const resource = option.resource ?? `${issuer}/mcp`;
140
+ parseAbsoluteUrl(resource, "resource");
141
+ const scopesSupported = option.scopesSupported ?? DEFAULT_SCOPES;
142
+ if (scopesSupported.length === 0) {
143
+ throw misconfigured("mcpOAuth.scopesSupported must list at least one scope");
144
+ }
145
+ return {
146
+ accessTokenTtlSeconds: positiveInteger(
147
+ option.accessTokenTtlSeconds,
148
+ DEFAULT_ACCESS_TOKEN_TTL_SECONDS,
149
+ "accessTokenTtlSeconds"
150
+ ),
151
+ allowedRedirectHosts: allowedRedirectHosts.map((host) => host.toLowerCase()),
152
+ authorizationCodeTtlSeconds: positiveInteger(
153
+ option.authorizationCodeTtlSeconds,
154
+ DEFAULT_AUTHORIZATION_CODE_TTL_SECONDS,
155
+ "authorizationCodeTtlSeconds"
156
+ ),
157
+ authorizationRequestTtlSeconds: positiveInteger(
158
+ option.authorizationRequestTtlSeconds,
159
+ DEFAULT_AUTHORIZATION_REQUEST_TTL_SECONDS,
160
+ "authorizationRequestTtlSeconds"
161
+ ),
162
+ consentUrl: option.consentUrl,
163
+ dynamicClientRegistration,
164
+ issuer,
165
+ refreshTokenTtlSeconds: positiveInteger(
166
+ option.refreshTokenTtlSeconds,
167
+ DEFAULT_REFRESH_TOKEN_TTL_SECONDS,
168
+ "refreshTokenTtlSeconds"
169
+ ),
170
+ resource,
171
+ resourceMetadataUrl: `${issuer}${protectedResourceMetadataPath(resource)}`,
172
+ scopesSupported,
173
+ };
174
+ };
175
+
176
+ /**
177
+ * Protocol responses bypass `res.json`, which TerrenoApp wraps to add `requestId`, so clients
178
+ * get exactly the RFC-defined members.
179
+ */
180
+ export const sendProtocolJson = (res: Response, status: number, body: unknown): void => {
181
+ res.status(status).type("application/json").send(JSON.stringify(body));
182
+ };
183
+
184
+ /** RFC 9728 protected-resource metadata. */
185
+ export const buildProtectedResourceMetadata = (
186
+ oauth: ResolvedMcpOAuthOptions
187
+ ): Record<string, unknown> => ({
188
+ authorization_servers: [oauth.issuer],
189
+ bearer_methods_supported: ["header"],
190
+ resource: oauth.resource,
191
+ scopes_supported: oauth.scopesSupported,
192
+ });
193
+
194
+ /** RFC 8414 authorization-server metadata. */
195
+ export const buildAuthorizationServerMetadata = (
196
+ oauth: ResolvedMcpOAuthOptions
197
+ ): Record<string, unknown> => ({
198
+ ...(oauth.dynamicClientRegistration
199
+ ? {registration_endpoint: `${oauth.issuer}/oauth/register`}
200
+ : {}),
201
+ authorization_endpoint: `${oauth.issuer}/oauth/authorize`,
202
+ authorization_response_iss_parameter_supported: true,
203
+ code_challenge_methods_supported: ["S256"],
204
+ grant_types_supported: SUPPORTED_GRANT_TYPES,
205
+ issuer: oauth.issuer,
206
+ response_types_supported: SUPPORTED_RESPONSE_TYPES,
207
+ revocation_endpoint: `${oauth.issuer}/oauth/revoke`,
208
+ revocation_endpoint_auth_methods_supported: ["none"],
209
+ scopes_supported: oauth.scopesSupported,
210
+ token_endpoint: `${oauth.issuer}/oauth/token`,
211
+ token_endpoint_auth_methods_supported: ["none"],
212
+ });
213
+
214
+ /**
215
+ * Answer an unauthenticated `/mcp` request with the RFC 9728 challenge that starts a client's
216
+ * OAuth discovery. `invalidToken` marks a presented-but-rejected credential so clients refresh.
217
+ */
218
+ export const sendMcpOAuthChallenge = (
219
+ res: Response,
220
+ oauth: ResolvedMcpOAuthOptions,
221
+ {invalidToken}: {invalidToken: boolean}
222
+ ): void => {
223
+ const params = [`resource_metadata="${oauth.resourceMetadataUrl}"`];
224
+ if (invalidToken) {
225
+ params.push('error="invalid_token"');
226
+ }
227
+ res.setHeader("WWW-Authenticate", `Bearer ${params.join(", ")}`);
228
+ sendProtocolJson(res, 401, {
229
+ error: invalidToken ? "invalid_token" : "unauthorized",
230
+ error_description: invalidToken
231
+ ? "The access token is invalid, expired, or revoked"
232
+ : "Authentication required",
233
+ });
234
+ };
@@ -38,6 +38,17 @@ export const registerMCPModel = <T>(
38
38
  });
39
39
  };
40
40
 
41
+ /**
42
+ * Catalog a pathless modelRouter whose actions opt into MCP but whose CRUD does not, so the
43
+ * action tools can find its model and options. Routers with a path are cataloged already.
44
+ */
45
+ export const registerMCPActionModel = <T>(
46
+ model: Model<T>,
47
+ options: ModelRouterOptions<T>
48
+ ): void => {
49
+ registerCollection({model, options, routePath: mcpRoutePathForModel(model)});
50
+ };
51
+
41
52
  export const updateMCPRegistryOptions = (
42
53
  modelName: string,
43
54
  options: ModelRouterOptions<unknown>
package/src/mcp/server.ts CHANGED
@@ -1,20 +1,31 @@
1
+ import {AsyncLocalStorage} from "node:async_hooks";
1
2
  import {toNodeHandler} from "@modelcontextprotocol/node";
2
3
  import {createMcpHandler, McpServer} from "@modelcontextprotocol/server";
3
- import type {Application, Request, Response} from "express";
4
+ import type {Application, NextFunction, Request, Response} from "express";
4
5
 
5
- import type {UserModel} from "../auth";
6
+ import type {User, UserModel} from "../auth";
6
7
  import type {BetterAuthInstance} from "../betterAuthSetup";
7
8
  import {logger} from "../logger";
8
9
  import {setRequestContext} from "../requestContext";
9
- import {extractUserFromHeaders, type MCPAuthContext} from "./auth";
10
+ import {extractAuthFromHeaders, type MCPAuthContext, type MCPAuthResult} from "./auth";
11
+ import {type ResolvedMcpOAuthOptions, sendMcpOAuthChallenge} from "./oauthMetadata";
10
12
  import {getAllMCPTools, type MCPToolDefinition} from "./toolGenerator";
11
13
 
12
14
  export interface MCPServerOptions {
13
15
  userModel: UserModel;
14
16
  betterAuth?: BetterAuthInstance;
15
17
  mcpServiceTokens?: boolean;
18
+ /**
19
+ * Resolved `mcpOAuth` options. When set, `/mcp` accepts OAuth access tokens and answers a
20
+ * request without valid credentials with a 401 RFC 9728 challenge.
21
+ */
22
+ mcpOAuth?: ResolvedMcpOAuthOptions;
16
23
  }
17
24
 
25
+ // Auth is resolved once in the Express handler (which may answer 401) and read back by the
26
+ // per-request MCP server factory, which only sees the request's headers.
27
+ const mcpAuthStorage = new AsyncLocalStorage<{auth?: MCPAuthResult}>();
28
+
18
29
  export const mountMCPServer = (app: Application, options: MCPServerOptions): void => {
19
30
  const tools = getAllMCPTools();
20
31
  if (tools.length === 0) {
@@ -22,6 +33,7 @@ export const mountMCPServer = (app: Application, options: MCPServerOptions): voi
22
33
  }
23
34
  const authContext: MCPAuthContext = {
24
35
  betterAuth: options.betterAuth,
36
+ mcpOAuth: Boolean(options.mcpOAuth),
25
37
  mcpServiceTokens: options.mcpServiceTokens,
26
38
  userModel: options.userModel,
27
39
  };
@@ -32,15 +44,17 @@ export const mountMCPServer = (app: Application, options: MCPServerOptions): voi
32
44
  // 2025-era clients through the SDK's stateless legacy fallback.
33
45
  const handler = createMcpHandler(
34
46
  async ({requestInfo}) => {
47
+ const stored = mcpAuthStorage.getStore();
48
+ if (stored) {
49
+ return createMcpServerInstance(tools, stored.auth?.user);
50
+ }
35
51
  const headers: Record<string, string> = {};
36
52
  requestInfo?.headers.forEach((value, key) => {
37
53
  headers[key] = value;
38
54
  });
39
- const user = await extractUserFromHeaders(headers, authContext);
40
- if (user?.id) {
41
- setRequestContext({userId: user.id});
42
- }
43
- return createMcpServerInstance(tools, user);
55
+ const auth = await extractAuthFromHeaders(headers, authContext);
56
+ recordMcpAuth(auth);
57
+ return createMcpServerInstance(tools, auth?.user);
44
58
  },
45
59
  {
46
60
  legacy: "stateless",
@@ -50,16 +64,42 @@ export const mountMCPServer = (app: Application, options: MCPServerOptions): voi
50
64
  );
51
65
  const nodeHandler = toNodeHandler(handler);
52
66
 
53
- app.all("/mcp", (req: Request, res: Response) => {
67
+ app.all("/mcp", async (req: Request, res: Response, next: NextFunction) => {
68
+ let auth: MCPAuthResult | undefined;
69
+ try {
70
+ auth = await extractAuthFromHeaders(req.headers, authContext);
71
+ } catch (error) {
72
+ next(error);
73
+ return;
74
+ }
75
+ if (!auth && options.mcpOAuth) {
76
+ sendMcpOAuthChallenge(res, options.mcpOAuth, {
77
+ invalidToken: Boolean(req.headers.authorization),
78
+ });
79
+ return;
80
+ }
81
+ recordMcpAuth(auth);
54
82
  // express.json() consumed the request stream, so pass its parsed body explicitly.
55
- void nodeHandler(req, res, req.body);
83
+ mcpAuthStorage.run({auth}, () => {
84
+ void nodeHandler(req, res, req.body);
85
+ });
86
+ });
87
+ };
88
+
89
+ /** Permission functions and hooks read the caller's credential type from the request context. */
90
+ const recordMcpAuth = (auth: MCPAuthResult | undefined): void => {
91
+ if (!auth?.user.id) {
92
+ setRequestContext({credential: undefined, oauthScopes: undefined});
93
+ return;
94
+ }
95
+ setRequestContext({
96
+ credential: auth.credential,
97
+ oauthScopes: auth.credential === "oauth" ? auth.scopes : undefined,
98
+ userId: auth.user.id,
56
99
  });
57
100
  };
58
101
 
59
- const createMcpServerInstance = (
60
- tools: MCPToolDefinition[],
61
- user?: Awaited<ReturnType<typeof extractUserFromHeaders>>
62
- ): McpServer => {
102
+ const createMcpServerInstance = (tools: MCPToolDefinition[], user?: User): McpServer => {
63
103
  const server = new McpServer(
64
104
  {
65
105
  name: "terreno-api-mcp",
@@ -5,9 +5,10 @@ import mongoose from "mongoose";
5
5
  import {asyncHandler, type OpenApiMiddleware} from "../api";
6
6
  import {authenticateMiddleware, type User} from "../auth";
7
7
  import {BadRequestError, NotFoundError, UnauthorizedError} from "../errors";
8
- import {McpServiceToken} from "../models/mcpServiceToken";
8
+ import {MCP_SERVICE_TOKEN_PREFIX, McpServiceToken} from "../models/mcpServiceToken";
9
9
  import {createOpenApiBuilder} from "../openApiBuilder";
10
10
  import type {McpServiceTokenDocument} from "../types/mcpServiceToken";
11
+ import {userTokenEpoch} from "./auth";
11
12
 
12
13
  export const MAX_ACTIVE_MCP_SERVICE_TOKENS = 10;
13
14
 
@@ -51,7 +52,7 @@ const bearerFromRequest = (req: Request): string | undefined => {
51
52
 
52
53
  const rejectMcpServiceTokenBearer = (req: Request, _res: Response, next: NextFunction): void => {
53
54
  const token = bearerFromRequest(req);
54
- if (token?.startsWith("mcp_")) {
55
+ if (token?.startsWith(MCP_SERVICE_TOKEN_PREFIX)) {
55
56
  next(new UnauthorizedError("MCP service tokens cannot manage service tokens"));
56
57
  return;
57
58
  }
@@ -193,6 +194,10 @@ export const addMcpServiceTokenRoutes = (
193
194
  const user = requireAuthenticatedUser(req);
194
195
  const name = parseName(req.body?.name);
195
196
  const expiresAt = parseExpiresAt(req.body?.expiresAt);
197
+ await McpServiceToken.revokeOutdatedForUser({
198
+ _id: user._id,
199
+ tokenEpoch: userTokenEpoch(user),
200
+ });
196
201
  const activeCount = await McpServiceToken.countActiveForUser(
197
202
  new mongoose.Types.ObjectId(String(user._id))
198
203
  );
@@ -201,7 +206,10 @@ export const addMcpServiceTokenRoutes = (
201
206
  title: `Maximum of ${MAX_ACTIVE_MCP_SERVICE_TOKENS} active MCP service tokens`,
202
207
  });
203
208
  }
204
- const issued = await McpServiceToken.issueFor({_id: user._id}, {expiresAt, name});
209
+ const issued = await McpServiceToken.issueFor(
210
+ {_id: user._id, tokenEpoch: userTokenEpoch(user)},
211
+ {expiresAt, name}
212
+ );
205
213
  return res.json({
206
214
  data: {
207
215
  created: issued.mcpServiceToken.created.toISOString(),
@@ -244,6 +252,11 @@ export const addMcpServiceTokenRoutes = (
244
252
  const user = requireAuthenticatedUser(req);
245
253
  const page = parsePage(req.query.page);
246
254
  const limit = parseLimit(req.query.limit);
255
+ // Tokens from before a password reset or session revocation no longer work; list them so.
256
+ await McpServiceToken.revokeOutdatedForUser({
257
+ _id: user._id,
258
+ tokenEpoch: userTokenEpoch(user),
259
+ });
247
260
  const filter = {userId: new mongoose.Types.ObjectId(String(user._id))};
248
261
  const total = await McpServiceToken.countDocuments(filter);
249
262
  const docs = await McpServiceToken.find(filter)
@@ -0,0 +1,67 @@
1
+ import type {User} from "../auth";
2
+ import {createScopedLogger} from "../logger";
3
+ import {setRequestContext} from "../requestContext";
4
+ import {getMCPErrorCause} from "./handlers";
5
+ import type {MCPToolResult} from "./types";
6
+
7
+ const getToolErrorMessage = (result: MCPToolResult): string => {
8
+ const text = result.content[0]?.text;
9
+ if (!text) {
10
+ return "Unknown MCP tool error";
11
+ }
12
+ try {
13
+ const parsed = JSON.parse(text) as {error?: unknown};
14
+ return typeof parsed.error === "string" ? parsed.error : text;
15
+ } catch {
16
+ return text;
17
+ }
18
+ };
19
+
20
+ /**
21
+ * Run one tool call with the caller in the request context and an audit log line. Refusals
22
+ * (permission, not-found, input errors) log as warnings; results carrying a cause and thrown
23
+ * errors are captured as exceptions.
24
+ */
25
+ export const executeTool = async ({
26
+ labels,
27
+ run,
28
+ user,
29
+ }: {
30
+ labels: Record<string, string>;
31
+ run: () => Promise<MCPToolResult>;
32
+ user?: User;
33
+ }): Promise<MCPToolResult> => {
34
+ const userId = user?.id ?? (user?._id ? String(user._id) : undefined);
35
+ if (userId) {
36
+ setRequestContext({userId});
37
+ }
38
+ const log = createScopedLogger({labels, prefix: "[MCPTool]"});
39
+ const startedAt = performance.now();
40
+
41
+ try {
42
+ const result = await run();
43
+ const durationMs = Math.round(performance.now() - startedAt);
44
+ if (!result.isError) {
45
+ log.info("MCP tool call succeeded", {durationMs});
46
+ return result;
47
+ }
48
+
49
+ const cause = getMCPErrorCause(result);
50
+ const message = getToolErrorMessage(result);
51
+ if (cause !== undefined) {
52
+ // ScopedLogger.catch records the original exception and captures it in Sentry when enabled.
53
+ log.catch(cause);
54
+ log.error("MCP tool call failed", {durationMs, message});
55
+ } else {
56
+ // Permission, not-found, and input errors are expected failures: retain an audit trail
57
+ // and Sentry log without reporting them as exceptions.
58
+ log.warn("MCP tool call refused", {durationMs, message});
59
+ }
60
+ return result;
61
+ } catch (error) {
62
+ const durationMs = Math.round(performance.now() - startedAt);
63
+ log.catch(error);
64
+ log.error("MCP tool call crashed", {durationMs});
65
+ throw error;
66
+ }
67
+ };
@@ -1,22 +1,17 @@
1
1
  import {toJSONSchema, type ZodType} from "zod";
2
2
 
3
3
  import type {User} from "../auth";
4
- import {createScopedLogger} from "../logger";
5
- import {setRequestContext} from "../requestContext";
6
- import {
7
- getMCPErrorCause,
8
- handleCreate,
9
- handleDelete,
10
- handleList,
11
- handleRead,
12
- handleUpdate,
13
- } from "./handlers";
4
+ import {listCollections} from "../collectionRegistry";
5
+ import {APIError} from "../errors";
6
+ import {generateActionTools} from "./actionTools";
7
+ import {handleCreate, handleDelete, handleList, handleRead, handleUpdate} from "./handlers";
14
8
  import {getMCPCustomTools, getMCPRegistry} from "./registry";
15
9
  import {
16
10
  generateInputSchema,
17
11
  generateToolDescription,
18
12
  restWriteExcludeFields,
19
13
  } from "./schemaGenerator";
14
+ import {executeTool} from "./toolExecution";
20
15
  import type {
21
16
  MCPMethod,
22
17
  MCPRegistryEntry,
@@ -60,76 +55,6 @@ const METHOD_HANDLERS: Record<
60
55
  update: handleUpdate,
61
56
  };
62
57
 
63
- const getToolErrorMessage = (result: MCPToolResult): string => {
64
- const text = result.content[0]?.text;
65
- if (!text) {
66
- return "Unknown MCP tool error";
67
- }
68
- try {
69
- const parsed = JSON.parse(text) as {error?: unknown};
70
- return typeof parsed.error === "string" ? parsed.error : text;
71
- } catch {
72
- return text;
73
- }
74
- };
75
-
76
- const executeTool = async ({
77
- args,
78
- entry,
79
- handler,
80
- method,
81
- toolName,
82
- user,
83
- }: {
84
- args: MCPToolArgs;
85
- entry: MCPRegistryEntry;
86
- handler: (entry: MCPRegistryEntry, args: MCPToolArgs, user?: User) => Promise<MCPToolResult>;
87
- method: MCPMethod;
88
- toolName: string;
89
- user?: User;
90
- }): Promise<MCPToolResult> => {
91
- const userId = user?.id ?? (user?._id ? String(user._id) : undefined);
92
- if (userId) {
93
- setRequestContext({userId});
94
- }
95
- const log = createScopedLogger({
96
- labels: {
97
- mcpMethod: method,
98
- mcpModel: entry.modelName,
99
- mcpTool: toolName,
100
- },
101
- prefix: "[MCPTool]",
102
- });
103
- const startedAt = performance.now();
104
-
105
- try {
106
- const result = await handler(entry, args, user);
107
- const durationMs = Math.round(performance.now() - startedAt);
108
- if (!result.isError) {
109
- log.info("MCP tool call succeeded", {durationMs});
110
- return result;
111
- }
112
-
113
- const cause = getMCPErrorCause(result);
114
- const message = getToolErrorMessage(result);
115
- if (cause !== undefined) {
116
- // ScopedLogger.catch records the original exception and captures it in Sentry when enabled.
117
- log.catch(cause);
118
- log.error("MCP tool call failed", {durationMs, message});
119
- } else {
120
- // Permission, not-found, and input errors are expected failures: retain an audit trail
121
- // and Sentry log without reporting them as exceptions.
122
- log.warn("MCP tool call refused", {durationMs, message});
123
- }
124
- return result;
125
- } catch (error) {
126
- const durationMs = Math.round(performance.now() - startedAt);
127
- log.catch(error);
128
- log.error("MCP tool call crashed", {durationMs});
129
- throw error;
130
- }
131
- };
132
-
133
58
  export const generateToolsForEntry = (entry: MCPRegistryEntry): MCPToolDefinition[] => {
134
59
  const methods = entry.config.methods ?? ["list", "read"];
135
60
  const prefix = getToolPrefix(entry);
@@ -166,7 +91,11 @@ export const generateToolsForEntry = (entry: MCPRegistryEntry): MCPToolDefinitio
166
91
  restExcludeFields
167
92
  ),
168
93
  handler: (args: MCPToolArgs, user?: User) =>
169
- executeTool({args, entry, handler, method, toolName, user}),
94
+ executeTool({
95
+ labels: {mcpMethod: method, mcpModel: entry.modelName, mcpTool: toolName},
96
+ run: () => handler(entry, args, user),
97
+ user,
98
+ }),
170
99
  inputSchema: inputSchema as MCPToolInputSchema,
171
100
  name: toolName,
172
101
  zodSchema,
@@ -184,7 +113,10 @@ export const generateAllTools = (entries: MCPRegistryEntry[]): MCPToolDefinition
184
113
  return tools;
185
114
  };
186
115
 
187
- /** Model-router tools plus any custom tools registered with `registerMCPTool`. */
116
+ /**
117
+ * Model-router CRUD tools, modelRouter actions that opted in with `mcp`, and custom tools
118
+ * registered with `registerMCPTool`.
119
+ */
188
120
  export const getAllMCPTools = (): MCPToolDefinition[] => {
189
121
  const customTools: MCPToolDefinition[] = getMCPCustomTools().map((tool) => {
190
122
  return {
@@ -195,5 +127,17 @@ export const getAllMCPTools = (): MCPToolDefinition[] => {
195
127
  zodSchema: tool.zodSchema,
196
128
  };
197
129
  });
198
- return [...generateAllTools(getMCPRegistry()), ...customTools];
130
+ const baseTools = [...generateAllTools(getMCPRegistry()), ...customTools];
131
+ const actionTools = generateActionTools(listCollections());
132
+ const takenNames = new Set(baseTools.map((tool) => tool.name));
133
+ for (const tool of actionTools) {
134
+ if (takenNames.has(tool.name)) {
135
+ throw new APIError({
136
+ status: 500,
137
+ title: `MCP tool name "${tool.name}" is used by more than one tool. Give the action a unique mcp.name.`,
138
+ });
139
+ }
140
+ takenNames.add(tool.name);
141
+ }
142
+ return [...baseTools, ...actionTools];
199
143
  };
package/src/mcp/types.ts CHANGED
@@ -33,10 +33,10 @@ export interface MCPToolInputSchema {
33
33
  export type MCPDocument = HydratedDocument<Record<string, unknown>>;
34
34
 
35
35
  /**
36
- * Express-shaped request handed to modelRouter lifecycle hooks and response handlers
37
- * during an MCP tool call. Built by `createMCPRequest` as a stub: only `user`
38
- * and `body` are populated. `headers`, `query`, and `params` are always empty
39
- * objects — MCP does not forward HTTP request fields.
36
+ * Express-shaped request handed to modelRouter lifecycle hooks, response handlers, and
37
+ * action handlers during an MCP tool call. Built by `createMCPRequest` as a stub: `user` and
38
+ * `body` are populated, and action tools also fill `params.id` (instance actions) and `query`
39
+ * (GET actions). `headers` is always empty — MCP does not forward HTTP request fields.
40
40
  */
41
41
  export interface MCPRequest {
42
42
  body: MCPToolArgs;