@terreno/api 58.0.6 → 58.1.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 (75) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/dist/actions.d.ts +6 -0
  3. package/dist/api.d.ts +21 -0
  4. package/dist/api.js +57 -32
  5. package/dist/bulk.d.ts +79 -0
  6. package/dist/bulk.js +449 -0
  7. package/dist/bulkOpenApi.d.ts +15 -0
  8. package/dist/bulkOpenApi.js +103 -0
  9. package/dist/bulkTransaction.d.ts +33 -0
  10. package/dist/bulkTransaction.js +126 -0
  11. package/dist/errors.d.ts +2 -0
  12. package/dist/errors.js +8 -6
  13. package/dist/index.d.ts +3 -2
  14. package/dist/index.js +6 -3
  15. package/dist/mcp/actionTools.js +2 -0
  16. package/dist/mcp/grantAccess.d.ts +27 -0
  17. package/dist/mcp/grantAccess.js +29 -0
  18. package/dist/mcp/oauth.js +86 -5
  19. package/dist/mcp/oauthMetadata.d.ts +32 -1
  20. package/dist/mcp/oauthMetadata.js +53 -2
  21. package/dist/mcp/registry.d.ts +8 -1
  22. package/dist/mcp/server.js +6 -1
  23. package/dist/mcp/toolGenerator.d.ts +5 -1
  24. package/dist/mcp/toolGenerator.js +11 -0
  25. package/dist/mcp/types.d.ts +11 -0
  26. package/dist/modelRouterWrites.d.ts +23 -0
  27. package/dist/modelRouterWrites.js +54 -0
  28. package/dist/openApi.d.ts +7 -0
  29. package/dist/openApi.js +6 -6
  30. package/dist/permissions.js +5 -4
  31. package/dist/rbac/access.js +2 -0
  32. package/dist/rbac/routes.js +1 -0
  33. package/dist/rbac/statements.d.ts +12 -1
  34. package/dist/rbac/statements.js +89 -1
  35. package/dist/rbac/types.d.ts +9 -2
  36. package/dist/sync/executors.d.ts +6 -4
  37. package/dist/sync/executors.js +6 -2
  38. package/package.json +6 -6
  39. package/src/actions.ts +6 -0
  40. package/src/api.ts +95 -33
  41. package/src/bulk.test.ts +1256 -0
  42. package/src/bulk.ts +680 -0
  43. package/src/bulkOpenApi.test.ts +172 -0
  44. package/src/bulkOpenApi.ts +126 -0
  45. package/src/bulkTransaction.test.ts +197 -0
  46. package/src/bulkTransaction.ts +149 -0
  47. package/src/errors.ts +2 -2
  48. package/src/index.ts +6 -0
  49. package/src/isolated/bulkAtomic.isolated.ts +630 -0
  50. package/src/isolated/bulkStandalone.isolated.ts +133 -0
  51. package/src/isolated/mongoTopology.isolated.ts +29 -0
  52. package/src/mcp/actionTools.ts +2 -0
  53. package/src/mcp/grantAccess.test.ts +107 -0
  54. package/src/mcp/grantAccess.ts +49 -0
  55. package/src/mcp/oauth.test.ts +327 -0
  56. package/src/mcp/oauth.ts +113 -5
  57. package/src/mcp/oauthMetadata.test.ts +125 -1
  58. package/src/mcp/oauthMetadata.ts +99 -2
  59. package/src/mcp/registry.ts +8 -1
  60. package/src/mcp/server.test.ts +419 -2
  61. package/src/mcp/server.ts +8 -1
  62. package/src/mcp/toolGenerator.ts +17 -0
  63. package/src/mcp/types.ts +12 -0
  64. package/src/modelRouterWrites.ts +72 -0
  65. package/src/openApi.ts +1 -1
  66. package/src/permissions.ts +5 -5
  67. package/src/rbac/access.ts +3 -1
  68. package/src/rbac/routes.test.ts +15 -0
  69. package/src/rbac/routes.ts +1 -0
  70. package/src/rbac/statements.test.ts +23 -0
  71. package/src/rbac/statements.ts +100 -1
  72. package/src/rbac/types.ts +9 -2
  73. package/src/sync/executors.test.ts +27 -0
  74. package/src/sync/executors.ts +12 -4
  75. package/src/tests/mongoTopology.ts +53 -0
@@ -0,0 +1,126 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.runInBulkTransaction = exports.isBulkCommitUnknownError = exports.BulkCommitUnknownError = exports.isTransientTransactionError = exports.supportsTransactions = exports.enableTransactionAsyncLocalStorage = void 0;
4
+ const errors_1 = require("./errors");
5
+ const transactionSupport = new WeakMap();
6
+ /**
7
+ * Turns on `transactionAsyncLocalStorage` for a Mongoose instance. This is app-wide: from then on
8
+ * every Mongoose operation inside any transaction store joins that transaction, including stores
9
+ * opened by the app's own `connection.transaction()` calls. Operations outside a store are
10
+ * unaffected.
11
+ */
12
+ const enableTransactionAsyncLocalStorage = (base) => {
13
+ if (!base.get("transactionAsyncLocalStorage")) {
14
+ base.set("transactionAsyncLocalStorage", true);
15
+ }
16
+ };
17
+ exports.enableTransactionAsyncLocalStorage = enableTransactionAsyncLocalStorage;
18
+ /** Whether the connection's deployment supports transactions (replica set or sharded). */
19
+ const supportsTransactions = (connection) => {
20
+ const cached = transactionSupport.get(connection);
21
+ if (cached) {
22
+ return cached;
23
+ }
24
+ const db = connection.db;
25
+ if (!db) {
26
+ // Not connected yet: answer for now, but probe again once the connection opens.
27
+ return Promise.resolve(false);
28
+ }
29
+ const check = (async () => {
30
+ const hello = await db.admin().command({ hello: 1 });
31
+ return Boolean(hello.setName) || hello.msg === "isdbgrid";
32
+ })();
33
+ // Do not cache a failed probe; the next request tries again.
34
+ check.catch(() => transactionSupport.delete(connection));
35
+ transactionSupport.set(connection, check);
36
+ return check;
37
+ };
38
+ exports.supportsTransactions = supportsTransactions;
39
+ const hasErrorLabel = (error, label) => {
40
+ const labelled = error;
41
+ if (typeof labelled?.hasErrorLabel === "function" && labelled.hasErrorLabel(label)) {
42
+ return true;
43
+ }
44
+ return Array.isArray(labelled?.errorLabels) && labelled.errorLabels.includes(label);
45
+ };
46
+ /**
47
+ * Whether an error (or any error in its `cause` chain, since executors wrap driver errors in
48
+ * APIErrors) is a transient transaction failure, such as a write conflict: the transaction was
49
+ * aborted and nothing it wrote is visible.
50
+ */
51
+ const isTransientTransactionError = (error) => {
52
+ let current = error;
53
+ for (let depth = 0; current && depth < 5; depth += 1) {
54
+ if (hasErrorLabel(current, "TransientTransactionError")) {
55
+ return true;
56
+ }
57
+ current = current.cause;
58
+ }
59
+ return false;
60
+ };
61
+ exports.isTransientTransactionError = isTransientTransactionError;
62
+ /** Thrown when a commit's outcome stays unknown after one retry: the writes may have landed. */
63
+ class BulkCommitUnknownError extends Error {
64
+ cause;
65
+ isBulkCommitUnknown = true;
66
+ constructor(cause) {
67
+ super("Bulk transaction commit outcome is unknown");
68
+ this.cause = cause;
69
+ }
70
+ }
71
+ exports.BulkCommitUnknownError = BulkCommitUnknownError;
72
+ const isBulkCommitUnknownError = (error) => Boolean(error?.isBulkCommitUnknown);
73
+ exports.isBulkCommitUnknownError = isBulkCommitUnknownError;
74
+ // The driver's guidance for UnknownTransactionCommitResult: retry the commit itself, which is
75
+ // safe and runs no hooks again. A second unknown result is reported, never guessed.
76
+ const commitWithOneRetry = async (session) => {
77
+ try {
78
+ await session.commitTransaction();
79
+ }
80
+ catch (error) {
81
+ if (!hasErrorLabel(error, "UnknownTransactionCommitResult")) {
82
+ throw error;
83
+ }
84
+ try {
85
+ await session.commitTransaction();
86
+ }
87
+ catch (retryError) {
88
+ if (hasErrorLabel(retryError, "UnknownTransactionCommitResult")) {
89
+ throw new BulkCommitUnknownError(retryError);
90
+ }
91
+ throw retryError;
92
+ }
93
+ }
94
+ };
95
+ /**
96
+ * Runs `fn` inside one transaction on `connection`, with every Mongoose operation of `base`
97
+ * joined to it. Commits when `fn` resolves; aborts and rethrows when it throws. Work `fn` starts
98
+ * without awaiting keeps the session after the transaction ends, so it must leave the store.
99
+ */
100
+ const runInBulkTransaction = async ({ base, connection, fn, }) => {
101
+ const storage = base.transactionAsyncLocalStorage;
102
+ if (!storage) {
103
+ throw new errors_1.APIError({
104
+ status: 500,
105
+ title: "transactionAsyncLocalStorage is not enabled on this Mongoose instance",
106
+ });
107
+ }
108
+ const session = await connection.startSession();
109
+ try {
110
+ session.startTransaction();
111
+ let result;
112
+ try {
113
+ result = await storage.run({ session }, fn);
114
+ }
115
+ catch (error) {
116
+ await session.abortTransaction().catch(() => undefined);
117
+ throw error;
118
+ }
119
+ await commitWithOneRetry(session);
120
+ return result;
121
+ }
122
+ finally {
123
+ await session.endSession();
124
+ }
125
+ };
126
+ exports.runInBulkTransaction = runInBulkTransaction;
package/dist/errors.d.ts CHANGED
@@ -141,6 +141,7 @@ export declare const errorStack: (error: unknown) => string;
141
141
  * this property attached.
142
142
  */
143
143
  export declare const getDisableExternalErrorTracking: (error: unknown) => boolean | undefined;
144
+ export declare const serializeAPIError: (error: APIError) => APIErrorBody;
144
145
  /**
145
146
  * Creates an APIError body to send to clients as JSON.
146
147
  * @deprecated Use `error.toJSON()` instead.
@@ -178,6 +179,7 @@ export declare const passthroughOrWrap: (error: unknown, wrapper: APIErrorOption
178
179
  * flattened into the wrapper's `detail`.
179
180
  */
180
181
  export declare const passthroughOrWrapWrite: (error: unknown, wrapper: APIErrorOptions) => APIError;
182
+ export declare const logAndCaptureAPIError: (err: APIError) => void;
181
183
  export declare const apiErrorMiddleware: (err: Error, _req: Request, res: Response, next: NextFunction) => void;
182
184
  /**
183
185
  * Final Express error handler for unexpected errors. Always returns JSON so
package/dist/errors.js CHANGED
@@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.apiFallthroughErrorMiddleware = exports.apiErrorMiddleware = exports.passthroughOrWrapWrite = exports.passthroughOrWrap = exports.bodyParserErrorToAPIError = exports.mongooseErrorToAPIError = exports.apiUnauthorizedMiddleware = exports.getAPIErrorBody = exports.getDisableExternalErrorTracking = exports.errorStack = exports.errorDetail = exports.errorMessage = exports.isAPIError = exports.errorsPlugin = exports.InternalServerError = exports.ValidationError = exports.ConflictError = exports.NotFoundError = exports.ForbiddenError = exports.UnauthorizedError = exports.BadRequestError = exports.APIError = void 0;
36
+ exports.apiFallthroughErrorMiddleware = exports.apiErrorMiddleware = exports.logAndCaptureAPIError = exports.passthroughOrWrapWrite = exports.passthroughOrWrap = exports.bodyParserErrorToAPIError = exports.mongooseErrorToAPIError = exports.apiUnauthorizedMiddleware = exports.getAPIErrorBody = exports.serializeAPIError = exports.getDisableExternalErrorTracking = exports.errorStack = exports.errorDetail = exports.errorMessage = exports.isAPIError = exports.errorsPlugin = exports.InternalServerError = exports.ValidationError = exports.ConflictError = exports.NotFoundError = exports.ForbiddenError = exports.UnauthorizedError = exports.BadRequestError = exports.APIError = void 0;
37
37
  // https://jsonapi.org/format/#errors
38
38
  const Sentry = __importStar(require("@sentry/bun"));
39
39
  const mongoose_1 = __importStar(require("mongoose"));
@@ -151,7 +151,7 @@ class APIError extends Error {
151
151
  // Client-facing JSONAPI body. Excludes name/stack/cause; includes
152
152
  // disableExternalErrorTracking only when true (client Sentry suppression).
153
153
  toJSON() {
154
- return serializeAPIError(this);
154
+ return (0, exports.serializeAPIError)(this);
155
155
  }
156
156
  }
157
157
  exports.APIError = APIError;
@@ -334,12 +334,13 @@ const serializeAPIError = (error) => {
334
334
  }
335
335
  return body;
336
336
  };
337
+ exports.serializeAPIError = serializeAPIError;
337
338
  /**
338
339
  * Creates an APIError body to send to clients as JSON.
339
340
  * @deprecated Use `error.toJSON()` instead.
340
341
  */
341
342
  const getAPIErrorBody = (error) => {
342
- return serializeAPIError(error);
343
+ return (0, exports.serializeAPIError)(error);
343
344
  };
344
345
  exports.getAPIErrorBody = getAPIErrorBody;
345
346
  /**
@@ -484,10 +485,11 @@ const logAndCaptureAPIError = (err) => {
484
485
  if (err.code) {
485
486
  scope.setTag("api_error.code", err.code);
486
487
  }
487
- scope.setContext("apiError", serializeAPIError(err));
488
+ scope.setContext("apiError", (0, exports.serializeAPIError)(err));
488
489
  Sentry.captureException(err);
489
490
  });
490
491
  };
492
+ exports.logAndCaptureAPIError = logAndCaptureAPIError;
491
493
  const apiErrorMiddleware = (err, _req, res, next) => {
492
494
  const apiError = (0, exports.isAPIError)(err)
493
495
  ? err
@@ -496,8 +498,8 @@ const apiErrorMiddleware = (err, _req, res, next) => {
496
498
  next(err);
497
499
  return;
498
500
  }
499
- logAndCaptureAPIError(apiError);
500
- res.status(apiError.status).json(serializeAPIError(apiError)).send();
501
+ (0, exports.logAndCaptureAPIError)(apiError);
502
+ res.status(apiError.status).json((0, exports.serializeAPIError)(apiError)).send();
501
503
  };
502
504
  exports.apiErrorMiddleware = apiErrorMiddleware;
503
505
  /**
package/dist/index.d.ts CHANGED
@@ -38,15 +38,16 @@ export * from "./httpClient";
38
38
  export * from "./logger";
39
39
  export { type McpRequestLogAppOption, type ResolvedMcpRequestLogOptions, resolveMcpRequestLogOption, } from "./mcp/adminTracking";
40
40
  export { extractAuthFromHeaders, extractUserFromHeaders, type MCPAuthContext, type MCPAuthResult, } from "./mcp/auth";
41
+ export { type CanUseMcpToolOptions, canUseMcpTool } from "./mcp/grantAccess";
41
42
  export { addMcpOAuthRoutes, type McpOAuthRoutesOptions } from "./mcp/oauth";
42
- export { buildAuthorizationServerMetadata, buildProtectedResourceMetadata, type McpOAuthAppOption, type McpOAuthOptions, type ResolvedMcpOAuthOptions, resolveMcpOAuthOption, sendMcpOAuthChallenge, } from "./mcp/oauthMetadata";
43
+ export { buildAuthorizationServerMetadata, buildProtectedResourceMetadata, MCP_OAUTH_GRANT_PRESETS, type McpOAuthAppOption, type McpOAuthGrant, type McpOAuthGrantAccess, type McpOAuthGrantPreset, type McpOAuthOptions, type ResolvedMcpOAuthOptions, resolveMcpOAuthOption, sendMcpOAuthChallenge, } from "./mcp/oauthMetadata";
43
44
  export type { MCPCustomTool } from "./mcp/registry";
44
45
  export { clearMCPRegistry, getMCPRegistry, registerMCPModel, registerMCPTool, updateMCPRegistryOptions, } from "./mcp/registry";
45
46
  export { generateInputSchema, generateToolDescription } from "./mcp/schemaGenerator";
46
47
  export { type MCPServerOptions, mountMCPServer } from "./mcp/server";
47
48
  export { addMcpServiceTokenRoutes, createMcpServiceTokenRouter, MAX_ACTIVE_MCP_SERVICE_TOKENS, MCP_SERVICE_TOKENS_ROUTE_PATH, MCP_SERVICE_TOKENS_SYNC_COLLECTION, type McpServiceTokenRoutesOptions, type McpServiceTokensAppOption, resolveMcpServiceTokensOption, toPublicMcpServiceToken, } from "./mcp/serviceTokens";
48
49
  export { generateAllTools, generateToolsForEntry, getAllMCPTools, type MCPToolDefinition, } from "./mcp/toolGenerator";
49
- export type { MCPConfig, MCPMethod, MCPRegistryEntry, MCPRequest, MCPToolArgs, MCPToolResult, } from "./mcp/types";
50
+ export type { MCPConfig, MCPMethod, MCPRegistryEntry, MCPRequest, MCPToolAccess, MCPToolArgs, MCPToolResult, } from "./mcp/types";
50
51
  export * from "./middleware";
51
52
  export * from "./migrations/builtin/mcpServiceTokenStringIds";
52
53
  export * from "./migrations/generate";
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.McpOAuthClient = exports.McpOAuthAuthorization = exports.getAllMCPTools = exports.generateToolsForEntry = exports.generateAllTools = exports.toPublicMcpServiceToken = exports.resolveMcpServiceTokensOption = exports.MCP_SERVICE_TOKENS_SYNC_COLLECTION = exports.MCP_SERVICE_TOKENS_ROUTE_PATH = exports.MAX_ACTIVE_MCP_SERVICE_TOKENS = exports.createMcpServiceTokenRouter = 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.getSocketUser = exports.createSocketAuthMiddleware = exports.createLegacyJwtValidator = exports.createBetterAuthValidator = exports.startSessionRevalidationSweep = exports.runSessionRevalidationSweep = exports.revalidateSocketSession = exports.reresolveSyncRoomsForSocket = exports.loadFullUserForSocket = exports.DEFAULT_SESSION_REVALIDATION_INTERVAL_MS = exports.RealtimeApp = exports.installRealtimeSocketHandlers = 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 = exports.McpRequestLog = exports.McpOAuthToken = exports.McpOAuthFamilyRevokedError = exports.McpOAuthRevokedFamily = 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 = void 0;
17
+ exports.getAllMCPTools = exports.generateToolsForEntry = exports.generateAllTools = exports.toPublicMcpServiceToken = exports.resolveMcpServiceTokensOption = exports.MCP_SERVICE_TOKENS_SYNC_COLLECTION = exports.MCP_SERVICE_TOKENS_ROUTE_PATH = exports.MAX_ACTIVE_MCP_SERVICE_TOKENS = exports.createMcpServiceTokenRouter = exports.addMcpServiceTokenRoutes = exports.mountMCPServer = exports.generateToolDescription = exports.generateInputSchema = exports.updateMCPRegistryOptions = exports.registerMCPTool = exports.registerMCPModel = exports.getMCPRegistry = exports.clearMCPRegistry = exports.sendMcpOAuthChallenge = exports.resolveMcpOAuthOption = exports.MCP_OAUTH_GRANT_PRESETS = exports.buildProtectedResourceMetadata = exports.buildAuthorizationServerMetadata = exports.addMcpOAuthRoutes = exports.canUseMcpTool = 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.createLegacyJwtValidator = exports.createBetterAuthValidator = exports.startSessionRevalidationSweep = exports.runSessionRevalidationSweep = exports.revalidateSocketSession = exports.reresolveSyncRoomsForSocket = exports.loadFullUserForSocket = exports.DEFAULT_SESSION_REVALIDATION_INTERVAL_MS = exports.RealtimeApp = exports.installRealtimeSocketHandlers = 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 = exports.McpRequestLog = exports.McpOAuthToken = exports.McpOAuthFamilyRevokedError = exports.McpOAuthRevokedFamily = exports.McpOAuthClient = exports.McpOAuthAuthorization = 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 = 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);
@@ -82,11 +82,14 @@ Object.defineProperty(exports, "resolveMcpRequestLogOption", { enumerable: true,
82
82
  var auth_1 = require("./mcp/auth");
83
83
  Object.defineProperty(exports, "extractAuthFromHeaders", { enumerable: true, get: function () { return auth_1.extractAuthFromHeaders; } });
84
84
  Object.defineProperty(exports, "extractUserFromHeaders", { enumerable: true, get: function () { return auth_1.extractUserFromHeaders; } });
85
+ var grantAccess_1 = require("./mcp/grantAccess");
86
+ Object.defineProperty(exports, "canUseMcpTool", { enumerable: true, get: function () { return grantAccess_1.canUseMcpTool; } });
85
87
  var oauth_1 = require("./mcp/oauth");
86
88
  Object.defineProperty(exports, "addMcpOAuthRoutes", { enumerable: true, get: function () { return oauth_1.addMcpOAuthRoutes; } });
87
89
  var oauthMetadata_1 = require("./mcp/oauthMetadata");
88
90
  Object.defineProperty(exports, "buildAuthorizationServerMetadata", { enumerable: true, get: function () { return oauthMetadata_1.buildAuthorizationServerMetadata; } });
89
91
  Object.defineProperty(exports, "buildProtectedResourceMetadata", { enumerable: true, get: function () { return oauthMetadata_1.buildProtectedResourceMetadata; } });
92
+ Object.defineProperty(exports, "MCP_OAUTH_GRANT_PRESETS", { enumerable: true, get: function () { return oauthMetadata_1.MCP_OAUTH_GRANT_PRESETS; } });
90
93
  Object.defineProperty(exports, "resolveMcpOAuthOption", { enumerable: true, get: function () { return oauthMetadata_1.resolveMcpOAuthOption; } });
91
94
  Object.defineProperty(exports, "sendMcpOAuthChallenge", { enumerable: true, get: function () { return oauthMetadata_1.sendMcpOAuthChallenge; } });
92
95
  var registry_1 = require("./mcp/registry");
@@ -137,6 +137,7 @@ const generateActionTools = (records) => {
137
137
  const toolName = entry.config.mcp?.name;
138
138
  const zodSchema = buildActionInputSchema(entry.scope, entry.config);
139
139
  tools.push({
140
+ access: entry.config.method === "GET" ? "read" : "write",
140
141
  description: describeAction(entry),
141
142
  handler: (args, user) => (0, toolExecution_1.executeTool)({
142
143
  labels: {
@@ -149,6 +150,7 @@ const generateActionTools = (records) => {
149
150
  }),
150
151
  inputSchema: (0, zod_1.toJSONSchema)(zodSchema),
151
152
  name: toolName,
153
+ scope: entry.config.mcp?.scope,
152
154
  zodSchema,
153
155
  });
154
156
  }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Grant enforcement for MCP OAuth tokens: decides which tools a token may see and call from the
3
+ * scopes it was granted and the app's resolved `mcpOAuth.grants`.
4
+ */
5
+ import type { RequestCredential } from "../requestContext";
6
+ import type { McpOAuthGrant } from "./oauthMetadata";
7
+ import type { MCPToolDefinition } from "./toolGenerator";
8
+ export interface CanUseMcpToolOptions {
9
+ /** The tool being listed or called. Only its `access` and `scope` are read. */
10
+ tool: Pick<MCPToolDefinition, "access" | "scope">;
11
+ /** How the caller authenticated. Only `oauth` credentials are limited by grants. */
12
+ credential: RequestCredential | undefined;
13
+ /** Scopes on the caller's OAuth access token. */
14
+ tokenScopes: string[] | undefined;
15
+ /** Resolved `mcpOAuth.grants`, or undefined when the app does not enforce grants. */
16
+ grants: McpOAuthGrant[] | undefined;
17
+ }
18
+ /**
19
+ * True when the caller may see and call `tool`.
20
+ *
21
+ * - Credentials other than an OAuth token, and apps without `grants`, may use every tool.
22
+ * - A tool that declares `scope` requires exactly that scope on the token.
23
+ * - A `read` tool needs a granted scope whose grant has `read` or `write` access (write implies
24
+ * read); a `write` tool needs a granted scope whose grant has `write` access.
25
+ * - Token scopes that match no grant (for example the legacy `mcp` scope) allow nothing.
26
+ */
27
+ export declare const canUseMcpTool: ({ tool, credential, tokenScopes, grants, }: CanUseMcpToolOptions) => boolean;
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.canUseMcpTool = void 0;
4
+ /**
5
+ * True when the caller may see and call `tool`.
6
+ *
7
+ * - Credentials other than an OAuth token, and apps without `grants`, may use every tool.
8
+ * - A tool that declares `scope` requires exactly that scope on the token.
9
+ * - A `read` tool needs a granted scope whose grant has `read` or `write` access (write implies
10
+ * read); a `write` tool needs a granted scope whose grant has `write` access.
11
+ * - Token scopes that match no grant (for example the legacy `mcp` scope) allow nothing.
12
+ */
13
+ const canUseMcpTool = ({ tool, credential, tokenScopes, grants, }) => {
14
+ if (credential !== "oauth" || !grants) {
15
+ return true;
16
+ }
17
+ const scopes = tokenScopes ?? [];
18
+ if (tool.scope) {
19
+ return scopes.includes(tool.scope);
20
+ }
21
+ const grantedAccess = grants
22
+ .filter((grant) => scopes.includes(grant.scope))
23
+ .map((grant) => grant.access);
24
+ if (tool.access === "read") {
25
+ return grantedAccess.length > 0;
26
+ }
27
+ return grantedAccess.includes("write");
28
+ };
29
+ exports.canUseMcpTool = canUseMcpTool;
package/dist/mcp/oauth.js CHANGED
@@ -120,6 +120,60 @@ const parseScope = (scope, supported) => {
120
120
  }
121
121
  return requested.join(" ");
122
122
  };
123
+ const splitScope = (scope) => {
124
+ return (scope ?? "").split(" ").filter((value) => value.length > 0);
125
+ };
126
+ /**
127
+ * Describe each requested scope for the consent screen, in requested order. Without configured
128
+ * grants a scope is shown by name and treated as full access, since nothing narrows it.
129
+ */
130
+ const consentGrantsFor = (scope, grants) => {
131
+ return splitScope(scope).map((value) => {
132
+ const grant = grants?.find((candidate) => candidate.scope === value);
133
+ if (!grant) {
134
+ return { access: "write", description: null, label: value, scope: value };
135
+ }
136
+ return {
137
+ access: grant.access,
138
+ description: grant.description ?? null,
139
+ label: grant.label,
140
+ scope: grant.scope,
141
+ };
142
+ });
143
+ };
144
+ /**
145
+ * The scope the user approved: the full requested scope when the consent screen sends none, or a
146
+ * non-empty subset of it. Approval can narrow a request but never widen it.
147
+ */
148
+ const approvedScope = (body, requested) => {
149
+ const narrowed = body?.scope;
150
+ if (narrowed === undefined) {
151
+ return requested ?? undefined;
152
+ }
153
+ if (typeof narrowed !== "string") {
154
+ throw new errors_1.BadRequestError({
155
+ detail: "scope must be a space-separated string",
156
+ title: "Invalid scope",
157
+ });
158
+ }
159
+ const chosen = [...new Set(splitScope(narrowed))];
160
+ if (chosen.length === 0) {
161
+ throw new errors_1.BadRequestError({
162
+ detail: "Approve at least one of the requested permissions",
163
+ title: "Choose at least one permission",
164
+ });
165
+ }
166
+ const requestedScopes = splitScope(requested);
167
+ const extra = chosen.filter((value) => !requestedScopes.includes(value));
168
+ if (extra.length > 0) {
169
+ throw new errors_1.BadRequestError({
170
+ detail: `Not requested by the client: ${extra.join(" ")}`,
171
+ title: "Scope was not requested",
172
+ });
173
+ }
174
+ // Keep the client's requested order so the issued scope string is stable.
175
+ return requestedScopes.filter((value) => chosen.includes(value)).join(" ");
176
+ };
123
177
  const normalizeResource = (resource) => resource.replace(/\/$/, "");
124
178
  const pkceS256 = (verifier) => (0, node_crypto_1.createHash)("sha256").update(verifier).digest("base64url");
125
179
  const appendParams = (base, params) => {
@@ -363,6 +417,18 @@ const addConsentRoutes = (app, oauth, openApi) => {
363
417
  clientId: { type: "string" },
364
418
  clientName: { type: "string" },
365
419
  expiresAt: { type: "string" },
420
+ grants: {
421
+ items: {
422
+ properties: {
423
+ access: { enum: ["read", "write"], type: "string" },
424
+ description: { nullable: true, type: "string" },
425
+ label: { type: "string" },
426
+ scope: { type: "string" },
427
+ },
428
+ type: "object",
429
+ },
430
+ type: "array",
431
+ },
366
432
  redirectHost: { type: "string" },
367
433
  redirectUri: { type: "string" },
368
434
  requestId: { type: "string" },
@@ -382,6 +448,7 @@ const addConsentRoutes = (app, oauth, openApi) => {
382
448
  clientId: authorization.clientId,
383
449
  clientName: client?.clientName ?? null,
384
450
  expiresAt: authorization.expiresAt.toISOString(),
451
+ grants: consentGrantsFor(authorization.scope, oauth.grants),
385
452
  redirectHost: new URL(authorization.redirectUri).host,
386
453
  redirectUri: authorization.redirectUri,
387
454
  requestId: authorization.requestId,
@@ -390,7 +457,7 @@ const addConsentRoutes = (app, oauth, openApi) => {
390
457
  },
391
458
  });
392
459
  }));
393
- const decisionOpenApi = (operationId, summary) => (0, openApiBuilder_1.createOpenApiBuilder)(openApiOptions)
460
+ const decisionOpenApiBuilder = (operationId, summary) => (0, openApiBuilder_1.createOpenApiBuilder)(openApiOptions)
394
461
  .withTags(["mcp"])
395
462
  .withOperationId(operationId)
396
463
  .withSummary(summary)
@@ -401,14 +468,22 @@ const addConsentRoutes = (app, oauth, openApi) => {
401
468
  properties: { redirectUrl: { type: "string" } },
402
469
  type: "object",
403
470
  },
404
- })
405
- .build();
471
+ });
472
+ const decisionOpenApi = (operationId, summary) => decisionOpenApiBuilder(operationId, summary).build();
406
473
  app.post("/oauth/authorize/:request/approve", [
407
474
  ...consentGuards,
408
- decisionOpenApi("approveMcpOAuthRequest", "Approve a pending MCP OAuth request"),
475
+ decisionOpenApiBuilder("approveMcpOAuthRequest", "Approve a pending MCP OAuth request")
476
+ .withRequestBody({
477
+ scope: {
478
+ description: "Space-separated subset of the requested scope the user approved. Omit to approve the full requested scope.",
479
+ type: "string",
480
+ },
481
+ }, { required: false })
482
+ .build(),
409
483
  ], (0, api_1.asyncHandler)(async (req, res) => {
410
484
  const user = requireUser(req);
411
485
  const pending = await loadPendingAuthorization(String(req.params.request));
486
+ const scope = approvedScope(req.body, pending.scope);
412
487
  const code = (0, mcpOAuthToken_1.generateMcpOAuthSecret)();
413
488
  const now = luxon_1.DateTime.now();
414
489
  const codeExpiresAt = now.plus({ seconds: oauth.authorizationCodeTtlSeconds });
@@ -418,6 +493,7 @@ const addConsentRoutes = (app, oauth, openApi) => {
418
493
  codeExpiresAt: codeExpiresAt.toJSDate(),
419
494
  codeHash: (0, mcpOAuthToken_1.hashMcpOAuthSecret)(code),
420
495
  expiresAt: expiresAt.toJSDate(),
496
+ ...(scope === undefined ? {} : { scope }),
421
497
  status: "approved",
422
498
  tokenEpoch: (0, auth_2.userTokenEpoch)(user),
423
499
  userId: new mongoose_1.default.Types.ObjectId(String(user._id)),
@@ -666,9 +742,14 @@ const exchangeClientCredentials = async (body, client, oauth, userModel) => {
666
742
  if (!user || userIsDisabled(user)) {
667
743
  throw new OAuthProtocolError("invalid_grant", "The user cannot be granted a token");
668
744
  }
745
+ // A client stored before the app switched to grants may hold scopes the server no longer
746
+ // supports; only the supported ones can be issued.
669
747
  const allowed = client.scope
670
- ? client.scope.split(" ").filter((scope) => scope.length > 0)
748
+ ? splitScope(client.scope).filter((value) => oauth.scopesSupported.includes(value))
671
749
  : oauth.scopesSupported;
750
+ if (allowed.length === 0) {
751
+ throw new OAuthProtocolError("invalid_scope", "The client's scope has no scope this server supports");
752
+ }
672
753
  const scope = parseScope(stringParam(body.scope), allowed);
673
754
  const issued = await issueOrInvalidGrant({
674
755
  accessTokenTtlSeconds: oauth.accessTokenTtlSeconds,
@@ -4,6 +4,26 @@
4
4
  * can serve the same metadata and challenge.
5
5
  */
6
6
  import type { Response } from "express";
7
+ /**
8
+ * One permission an MCP OAuth client can be granted. The consent screen shows its `label` and
9
+ * `description`; the server enforces its `access` level on every tool the token calls.
10
+ */
11
+ export interface McpOAuthGrant {
12
+ /** OAuth scope value. No spaces, since scopes are space-delimited on the wire. */
13
+ scope: string;
14
+ /** Short name the consent screen shows next to the grant's checkbox. */
15
+ label: string;
16
+ /** Longer explanation shown under the label. */
17
+ description?: string;
18
+ /** `read` allows read-only tools; `write` allows every tool, since write implies read. */
19
+ access: McpOAuthGrantAccess;
20
+ }
21
+ /** Access level a grant gives. Write implies read. */
22
+ export type McpOAuthGrantAccess = "read" | "write";
23
+ /** Named grant sets for `mcpOAuth.grants`. */
24
+ export type McpOAuthGrantPreset = "readOnly" | "readWrite";
25
+ /** The grants each `mcpOAuth.grants` preset expands to, in consent-screen order. */
26
+ export declare const MCP_OAUTH_GRANT_PRESETS: Readonly<Record<McpOAuthGrantPreset, readonly McpOAuthGrant[]>>;
7
27
  /** Grants a public PKCE client may register. Dynamic registration rejects anything else. */
8
28
  export declare const PUBLIC_CLIENT_GRANT_TYPES: string[];
9
29
  export declare const SUPPORTED_RESPONSE_TYPES: string[];
@@ -39,8 +59,17 @@ export interface McpOAuthOptions {
39
59
  allowedRedirectHosts?: string[];
40
60
  /** RFC 8707 resource identifier for `/mcp`. Default: `${issuer}/mcp`. */
41
61
  resource?: string;
42
- /** Scopes advertised and accepted. Default: `["mcp"]`. */
62
+ /**
63
+ * Scopes advertised and accepted, without enforcement. Default: `["mcp"]`. Cannot be combined
64
+ * with `grants`, which derives the scopes from its grants.
65
+ */
43
66
  scopesSupported?: string[];
67
+ /**
68
+ * Enforced grants a client can request and the user can approve: the `"readOnly"` or
69
+ * `"readWrite"` preset, or your own list. Sets `scopesSupported` to the grants' scopes. While
70
+ * unset, the default `mcp` scope is accepted and not enforced.
71
+ */
72
+ grants?: McpOAuthGrantPreset | McpOAuthGrant[];
44
73
  /** Access token lifetime. Default: 3600 (one hour). */
45
74
  accessTokenTtlSeconds?: number;
46
75
  /** Refresh token lifetime. Default: 30 days. */
@@ -64,6 +93,8 @@ export interface ResolvedMcpOAuthOptions {
64
93
  /** URL of the RFC 9728 protected-resource metadata for {@link resource}. */
65
94
  resourceMetadataUrl: string;
66
95
  scopesSupported: string[];
96
+ /** Enforced grants, or undefined while `mcpOAuth.grants` is unset. */
97
+ grants: McpOAuthGrant[] | undefined;
67
98
  }
68
99
  /** RFC 9728 §3.1: the well-known segment goes between the host and the resource's path. */
69
100
  export declare const protectedResourceMetadataPath: (resource: string) => string;
@@ -1,12 +1,30 @@
1
1
  "use strict";
2
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.PUBLIC_CLIENT_GRANT_TYPES = void 0;
3
+ exports.sendMcpOAuthChallenge = exports.buildAuthorizationServerMetadata = exports.buildProtectedResourceMetadata = exports.sendProtocolJson = exports.resolveMcpOAuthOption = exports.protectedResourceMetadataPath = exports.LOOPBACK_HOSTS = exports.SUPPORTED_RESPONSE_TYPES = exports.PUBLIC_CLIENT_GRANT_TYPES = exports.MCP_OAUTH_GRANT_PRESETS = void 0;
4
4
  const errors_1 = require("../errors");
5
5
  const DEFAULT_ACCESS_TOKEN_TTL_SECONDS = 60 * 60;
6
6
  const DEFAULT_REFRESH_TOKEN_TTL_SECONDS = 30 * 24 * 60 * 60;
7
7
  const DEFAULT_AUTHORIZATION_REQUEST_TTL_SECONDS = 10 * 60;
8
8
  const DEFAULT_AUTHORIZATION_CODE_TTL_SECONDS = 60;
9
9
  const DEFAULT_SCOPES = ["mcp"];
10
+ const READ_GRANT = {
11
+ access: "read",
12
+ description: "See your records. It cannot change anything.",
13
+ label: "Read your data",
14
+ scope: "mcp:read",
15
+ };
16
+ const WRITE_GRANT = {
17
+ access: "write",
18
+ description: "Create, update, and delete records for you.",
19
+ label: "Change your data",
20
+ scope: "mcp:write",
21
+ };
22
+ /** The grants each `mcpOAuth.grants` preset expands to, in consent-screen order. */
23
+ exports.MCP_OAUTH_GRANT_PRESETS = {
24
+ readOnly: [READ_GRANT],
25
+ readWrite: [READ_GRANT, WRITE_GRANT],
26
+ };
27
+ const GRANT_ACCESS_LEVELS = new Set(["read", "write"]);
10
28
  /** Grants a public PKCE client may register. Dynamic registration rejects anything else. */
11
29
  exports.PUBLIC_CLIENT_GRANT_TYPES = ["authorization_code", "refresh_token"];
12
30
  const SUPPORTED_GRANT_TYPES = [...exports.PUBLIC_CLIENT_GRANT_TYPES, "client_credentials"];
@@ -36,6 +54,34 @@ const positiveInteger = (value, fallback, field) => {
36
54
  }
37
55
  return value;
38
56
  };
57
+ const resolveGrants = (grants) => {
58
+ if (typeof grants === "string") {
59
+ if (!Object.hasOwn(exports.MCP_OAUTH_GRANT_PRESETS, grants)) {
60
+ throw misconfigured(`mcpOAuth.grants must be "readOnly", "readWrite", or a list of grants, got "${grants}"`);
61
+ }
62
+ return exports.MCP_OAUTH_GRANT_PRESETS[grants].map((grant) => ({ ...grant }));
63
+ }
64
+ if (!Array.isArray(grants) || grants.length === 0) {
65
+ throw misconfigured("mcpOAuth.grants must list at least one grant");
66
+ }
67
+ const seen = new Set();
68
+ for (const grant of grants) {
69
+ if (typeof grant?.scope !== "string" || !/^[\x21\x23-\x5B\x5D-\x7E]+$/.test(grant.scope)) {
70
+ throw misconfigured(`mcpOAuth.grants scope must be a non-empty string without spaces, got "${grant?.scope}"`);
71
+ }
72
+ if (seen.has(grant.scope)) {
73
+ throw misconfigured(`mcpOAuth.grants lists scope "${grant.scope}" more than once`);
74
+ }
75
+ seen.add(grant.scope);
76
+ if (typeof grant.label !== "string" || grant.label.trim() === "") {
77
+ throw misconfigured(`mcpOAuth.grants "${grant.scope}" needs a label`);
78
+ }
79
+ if (!GRANT_ACCESS_LEVELS.has(grant.access)) {
80
+ throw misconfigured(`mcpOAuth.grants "${grant.scope}" access must be "read" or "write", got "${grant.access}"`);
81
+ }
82
+ }
83
+ return grants;
84
+ };
39
85
  /** RFC 9728 §3.1: the well-known segment goes between the host and the resource's path. */
40
86
  const protectedResourceMetadataPath = (resource) => {
41
87
  const { pathname } = new URL(resource);
@@ -67,7 +113,11 @@ const resolveMcpOAuthOption = (option) => {
67
113
  const issuer = issuerUrl.origin;
68
114
  const resource = option.resource ?? `${issuer}/mcp`;
69
115
  parseAbsoluteUrl(resource, "resource");
70
- const scopesSupported = option.scopesSupported ?? DEFAULT_SCOPES;
116
+ if (option.grants !== undefined && option.scopesSupported !== undefined) {
117
+ throw misconfigured("mcpOAuth: set grants or scopesSupported, not both");
118
+ }
119
+ const grants = option.grants === undefined ? undefined : resolveGrants(option.grants);
120
+ const scopesSupported = grants?.map((grant) => grant.scope) ?? option.scopesSupported ?? DEFAULT_SCOPES;
71
121
  if (scopesSupported.length === 0) {
72
122
  throw misconfigured("mcpOAuth.scopesSupported must list at least one scope");
73
123
  }
@@ -78,6 +128,7 @@ const resolveMcpOAuthOption = (option) => {
78
128
  authorizationRequestTtlSeconds: positiveInteger(option.authorizationRequestTtlSeconds, DEFAULT_AUTHORIZATION_REQUEST_TTL_SECONDS, "authorizationRequestTtlSeconds"),
79
129
  consentUrl: option.consentUrl,
80
130
  dynamicClientRegistration,
131
+ grants,
81
132
  issuer,
82
133
  refreshTokenTtlSeconds: positiveInteger(option.refreshTokenTtlSeconds, DEFAULT_REFRESH_TOKEN_TTL_SECONDS, "refreshTokenTtlSeconds"),
83
134
  resource,
@@ -2,12 +2,19 @@ import type { Model } from "mongoose";
2
2
  import type { ZodType } from "zod";
3
3
  import type { ModelRouterOptions } from "../api";
4
4
  import type { User } from "../auth";
5
- import type { MCPConfig, MCPRegistryEntry, MCPToolArgs, MCPToolResult } from "./types";
5
+ import type { MCPConfig, MCPRegistryEntry, MCPToolAccess, MCPToolArgs, MCPToolResult } from "./types";
6
6
  export interface MCPCustomTool {
7
7
  description: string;
8
8
  handler: (args: MCPToolArgs, user?: User) => Promise<MCPToolResult>;
9
9
  name: string;
10
10
  zodSchema: ZodType;
11
+ /**
12
+ * `read` for tools that only read data, `write` for tools that can change it. Default:
13
+ * `"write"`, so a read-only OAuth grant cannot call the tool until it declares `"read"`.
14
+ */
15
+ access?: MCPToolAccess;
16
+ /** When set, an OAuth token must hold exactly this scope to see and call the tool. */
17
+ scope?: string;
11
18
  }
12
19
  export declare const registerMCPModel: <T>(model: Model<T>, config: MCPConfig, options: ModelRouterOptions<T>) => void;
13
20
  /**