@terreno/api 57.16.2 → 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,89 @@
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
+ export declare const SUPPORTED_GRANT_TYPES: string[];
8
+ export declare const SUPPORTED_RESPONSE_TYPES: string[];
9
+ export declare const LOOPBACK_HOSTS: Set<string>;
10
+ export interface McpOAuthOptions {
11
+ /** Turns the authorization server on. Every other field is ignored while false. */
12
+ enabled: boolean;
13
+ /**
14
+ * Public origin of this API, for example `https://api.example.com`. It is the RFC 8414
15
+ * `issuer`, and every endpoint URL in the metadata is built from it. It must be an origin with
16
+ * no path, because the well-known documents are served from the root of this app.
17
+ */
18
+ issuer: string;
19
+ /**
20
+ * App page that hosts the consent screen. `/oauth/authorize` redirects the browser here with
21
+ * `?request=<id>` added. The page reads the request with `GET /oauth/authorize/:request` and
22
+ * posts the user's decision to `/oauth/authorize/:request/approve` or `/deny`.
23
+ */
24
+ consentUrl: string;
25
+ /**
26
+ * Mount RFC 7591 dynamic client registration at `POST /oauth/register` and advertise it in the
27
+ * metadata. Default: false. The endpoint is unauthenticated, so anyone who can reach the API
28
+ * can create a client; the consent screen is then the only gate. While off, only clients you
29
+ * create as `McpOAuthClient` documents can run the flow, and `/oauth/register` returns 404.
30
+ */
31
+ dynamicClientRegistration?: boolean;
32
+ /**
33
+ * Hostnames a registering client may put redirect URIs on, for example
34
+ * `["claude.ai", "chatgpt.com"]`. Required with `dynamicClientRegistration`, unused without it.
35
+ * `*.example.com` matches any subdomain. Add `localhost` to allow loopback `http://` redirects
36
+ * for local clients.
37
+ */
38
+ allowedRedirectHosts?: string[];
39
+ /** RFC 8707 resource identifier for `/mcp`. Default: `${issuer}/mcp`. */
40
+ resource?: string;
41
+ /** Scopes advertised and accepted. Default: `["mcp"]`. */
42
+ scopesSupported?: string[];
43
+ /** Access token lifetime. Default: 3600 (one hour). */
44
+ accessTokenTtlSeconds?: number;
45
+ /** Refresh token lifetime. Default: 30 days. */
46
+ refreshTokenTtlSeconds?: number;
47
+ /** How long a pending authorization request waits for a consent decision. Default: 600. */
48
+ authorizationRequestTtlSeconds?: number;
49
+ /** How long an issued authorization code can be exchanged. Default: 60. */
50
+ authorizationCodeTtlSeconds?: number;
51
+ }
52
+ export type McpOAuthAppOption = McpOAuthOptions;
53
+ export interface ResolvedMcpOAuthOptions {
54
+ accessTokenTtlSeconds: number;
55
+ allowedRedirectHosts: string[];
56
+ authorizationCodeTtlSeconds: number;
57
+ authorizationRequestTtlSeconds: number;
58
+ consentUrl: string;
59
+ dynamicClientRegistration: boolean;
60
+ issuer: string;
61
+ refreshTokenTtlSeconds: number;
62
+ resource: string;
63
+ /** URL of the RFC 9728 protected-resource metadata for {@link resource}. */
64
+ resourceMetadataUrl: string;
65
+ scopesSupported: string[];
66
+ }
67
+ /** RFC 9728 §3.1: the well-known segment goes between the host and the resource's path. */
68
+ export declare const protectedResourceMetadataPath: (resource: string) => string;
69
+ /**
70
+ * Validate and default the `mcpOAuth` TerrenoApp option. Returns undefined while disabled.
71
+ * Misconfiguration throws at boot rather than failing the first client's flow.
72
+ */
73
+ export declare const resolveMcpOAuthOption: (option: McpOAuthAppOption | undefined) => ResolvedMcpOAuthOptions | undefined;
74
+ /**
75
+ * Protocol responses bypass `res.json`, which TerrenoApp wraps to add `requestId`, so clients
76
+ * get exactly the RFC-defined members.
77
+ */
78
+ export declare const sendProtocolJson: (res: Response, status: number, body: unknown) => void;
79
+ /** RFC 9728 protected-resource metadata. */
80
+ export declare const buildProtectedResourceMetadata: (oauth: ResolvedMcpOAuthOptions) => Record<string, unknown>;
81
+ /** RFC 8414 authorization-server metadata. */
82
+ export declare const buildAuthorizationServerMetadata: (oauth: ResolvedMcpOAuthOptions) => Record<string, unknown>;
83
+ /**
84
+ * Answer an unauthenticated `/mcp` request with the RFC 9728 challenge that starts a client's
85
+ * OAuth discovery. `invalidToken` marks a presented-but-rejected credential so clients refresh.
86
+ */
87
+ export declare const sendMcpOAuthChallenge: (res: Response, oauth: ResolvedMcpOAuthOptions, { invalidToken }: {
88
+ invalidToken: boolean;
89
+ }) => void;
@@ -0,0 +1,137 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.sendMcpOAuthChallenge = exports.buildAuthorizationServerMetadata = exports.buildProtectedResourceMetadata = exports.sendProtocolJson = exports.resolveMcpOAuthOption = exports.protectedResourceMetadataPath = exports.LOOPBACK_HOSTS = exports.SUPPORTED_RESPONSE_TYPES = exports.SUPPORTED_GRANT_TYPES = void 0;
4
+ const errors_1 = require("../errors");
5
+ const DEFAULT_ACCESS_TOKEN_TTL_SECONDS = 60 * 60;
6
+ const DEFAULT_REFRESH_TOKEN_TTL_SECONDS = 30 * 24 * 60 * 60;
7
+ const DEFAULT_AUTHORIZATION_REQUEST_TTL_SECONDS = 10 * 60;
8
+ const DEFAULT_AUTHORIZATION_CODE_TTL_SECONDS = 60;
9
+ const DEFAULT_SCOPES = ["mcp"];
10
+ exports.SUPPORTED_GRANT_TYPES = ["authorization_code", "refresh_token"];
11
+ exports.SUPPORTED_RESPONSE_TYPES = ["code"];
12
+ exports.LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);
13
+ const misconfigured = (detail) => new errors_1.APIError({
14
+ code: "mcp-oauth-misconfigured",
15
+ detail,
16
+ status: 500,
17
+ title: "MCP OAuth is misconfigured",
18
+ });
19
+ const parseAbsoluteUrl = (value, field) => {
20
+ try {
21
+ return new URL(value);
22
+ }
23
+ catch {
24
+ throw misconfigured(`mcpOAuth.${field} must be an absolute URL, got "${value}"`);
25
+ }
26
+ };
27
+ const positiveInteger = (value, fallback, field) => {
28
+ if (value === undefined) {
29
+ return fallback;
30
+ }
31
+ if (!Number.isInteger(value) || value <= 0) {
32
+ throw misconfigured(`mcpOAuth.${field} must be a positive integer`);
33
+ }
34
+ return value;
35
+ };
36
+ /** RFC 9728 §3.1: the well-known segment goes between the host and the resource's path. */
37
+ const protectedResourceMetadataPath = (resource) => {
38
+ const { pathname } = new URL(resource);
39
+ const suffix = pathname === "/" ? "" : pathname.replace(/\/$/, "");
40
+ return `/.well-known/oauth-protected-resource${suffix}`;
41
+ };
42
+ exports.protectedResourceMetadataPath = protectedResourceMetadataPath;
43
+ /**
44
+ * Validate and default the `mcpOAuth` TerrenoApp option. Returns undefined while disabled.
45
+ * Misconfiguration throws at boot rather than failing the first client's flow.
46
+ */
47
+ const resolveMcpOAuthOption = (option) => {
48
+ if (!option?.enabled) {
49
+ return undefined;
50
+ }
51
+ const issuerUrl = parseAbsoluteUrl(option.issuer, "issuer");
52
+ if (issuerUrl.pathname !== "/" || issuerUrl.search || issuerUrl.hash) {
53
+ throw misconfigured("mcpOAuth.issuer must be an origin with no path, query, or fragment");
54
+ }
55
+ if (issuerUrl.protocol !== "https:" && !exports.LOOPBACK_HOSTS.has(issuerUrl.hostname)) {
56
+ throw misconfigured("mcpOAuth.issuer must use https outside localhost");
57
+ }
58
+ parseAbsoluteUrl(option.consentUrl, "consentUrl");
59
+ const dynamicClientRegistration = option.dynamicClientRegistration === true;
60
+ const allowedRedirectHosts = option.allowedRedirectHosts ?? [];
61
+ if (dynamicClientRegistration && allowedRedirectHosts.length === 0) {
62
+ throw misconfigured("mcpOAuth.allowedRedirectHosts must list at least one host when dynamicClientRegistration is on");
63
+ }
64
+ const issuer = issuerUrl.origin;
65
+ const resource = option.resource ?? `${issuer}/mcp`;
66
+ parseAbsoluteUrl(resource, "resource");
67
+ const scopesSupported = option.scopesSupported ?? DEFAULT_SCOPES;
68
+ if (scopesSupported.length === 0) {
69
+ throw misconfigured("mcpOAuth.scopesSupported must list at least one scope");
70
+ }
71
+ return {
72
+ accessTokenTtlSeconds: positiveInteger(option.accessTokenTtlSeconds, DEFAULT_ACCESS_TOKEN_TTL_SECONDS, "accessTokenTtlSeconds"),
73
+ allowedRedirectHosts: allowedRedirectHosts.map((host) => host.toLowerCase()),
74
+ authorizationCodeTtlSeconds: positiveInteger(option.authorizationCodeTtlSeconds, DEFAULT_AUTHORIZATION_CODE_TTL_SECONDS, "authorizationCodeTtlSeconds"),
75
+ authorizationRequestTtlSeconds: positiveInteger(option.authorizationRequestTtlSeconds, DEFAULT_AUTHORIZATION_REQUEST_TTL_SECONDS, "authorizationRequestTtlSeconds"),
76
+ consentUrl: option.consentUrl,
77
+ dynamicClientRegistration,
78
+ issuer,
79
+ refreshTokenTtlSeconds: positiveInteger(option.refreshTokenTtlSeconds, DEFAULT_REFRESH_TOKEN_TTL_SECONDS, "refreshTokenTtlSeconds"),
80
+ resource,
81
+ resourceMetadataUrl: `${issuer}${(0, exports.protectedResourceMetadataPath)(resource)}`,
82
+ scopesSupported,
83
+ };
84
+ };
85
+ exports.resolveMcpOAuthOption = resolveMcpOAuthOption;
86
+ /**
87
+ * Protocol responses bypass `res.json`, which TerrenoApp wraps to add `requestId`, so clients
88
+ * get exactly the RFC-defined members.
89
+ */
90
+ const sendProtocolJson = (res, status, body) => {
91
+ res.status(status).type("application/json").send(JSON.stringify(body));
92
+ };
93
+ exports.sendProtocolJson = sendProtocolJson;
94
+ /** RFC 9728 protected-resource metadata. */
95
+ const buildProtectedResourceMetadata = (oauth) => ({
96
+ authorization_servers: [oauth.issuer],
97
+ bearer_methods_supported: ["header"],
98
+ resource: oauth.resource,
99
+ scopes_supported: oauth.scopesSupported,
100
+ });
101
+ exports.buildProtectedResourceMetadata = buildProtectedResourceMetadata;
102
+ /** RFC 8414 authorization-server metadata. */
103
+ const buildAuthorizationServerMetadata = (oauth) => ({
104
+ ...(oauth.dynamicClientRegistration
105
+ ? { registration_endpoint: `${oauth.issuer}/oauth/register` }
106
+ : {}),
107
+ authorization_endpoint: `${oauth.issuer}/oauth/authorize`,
108
+ authorization_response_iss_parameter_supported: true,
109
+ code_challenge_methods_supported: ["S256"],
110
+ grant_types_supported: exports.SUPPORTED_GRANT_TYPES,
111
+ issuer: oauth.issuer,
112
+ response_types_supported: exports.SUPPORTED_RESPONSE_TYPES,
113
+ revocation_endpoint: `${oauth.issuer}/oauth/revoke`,
114
+ revocation_endpoint_auth_methods_supported: ["none"],
115
+ scopes_supported: oauth.scopesSupported,
116
+ token_endpoint: `${oauth.issuer}/oauth/token`,
117
+ token_endpoint_auth_methods_supported: ["none"],
118
+ });
119
+ exports.buildAuthorizationServerMetadata = buildAuthorizationServerMetadata;
120
+ /**
121
+ * Answer an unauthenticated `/mcp` request with the RFC 9728 challenge that starts a client's
122
+ * OAuth discovery. `invalidToken` marks a presented-but-rejected credential so clients refresh.
123
+ */
124
+ const sendMcpOAuthChallenge = (res, oauth, { invalidToken }) => {
125
+ const params = [`resource_metadata="${oauth.resourceMetadataUrl}"`];
126
+ if (invalidToken) {
127
+ params.push('error="invalid_token"');
128
+ }
129
+ res.setHeader("WWW-Authenticate", `Bearer ${params.join(", ")}`);
130
+ (0, exports.sendProtocolJson)(res, 401, {
131
+ error: invalidToken ? "invalid_token" : "unauthorized",
132
+ error_description: invalidToken
133
+ ? "The access token is invalid, expired, or revoked"
134
+ : "Authentication required",
135
+ });
136
+ };
137
+ exports.sendMcpOAuthChallenge = sendMcpOAuthChallenge;
@@ -10,6 +10,11 @@ export interface MCPCustomTool {
10
10
  zodSchema: ZodType;
11
11
  }
12
12
  export declare const registerMCPModel: <T>(model: Model<T>, config: MCPConfig, options: ModelRouterOptions<T>) => void;
13
+ /**
14
+ * Catalog a pathless modelRouter whose actions opt into MCP but whose CRUD does not, so the
15
+ * action tools can find its model and options. Routers with a path are cataloged already.
16
+ */
17
+ export declare const registerMCPActionModel: <T>(model: Model<T>, options: ModelRouterOptions<T>) => void;
13
18
  export declare const updateMCPRegistryOptions: (modelName: string, options: ModelRouterOptions<unknown>) => void;
14
19
  export declare const registerMCPTool: (tool: MCPCustomTool) => void;
15
20
  export declare const getMCPRegistry: () => MCPRegistryEntry[];
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.clearMCPRegistry = exports.getMCPCustomTools = exports.getMCPRegistry = exports.registerMCPTool = exports.updateMCPRegistryOptions = exports.registerMCPModel = void 0;
3
+ exports.clearMCPRegistry = exports.getMCPCustomTools = exports.getMCPRegistry = exports.registerMCPTool = exports.updateMCPRegistryOptions = exports.registerMCPActionModel = exports.registerMCPModel = void 0;
4
4
  const collectionRegistry_1 = require("../collectionRegistry");
5
5
  const mcpCustomTools = [];
6
6
  const findCollectionByModelName = (modelName) => (0, collectionRegistry_1.listCollections)().find((record) => record.model.modelName === modelName);
@@ -13,6 +13,14 @@ const registerMCPModel = (model, config, options) => {
13
13
  });
14
14
  };
15
15
  exports.registerMCPModel = registerMCPModel;
16
+ /**
17
+ * Catalog a pathless modelRouter whose actions opt into MCP but whose CRUD does not, so the
18
+ * action tools can find its model and options. Routers with a path are cataloged already.
19
+ */
20
+ const registerMCPActionModel = (model, options) => {
21
+ (0, collectionRegistry_1.registerCollection)({ model, options, routePath: mcpRoutePathForModel(model) });
22
+ };
23
+ exports.registerMCPActionModel = registerMCPActionModel;
16
24
  const updateMCPRegistryOptions = (modelName, options) => {
17
25
  const existing = findCollectionByModelName(modelName);
18
26
  if (!existing) {
@@ -1,9 +1,15 @@
1
1
  import type { Application } from "express";
2
2
  import type { UserModel } from "../auth";
3
3
  import type { BetterAuthInstance } from "../betterAuthSetup";
4
+ import { type ResolvedMcpOAuthOptions } from "./oauthMetadata";
4
5
  export interface MCPServerOptions {
5
6
  userModel: UserModel;
6
7
  betterAuth?: BetterAuthInstance;
7
8
  mcpServiceTokens?: boolean;
9
+ /**
10
+ * Resolved `mcpOAuth` options. When set, `/mcp` accepts OAuth access tokens and answers a
11
+ * request without valid credentials with a 401 RFC 9728 challenge.
12
+ */
13
+ mcpOAuth?: ResolvedMcpOAuthOptions;
8
14
  }
9
15
  export declare const mountMCPServer: (app: Application, options: MCPServerOptions) => void;
@@ -1,12 +1,17 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.mountMCPServer = void 0;
4
+ const node_async_hooks_1 = require("node:async_hooks");
4
5
  const node_1 = require("@modelcontextprotocol/node");
5
6
  const server_1 = require("@modelcontextprotocol/server");
6
7
  const logger_1 = require("../logger");
7
8
  const requestContext_1 = require("../requestContext");
8
9
  const auth_1 = require("./auth");
10
+ const oauthMetadata_1 = require("./oauthMetadata");
9
11
  const toolGenerator_1 = require("./toolGenerator");
12
+ // Auth is resolved once in the Express handler (which may answer 401) and read back by the
13
+ // per-request MCP server factory, which only sees the request's headers.
14
+ const mcpAuthStorage = new node_async_hooks_1.AsyncLocalStorage();
10
15
  const mountMCPServer = (app, options) => {
11
16
  const tools = (0, toolGenerator_1.getAllMCPTools)();
12
17
  if (tools.length === 0) {
@@ -14,6 +19,7 @@ const mountMCPServer = (app, options) => {
14
19
  }
15
20
  const authContext = {
16
21
  betterAuth: options.betterAuth,
22
+ mcpOAuth: Boolean(options.mcpOAuth),
17
23
  mcpServiceTokens: options.mcpServiceTokens,
18
24
  userModel: options.userModel,
19
25
  };
@@ -21,27 +27,58 @@ const mountMCPServer = (app, options) => {
21
27
  // The 2026-07-28 handler is stateless: it creates one server per request and also serves
22
28
  // 2025-era clients through the SDK's stateless legacy fallback.
23
29
  const handler = (0, server_1.createMcpHandler)(async ({ requestInfo }) => {
30
+ const stored = mcpAuthStorage.getStore();
31
+ if (stored) {
32
+ return createMcpServerInstance(tools, stored.auth?.user);
33
+ }
24
34
  const headers = {};
25
35
  requestInfo?.headers.forEach((value, key) => {
26
36
  headers[key] = value;
27
37
  });
28
- const user = await (0, auth_1.extractUserFromHeaders)(headers, authContext);
29
- if (user?.id) {
30
- (0, requestContext_1.setRequestContext)({ userId: user.id });
31
- }
32
- return createMcpServerInstance(tools, user);
38
+ const auth = await (0, auth_1.extractAuthFromHeaders)(headers, authContext);
39
+ recordMcpAuth(auth);
40
+ return createMcpServerInstance(tools, auth?.user);
33
41
  }, {
34
42
  legacy: "stateless",
35
43
  onerror: (error) => logger_1.logger.catch(error),
36
44
  responseMode: "auto",
37
45
  });
38
46
  const nodeHandler = (0, node_1.toNodeHandler)(handler);
39
- app.all("/mcp", (req, res) => {
47
+ app.all("/mcp", async (req, res, next) => {
48
+ let auth;
49
+ try {
50
+ auth = await (0, auth_1.extractAuthFromHeaders)(req.headers, authContext);
51
+ }
52
+ catch (error) {
53
+ next(error);
54
+ return;
55
+ }
56
+ if (!auth && options.mcpOAuth) {
57
+ (0, oauthMetadata_1.sendMcpOAuthChallenge)(res, options.mcpOAuth, {
58
+ invalidToken: Boolean(req.headers.authorization),
59
+ });
60
+ return;
61
+ }
62
+ recordMcpAuth(auth);
40
63
  // express.json() consumed the request stream, so pass its parsed body explicitly.
41
- void nodeHandler(req, res, req.body);
64
+ mcpAuthStorage.run({ auth }, () => {
65
+ void nodeHandler(req, res, req.body);
66
+ });
42
67
  });
43
68
  };
44
69
  exports.mountMCPServer = mountMCPServer;
70
+ /** Permission functions and hooks read the caller's credential type from the request context. */
71
+ const recordMcpAuth = (auth) => {
72
+ if (!auth?.user.id) {
73
+ (0, requestContext_1.setRequestContext)({ credential: undefined, oauthScopes: undefined });
74
+ return;
75
+ }
76
+ (0, requestContext_1.setRequestContext)({
77
+ credential: auth.credential,
78
+ oauthScopes: auth.credential === "oauth" ? auth.scopes : undefined,
79
+ userId: auth.user.id,
80
+ });
81
+ };
45
82
  const createMcpServerInstance = (tools, user) => {
46
83
  const server = new server_1.McpServer({
47
84
  name: "terreno-api-mcp",
@@ -11,6 +11,7 @@ const auth_1 = require("../auth");
11
11
  const errors_1 = require("../errors");
12
12
  const mcpServiceToken_1 = require("../models/mcpServiceToken");
13
13
  const openApiBuilder_1 = require("../openApiBuilder");
14
+ const auth_2 = require("./auth");
14
15
  exports.MAX_ACTIVE_MCP_SERVICE_TOKENS = 10;
15
16
  const DEFAULT_LIST_LIMIT = 100;
16
17
  const MAX_LIST_LIMIT = 100;
@@ -36,7 +37,7 @@ const bearerFromRequest = (req) => {
36
37
  };
37
38
  const rejectMcpServiceTokenBearer = (req, _res, next) => {
38
39
  const token = bearerFromRequest(req);
39
- if (token?.startsWith("mcp_")) {
40
+ if (token?.startsWith(mcpServiceToken_1.MCP_SERVICE_TOKEN_PREFIX)) {
40
41
  next(new errors_1.UnauthorizedError("MCP service tokens cannot manage service tokens"));
41
42
  return;
42
43
  }
@@ -159,13 +160,17 @@ const addMcpServiceTokenRoutes = (app, options = {}) => {
159
160
  const user = requireAuthenticatedUser(req);
160
161
  const name = parseName(req.body?.name);
161
162
  const expiresAt = parseExpiresAt(req.body?.expiresAt);
163
+ await mcpServiceToken_1.McpServiceToken.revokeOutdatedForUser({
164
+ _id: user._id,
165
+ tokenEpoch: (0, auth_2.userTokenEpoch)(user),
166
+ });
162
167
  const activeCount = await mcpServiceToken_1.McpServiceToken.countActiveForUser(new mongoose_1.default.Types.ObjectId(String(user._id)));
163
168
  if (activeCount >= exports.MAX_ACTIVE_MCP_SERVICE_TOKENS) {
164
169
  throw new errors_1.BadRequestError({
165
170
  title: `Maximum of ${exports.MAX_ACTIVE_MCP_SERVICE_TOKENS} active MCP service tokens`,
166
171
  });
167
172
  }
168
- const issued = await mcpServiceToken_1.McpServiceToken.issueFor({ _id: user._id }, { expiresAt, name });
173
+ const issued = await mcpServiceToken_1.McpServiceToken.issueFor({ _id: user._id, tokenEpoch: (0, auth_2.userTokenEpoch)(user) }, { expiresAt, name });
169
174
  return res.json({
170
175
  data: {
171
176
  created: issued.mcpServiceToken.created.toISOString(),
@@ -201,6 +206,11 @@ const addMcpServiceTokenRoutes = (app, options = {}) => {
201
206
  const user = requireAuthenticatedUser(req);
202
207
  const page = parsePage(req.query.page);
203
208
  const limit = parseLimit(req.query.limit);
209
+ // Tokens from before a password reset or session revocation no longer work; list them so.
210
+ await mcpServiceToken_1.McpServiceToken.revokeOutdatedForUser({
211
+ _id: user._id,
212
+ tokenEpoch: (0, auth_2.userTokenEpoch)(user),
213
+ });
204
214
  const filter = { userId: new mongoose_1.default.Types.ObjectId(String(user._id)) };
205
215
  const total = await mcpServiceToken_1.McpServiceToken.countDocuments(filter);
206
216
  const docs = await mcpServiceToken_1.McpServiceToken.find(filter)
@@ -0,0 +1,12 @@
1
+ import type { User } from "../auth";
2
+ import type { MCPToolResult } from "./types";
3
+ /**
4
+ * Run one tool call with the caller in the request context and an audit log line. Refusals
5
+ * (permission, not-found, input errors) log as warnings; results carrying a cause and thrown
6
+ * errors are captured as exceptions.
7
+ */
8
+ export declare const executeTool: ({ labels, run, user, }: {
9
+ labels: Record<string, string>;
10
+ run: () => Promise<MCPToolResult>;
11
+ user?: User;
12
+ }) => Promise<MCPToolResult>;
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.executeTool = void 0;
4
+ const logger_1 = require("../logger");
5
+ const requestContext_1 = require("../requestContext");
6
+ const handlers_1 = require("./handlers");
7
+ const getToolErrorMessage = (result) => {
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);
14
+ return typeof parsed.error === "string" ? parsed.error : text;
15
+ }
16
+ catch {
17
+ return text;
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
+ const executeTool = async ({ labels, run, user, }) => {
26
+ const userId = user?.id ?? (user?._id ? String(user._id) : undefined);
27
+ if (userId) {
28
+ (0, requestContext_1.setRequestContext)({ userId });
29
+ }
30
+ const log = (0, logger_1.createScopedLogger)({ labels, prefix: "[MCPTool]" });
31
+ const startedAt = performance.now();
32
+ try {
33
+ const result = await run();
34
+ const durationMs = Math.round(performance.now() - startedAt);
35
+ if (!result.isError) {
36
+ log.info("MCP tool call succeeded", { durationMs });
37
+ return result;
38
+ }
39
+ const cause = (0, handlers_1.getMCPErrorCause)(result);
40
+ const message = getToolErrorMessage(result);
41
+ if (cause !== undefined) {
42
+ // ScopedLogger.catch records the original exception and captures it in Sentry when enabled.
43
+ log.catch(cause);
44
+ log.error("MCP tool call failed", { durationMs, message });
45
+ }
46
+ else {
47
+ // Permission, not-found, and input errors are expected failures: retain an audit trail
48
+ // and Sentry log without reporting them as exceptions.
49
+ log.warn("MCP tool call refused", { durationMs, message });
50
+ }
51
+ return result;
52
+ }
53
+ catch (error) {
54
+ const durationMs = Math.round(performance.now() - startedAt);
55
+ log.catch(error);
56
+ log.error("MCP tool call crashed", { durationMs });
57
+ throw error;
58
+ }
59
+ };
60
+ exports.executeTool = executeTool;
@@ -10,5 +10,8 @@ export interface MCPToolDefinition {
10
10
  }
11
11
  export declare const generateToolsForEntry: (entry: MCPRegistryEntry) => MCPToolDefinition[];
12
12
  export declare const generateAllTools: (entries: MCPRegistryEntry[]) => MCPToolDefinition[];
13
- /** Model-router tools plus any custom tools registered with `registerMCPTool`. */
13
+ /**
14
+ * Model-router CRUD tools, modelRouter actions that opted in with `mcp`, and custom tools
15
+ * registered with `registerMCPTool`.
16
+ */
14
17
  export declare const getAllMCPTools: () => MCPToolDefinition[];
@@ -2,11 +2,13 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getAllMCPTools = exports.generateAllTools = exports.generateToolsForEntry = void 0;
4
4
  const zod_1 = require("zod");
5
- const logger_1 = require("../logger");
6
- const requestContext_1 = require("../requestContext");
5
+ const collectionRegistry_1 = require("../collectionRegistry");
6
+ const errors_1 = require("../errors");
7
+ const actionTools_1 = require("./actionTools");
7
8
  const handlers_1 = require("./handlers");
8
9
  const registry_1 = require("./registry");
9
10
  const schemaGenerator_1 = require("./schemaGenerator");
11
+ const toolExecution_1 = require("./toolExecution");
10
12
  const getToolPrefix = (entry) => {
11
13
  if (entry.config.toolPrefix) {
12
14
  return entry.config.toolPrefix;
@@ -29,61 +31,6 @@ const METHOD_HANDLERS = {
29
31
  read: handlers_1.handleRead,
30
32
  update: handlers_1.handleUpdate,
31
33
  };
32
- const getToolErrorMessage = (result) => {
33
- const text = result.content[0]?.text;
34
- if (!text) {
35
- return "Unknown MCP tool error";
36
- }
37
- try {
38
- const parsed = JSON.parse(text);
39
- return typeof parsed.error === "string" ? parsed.error : text;
40
- }
41
- catch {
42
- return text;
43
- }
44
- };
45
- const executeTool = async ({ args, entry, handler, method, toolName, user, }) => {
46
- const userId = user?.id ?? (user?._id ? String(user._id) : undefined);
47
- if (userId) {
48
- (0, requestContext_1.setRequestContext)({ userId });
49
- }
50
- const log = (0, logger_1.createScopedLogger)({
51
- labels: {
52
- mcpMethod: method,
53
- mcpModel: entry.modelName,
54
- mcpTool: toolName,
55
- },
56
- prefix: "[MCPTool]",
57
- });
58
- const startedAt = performance.now();
59
- try {
60
- const result = await handler(entry, args, user);
61
- const durationMs = Math.round(performance.now() - startedAt);
62
- if (!result.isError) {
63
- log.info("MCP tool call succeeded", { durationMs });
64
- return result;
65
- }
66
- const cause = (0, handlers_1.getMCPErrorCause)(result);
67
- const message = getToolErrorMessage(result);
68
- if (cause !== undefined) {
69
- // ScopedLogger.catch records the original exception and captures it in Sentry when enabled.
70
- log.catch(cause);
71
- log.error("MCP tool call failed", { durationMs, message });
72
- }
73
- else {
74
- // Permission, not-found, and input errors are expected failures: retain an audit trail
75
- // and Sentry log without reporting them as exceptions.
76
- log.warn("MCP tool call refused", { durationMs, message });
77
- }
78
- return result;
79
- }
80
- catch (error) {
81
- const durationMs = Math.round(performance.now() - startedAt);
82
- log.catch(error);
83
- log.error("MCP tool call crashed", { durationMs });
84
- throw error;
85
- }
86
- };
87
34
  const generateToolsForEntry = (entry) => {
88
35
  const methods = entry.config.methods ?? ["list", "read"];
89
36
  const prefix = getToolPrefix(entry);
@@ -100,7 +47,11 @@ const generateToolsForEntry = (entry) => {
100
47
  const toolName = `${prefix}_${method}`;
101
48
  tools.push({
102
49
  description: (0, schemaGenerator_1.generateToolDescription)(entry.model, method, entry.config, entry.options.queryFields, entry.options.populatePaths, restExcludeFields),
103
- handler: (args, user) => executeTool({ args, entry, handler, method, toolName, user }),
50
+ handler: (args, user) => (0, toolExecution_1.executeTool)({
51
+ labels: { mcpMethod: method, mcpModel: entry.modelName, mcpTool: toolName },
52
+ run: () => handler(entry, args, user),
53
+ user,
54
+ }),
104
55
  inputSchema: inputSchema,
105
56
  name: toolName,
106
57
  zodSchema,
@@ -117,7 +68,10 @@ const generateAllTools = (entries) => {
117
68
  return tools;
118
69
  };
119
70
  exports.generateAllTools = generateAllTools;
120
- /** Model-router tools plus any custom tools registered with `registerMCPTool`. */
71
+ /**
72
+ * Model-router CRUD tools, modelRouter actions that opted in with `mcp`, and custom tools
73
+ * registered with `registerMCPTool`.
74
+ */
121
75
  const getAllMCPTools = () => {
122
76
  const customTools = (0, registry_1.getMCPCustomTools)().map((tool) => {
123
77
  return {
@@ -128,6 +82,18 @@ const getAllMCPTools = () => {
128
82
  zodSchema: tool.zodSchema,
129
83
  };
130
84
  });
131
- return [...(0, exports.generateAllTools)((0, registry_1.getMCPRegistry)()), ...customTools];
85
+ const baseTools = [...(0, exports.generateAllTools)((0, registry_1.getMCPRegistry)()), ...customTools];
86
+ const actionTools = (0, actionTools_1.generateActionTools)((0, collectionRegistry_1.listCollections)());
87
+ const takenNames = new Set(baseTools.map((tool) => tool.name));
88
+ for (const tool of actionTools) {
89
+ if (takenNames.has(tool.name)) {
90
+ throw new errors_1.APIError({
91
+ status: 500,
92
+ title: `MCP tool name "${tool.name}" is used by more than one tool. Give the action a unique mcp.name.`,
93
+ });
94
+ }
95
+ takenNames.add(tool.name);
96
+ }
97
+ return [...baseTools, ...actionTools];
132
98
  };
133
99
  exports.getAllMCPTools = getAllMCPTools;
@@ -29,10 +29,10 @@ export interface MCPToolInputSchema {
29
29
  */
30
30
  export type MCPDocument = HydratedDocument<Record<string, unknown>>;
31
31
  /**
32
- * Express-shaped request handed to modelRouter lifecycle hooks and response handlers
33
- * during an MCP tool call. Built by `createMCPRequest` as a stub: only `user`
34
- * and `body` are populated. `headers`, `query`, and `params` are always empty
35
- * objects — MCP does not forward HTTP request fields.
32
+ * Express-shaped request handed to modelRouter lifecycle hooks, response handlers, and
33
+ * action handlers during an MCP tool call. Built by `createMCPRequest` as a stub: `user` and
34
+ * `body` are populated, and action tools also fill `params.id` (instance actions) and `query`
35
+ * (GET actions). `headers` is always empty — MCP does not forward HTTP request fields.
36
36
  */
37
37
  export interface MCPRequest {
38
38
  body: MCPToolArgs;
@@ -0,0 +1,2 @@
1
+ import type { McpOAuthAuthorizationModel } from "../types/mcpOAuth";
2
+ export declare const McpOAuthAuthorization: McpOAuthAuthorizationModel;