@terreno/api 58.0.5 → 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 +58 -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
package/src/mcp/oauth.ts CHANGED
@@ -36,6 +36,7 @@ import {
36
36
  buildAuthorizationServerMetadata,
37
37
  buildProtectedResourceMetadata,
38
38
  LOOPBACK_HOSTS,
39
+ type McpOAuthGrant,
39
40
  PUBLIC_CLIENT_GRANT_TYPES,
40
41
  protectedResourceMetadataPath,
41
42
  type ResolvedMcpOAuthOptions,
@@ -155,6 +156,74 @@ const parseScope = (scope: string | undefined, supported: string[]): string => {
155
156
  return requested.join(" ");
156
157
  };
157
158
 
159
+ const splitScope = (scope: string | undefined | null): string[] => {
160
+ return (scope ?? "").split(" ").filter((value) => value.length > 0);
161
+ };
162
+
163
+ /** The consent-screen view of one grant. */
164
+ interface McpOAuthConsentGrant {
165
+ access: McpOAuthGrant["access"];
166
+ description: string | null;
167
+ label: string;
168
+ scope: string;
169
+ }
170
+
171
+ /**
172
+ * Describe each requested scope for the consent screen, in requested order. Without configured
173
+ * grants a scope is shown by name and treated as full access, since nothing narrows it.
174
+ */
175
+ const consentGrantsFor = (
176
+ scope: string | undefined | null,
177
+ grants: McpOAuthGrant[] | undefined
178
+ ): McpOAuthConsentGrant[] => {
179
+ return splitScope(scope).map((value) => {
180
+ const grant = grants?.find((candidate) => candidate.scope === value);
181
+ if (!grant) {
182
+ return {access: "write", description: null, label: value, scope: value};
183
+ }
184
+ return {
185
+ access: grant.access,
186
+ description: grant.description ?? null,
187
+ label: grant.label,
188
+ scope: grant.scope,
189
+ };
190
+ });
191
+ };
192
+
193
+ /**
194
+ * The scope the user approved: the full requested scope when the consent screen sends none, or a
195
+ * non-empty subset of it. Approval can narrow a request but never widen it.
196
+ */
197
+ const approvedScope = (body: unknown, requested: string | undefined | null): string | undefined => {
198
+ const narrowed = (body as {scope?: unknown} | null | undefined)?.scope;
199
+ if (narrowed === undefined) {
200
+ return requested ?? undefined;
201
+ }
202
+ if (typeof narrowed !== "string") {
203
+ throw new BadRequestError({
204
+ detail: "scope must be a space-separated string",
205
+ title: "Invalid scope",
206
+ });
207
+ }
208
+ const chosen = [...new Set(splitScope(narrowed))];
209
+ if (chosen.length === 0) {
210
+ throw new BadRequestError({
211
+ detail: "Approve at least one of the requested permissions",
212
+ title: "Choose at least one permission",
213
+ });
214
+ }
215
+ const requestedScopes = splitScope(requested);
216
+ const extra = chosen.filter((value) => !requestedScopes.includes(value));
217
+ if (extra.length > 0) {
218
+ throw new BadRequestError({
219
+ detail: `Not requested by the client: ${extra.join(" ")}`,
220
+ title: "Scope was not requested",
221
+ });
222
+ }
223
+ // Keep the client's requested order so the issued scope string is stable.
224
+ return requestedScopes.filter((value) => chosen.includes(value)).join(" ");
225
+ };
226
+
158
227
  const normalizeResource = (resource: string): string => resource.replace(/\/$/, "");
159
228
 
160
229
  const pkceS256 = (verifier: string): string =>
@@ -454,6 +523,18 @@ const addConsentRoutes = (
454
523
  clientId: {type: "string"},
455
524
  clientName: {type: "string"},
456
525
  expiresAt: {type: "string"},
526
+ grants: {
527
+ items: {
528
+ properties: {
529
+ access: {enum: ["read", "write"], type: "string"},
530
+ description: {nullable: true, type: "string"},
531
+ label: {type: "string"},
532
+ scope: {type: "string"},
533
+ },
534
+ type: "object",
535
+ },
536
+ type: "array",
537
+ },
457
538
  redirectHost: {type: "string"},
458
539
  redirectUri: {type: "string"},
459
540
  requestId: {type: "string"},
@@ -474,6 +555,7 @@ const addConsentRoutes = (
474
555
  clientId: authorization.clientId,
475
556
  clientName: client?.clientName ?? null,
476
557
  expiresAt: authorization.expiresAt.toISOString(),
558
+ grants: consentGrantsFor(authorization.scope, oauth.grants),
477
559
  redirectHost: new URL(authorization.redirectUri).host,
478
560
  redirectUri: authorization.redirectUri,
479
561
  requestId: authorization.requestId,
@@ -484,7 +566,10 @@ const addConsentRoutes = (
484
566
  })
485
567
  );
486
568
 
487
- const decisionOpenApi = (operationId: string, summary: string): RequestHandler =>
569
+ const decisionOpenApiBuilder = (
570
+ operationId: string,
571
+ summary: string
572
+ ): ReturnType<typeof createOpenApiBuilder> =>
488
573
  createOpenApiBuilder(openApiOptions)
489
574
  .withTags(["mcp"])
490
575
  .withOperationId(operationId)
@@ -498,18 +583,32 @@ const addConsentRoutes = (
498
583
  properties: {redirectUrl: {type: "string"}},
499
584
  type: "object",
500
585
  },
501
- })
502
- .build();
586
+ });
587
+
588
+ const decisionOpenApi = (operationId: string, summary: string): RequestHandler =>
589
+ decisionOpenApiBuilder(operationId, summary).build();
503
590
 
504
591
  app.post(
505
592
  "/oauth/authorize/:request/approve",
506
593
  [
507
594
  ...consentGuards,
508
- decisionOpenApi("approveMcpOAuthRequest", "Approve a pending MCP OAuth request"),
595
+ decisionOpenApiBuilder("approveMcpOAuthRequest", "Approve a pending MCP OAuth request")
596
+ .withRequestBody<{scope: string}>(
597
+ {
598
+ scope: {
599
+ description:
600
+ "Space-separated subset of the requested scope the user approved. Omit to approve the full requested scope.",
601
+ type: "string",
602
+ },
603
+ },
604
+ {required: false}
605
+ )
606
+ .build(),
509
607
  ],
510
608
  asyncHandler(async (req, res) => {
511
609
  const user = requireUser(req);
512
610
  const pending = await loadPendingAuthorization(String(req.params.request));
611
+ const scope = approvedScope(req.body, pending.scope);
513
612
  const code = generateMcpOAuthSecret();
514
613
  const now = DateTime.now();
515
614
  const codeExpiresAt = now.plus({seconds: oauth.authorizationCodeTtlSeconds});
@@ -524,6 +623,7 @@ const addConsentRoutes = (
524
623
  codeExpiresAt: codeExpiresAt.toJSDate(),
525
624
  codeHash: hashMcpOAuthSecret(code),
526
625
  expiresAt: expiresAt.toJSDate(),
626
+ ...(scope === undefined ? {} : {scope}),
527
627
  status: "approved",
528
628
  tokenEpoch: userTokenEpoch(user),
529
629
  userId: new mongoose.Types.ObjectId(String(user._id)),
@@ -855,9 +955,17 @@ const exchangeClientCredentials = async (
855
955
  if (!user || userIsDisabled(user)) {
856
956
  throw new OAuthProtocolError("invalid_grant", "The user cannot be granted a token");
857
957
  }
958
+ // A client stored before the app switched to grants may hold scopes the server no longer
959
+ // supports; only the supported ones can be issued.
858
960
  const allowed = client.scope
859
- ? client.scope.split(" ").filter((scope) => scope.length > 0)
961
+ ? splitScope(client.scope).filter((value) => oauth.scopesSupported.includes(value))
860
962
  : oauth.scopesSupported;
963
+ if (allowed.length === 0) {
964
+ throw new OAuthProtocolError(
965
+ "invalid_scope",
966
+ "The client's scope has no scope this server supports"
967
+ );
968
+ }
861
969
  const scope = parseScope(stringParam(body.scope), allowed);
862
970
  const issued = await issueOrInvalidGrant({
863
971
  accessTokenTtlSeconds: oauth.accessTokenTtlSeconds,
@@ -2,7 +2,36 @@ import {describe, expect, it} from "bun:test";
2
2
  import express from "express";
3
3
  import supertest from "supertest";
4
4
 
5
- import {sendProtocolJson} from "./oauthMetadata";
5
+ import type {McpOAuthGrant} from "../index";
6
+ import {
7
+ buildAuthorizationServerMetadata,
8
+ type McpOAuthOptions,
9
+ resolveMcpOAuthOption,
10
+ sendProtocolJson,
11
+ } from "./oauthMetadata";
12
+
13
+ const baseOptions: McpOAuthOptions = {
14
+ consentUrl: "https://app.example.com/oauth/consent",
15
+ enabled: true,
16
+ issuer: "https://api.example.com",
17
+ };
18
+
19
+ // Takes `unknown` so the validation cases can pass invalid grants past the type checker.
20
+ const withGrants = (grants: unknown, extra: Record<string, unknown> = {}): McpOAuthOptions =>
21
+ ({...baseOptions, ...extra, grants}) as McpOAuthOptions;
22
+
23
+ const READ_GRANT: McpOAuthGrant = {
24
+ access: "read",
25
+ description: "See your records. It cannot change anything.",
26
+ label: "Read your data",
27
+ scope: "mcp:read",
28
+ };
29
+ const WRITE_GRANT: McpOAuthGrant = {
30
+ access: "write",
31
+ description: "Create, update, and delete records for you.",
32
+ label: "Change your data",
33
+ scope: "mcp:write",
34
+ };
6
35
 
7
36
  describe("sendProtocolJson", () => {
8
37
  it("serializes reflected input as JSON with a JSON content type", async () => {
@@ -17,3 +46,98 @@ describe("sendProtocolJson", () => {
17
46
  expect(res.text).toBe(JSON.stringify({error: "invalid_request", error_description: payload}));
18
47
  });
19
48
  });
49
+
50
+ describe("resolveMcpOAuthOption grants", () => {
51
+ it('resolves "readOnly" to the read preset', () => {
52
+ const resolved = resolveMcpOAuthOption(withGrants("readOnly"));
53
+
54
+ expect(resolved?.scopesSupported).toEqual(["mcp:read"]);
55
+ expect(resolved?.grants).toEqual([READ_GRANT]);
56
+ });
57
+
58
+ it('resolves "readWrite" to read then write, in that order', () => {
59
+ const resolved = resolveMcpOAuthOption(withGrants("readWrite"));
60
+
61
+ expect(resolved?.scopesSupported).toEqual(["mcp:read", "mcp:write"]);
62
+ expect(resolved?.grants).toEqual([READ_GRANT, WRITE_GRANT]);
63
+ });
64
+
65
+ it("keeps a custom grant as given and derives scopesSupported from it", () => {
66
+ const custom: McpOAuthGrant[] = [{access: "write", label: "Todos", scope: "todos"}];
67
+ const resolved = resolveMcpOAuthOption(withGrants(custom));
68
+
69
+ expect(resolved?.scopesSupported).toEqual(["todos"]);
70
+ expect(resolved?.grants).toEqual(custom);
71
+ });
72
+
73
+ it("advertises preset scopes in the authorization-server metadata", () => {
74
+ const readOnly = resolveMcpOAuthOption(withGrants("readOnly"));
75
+ const readWrite = resolveMcpOAuthOption(withGrants("readWrite"));
76
+ if (!(readOnly && readWrite)) {
77
+ throw new Error("expected resolved options");
78
+ }
79
+
80
+ expect(buildAuthorizationServerMetadata(readOnly).scopes_supported).toEqual(["mcp:read"]);
81
+ expect(buildAuthorizationServerMetadata(readWrite).scopes_supported).toEqual([
82
+ "mcp:read",
83
+ "mcp:write",
84
+ ]);
85
+ });
86
+
87
+ it("leaves grants undefined and scopesSupported as [mcp] when neither is set", () => {
88
+ const resolved = resolveMcpOAuthOption(baseOptions);
89
+
90
+ expect(resolved?.scopesSupported).toEqual(["mcp"]);
91
+ expect(resolved).toHaveProperty("grants", undefined);
92
+ });
93
+
94
+ it("keeps an explicit scopesSupported when grants is unset", () => {
95
+ const resolved = resolveMcpOAuthOption({...baseOptions, scopesSupported: ["a", "b"]});
96
+
97
+ expect(resolved?.scopesSupported).toEqual(["a", "b"]);
98
+ expect(resolved).toHaveProperty("grants", undefined);
99
+ });
100
+
101
+ it("throws when both grants and scopesSupported are set", () => {
102
+ // The per-occurrence text lives in `detail`; `title` (and so `message`) stays a stable summary.
103
+ let caught: unknown;
104
+ try {
105
+ resolveMcpOAuthOption(withGrants("readOnly", {scopesSupported: ["mcp"]}));
106
+ } catch (error) {
107
+ caught = error;
108
+ }
109
+ expect(caught).toMatchObject({
110
+ detail: "mcpOAuth: set grants or scopesSupported, not both",
111
+ title: "MCP OAuth is misconfigured",
112
+ });
113
+ });
114
+
115
+ it("throws for an empty grants list", () => {
116
+ expect(() => resolveMcpOAuthOption(withGrants([]))).toThrow();
117
+ });
118
+
119
+ it("throws for a duplicate scope", () => {
120
+ const dup = [
121
+ {access: "read", label: "A", scope: "todos"},
122
+ {access: "write", label: "B", scope: "todos"},
123
+ ];
124
+
125
+ expect(() => resolveMcpOAuthOption(withGrants(dup))).toThrow();
126
+ });
127
+
128
+ it("throws for a scope containing a space", () => {
129
+ expect(() =>
130
+ resolveMcpOAuthOption(withGrants([{access: "read", label: "A", scope: "to dos"}]))
131
+ ).toThrow();
132
+ });
133
+
134
+ it("throws for an unknown preset string", () => {
135
+ expect(() => resolveMcpOAuthOption(withGrants("admin"))).toThrow();
136
+ });
137
+
138
+ it("throws for an invalid access level", () => {
139
+ expect(() =>
140
+ resolveMcpOAuthOption(withGrants([{access: "admin", label: "A", scope: "todos"}]))
141
+ ).toThrow();
142
+ });
143
+ });
@@ -13,6 +13,51 @@ const DEFAULT_AUTHORIZATION_REQUEST_TTL_SECONDS = 10 * 60;
13
13
  const DEFAULT_AUTHORIZATION_CODE_TTL_SECONDS = 60;
14
14
  const DEFAULT_SCOPES = ["mcp"];
15
15
 
16
+ /**
17
+ * One permission an MCP OAuth client can be granted. The consent screen shows its `label` and
18
+ * `description`; the server enforces its `access` level on every tool the token calls.
19
+ */
20
+ export interface McpOAuthGrant {
21
+ /** OAuth scope value. No spaces, since scopes are space-delimited on the wire. */
22
+ scope: string;
23
+ /** Short name the consent screen shows next to the grant's checkbox. */
24
+ label: string;
25
+ /** Longer explanation shown under the label. */
26
+ description?: string;
27
+ /** `read` allows read-only tools; `write` allows every tool, since write implies read. */
28
+ access: McpOAuthGrantAccess;
29
+ }
30
+
31
+ /** Access level a grant gives. Write implies read. */
32
+ export type McpOAuthGrantAccess = "read" | "write";
33
+
34
+ /** Named grant sets for `mcpOAuth.grants`. */
35
+ export type McpOAuthGrantPreset = "readOnly" | "readWrite";
36
+
37
+ const READ_GRANT: McpOAuthGrant = {
38
+ access: "read",
39
+ description: "See your records. It cannot change anything.",
40
+ label: "Read your data",
41
+ scope: "mcp:read",
42
+ };
43
+
44
+ const WRITE_GRANT: McpOAuthGrant = {
45
+ access: "write",
46
+ description: "Create, update, and delete records for you.",
47
+ label: "Change your data",
48
+ scope: "mcp:write",
49
+ };
50
+
51
+ /** The grants each `mcpOAuth.grants` preset expands to, in consent-screen order. */
52
+ export const MCP_OAUTH_GRANT_PRESETS: Readonly<
53
+ Record<McpOAuthGrantPreset, readonly McpOAuthGrant[]>
54
+ > = {
55
+ readOnly: [READ_GRANT],
56
+ readWrite: [READ_GRANT, WRITE_GRANT],
57
+ };
58
+
59
+ const GRANT_ACCESS_LEVELS = new Set<string>(["read", "write"]);
60
+
16
61
  /** Grants a public PKCE client may register. Dynamic registration rejects anything else. */
17
62
  export const PUBLIC_CLIENT_GRANT_TYPES = ["authorization_code", "refresh_token"];
18
63
  const SUPPORTED_GRANT_TYPES = [...PUBLIC_CLIENT_GRANT_TYPES, "client_credentials"];
@@ -51,8 +96,17 @@ export interface McpOAuthOptions {
51
96
  allowedRedirectHosts?: string[];
52
97
  /** RFC 8707 resource identifier for `/mcp`. Default: `${issuer}/mcp`. */
53
98
  resource?: string;
54
- /** Scopes advertised and accepted. Default: `["mcp"]`. */
99
+ /**
100
+ * Scopes advertised and accepted, without enforcement. Default: `["mcp"]`. Cannot be combined
101
+ * with `grants`, which derives the scopes from its grants.
102
+ */
55
103
  scopesSupported?: string[];
104
+ /**
105
+ * Enforced grants a client can request and the user can approve: the `"readOnly"` or
106
+ * `"readWrite"` preset, or your own list. Sets `scopesSupported` to the grants' scopes. While
107
+ * unset, the default `mcp` scope is accepted and not enforced.
108
+ */
109
+ grants?: McpOAuthGrantPreset | McpOAuthGrant[];
56
110
  /** Access token lifetime. Default: 3600 (one hour). */
57
111
  accessTokenTtlSeconds?: number;
58
112
  /** Refresh token lifetime. Default: 30 days. */
@@ -78,6 +132,8 @@ export interface ResolvedMcpOAuthOptions {
78
132
  /** URL of the RFC 9728 protected-resource metadata for {@link resource}. */
79
133
  resourceMetadataUrl: string;
80
134
  scopesSupported: string[];
135
+ /** Enforced grants, or undefined while `mcpOAuth.grants` is unset. */
136
+ grants: McpOAuthGrant[] | undefined;
81
137
  }
82
138
 
83
139
  const misconfigured = (detail: string): APIError =>
@@ -106,6 +162,41 @@ const positiveInteger = (value: number | undefined, fallback: number, field: str
106
162
  return value;
107
163
  };
108
164
 
165
+ const resolveGrants = (grants: McpOAuthOptions["grants"]): McpOAuthGrant[] => {
166
+ if (typeof grants === "string") {
167
+ if (!Object.hasOwn(MCP_OAUTH_GRANT_PRESETS, grants)) {
168
+ throw misconfigured(
169
+ `mcpOAuth.grants must be "readOnly", "readWrite", or a list of grants, got "${grants}"`
170
+ );
171
+ }
172
+ return MCP_OAUTH_GRANT_PRESETS[grants].map((grant) => ({...grant}));
173
+ }
174
+ if (!Array.isArray(grants) || grants.length === 0) {
175
+ throw misconfigured("mcpOAuth.grants must list at least one grant");
176
+ }
177
+ const seen = new Set<string>();
178
+ for (const grant of grants) {
179
+ if (typeof grant?.scope !== "string" || !/^[\x21\x23-\x5B\x5D-\x7E]+$/.test(grant.scope)) {
180
+ throw misconfigured(
181
+ `mcpOAuth.grants scope must be a non-empty string without spaces, got "${grant?.scope}"`
182
+ );
183
+ }
184
+ if (seen.has(grant.scope)) {
185
+ throw misconfigured(`mcpOAuth.grants lists scope "${grant.scope}" more than once`);
186
+ }
187
+ seen.add(grant.scope);
188
+ if (typeof grant.label !== "string" || grant.label.trim() === "") {
189
+ throw misconfigured(`mcpOAuth.grants "${grant.scope}" needs a label`);
190
+ }
191
+ if (!GRANT_ACCESS_LEVELS.has(grant.access)) {
192
+ throw misconfigured(
193
+ `mcpOAuth.grants "${grant.scope}" access must be "read" or "write", got "${grant.access}"`
194
+ );
195
+ }
196
+ }
197
+ return grants;
198
+ };
199
+
109
200
  /** RFC 9728 §3.1: the well-known segment goes between the host and the resource's path. */
110
201
  export const protectedResourceMetadataPath = (resource: string): string => {
111
202
  const {pathname} = new URL(resource);
@@ -141,7 +232,12 @@ export const resolveMcpOAuthOption = (
141
232
  const issuer = issuerUrl.origin;
142
233
  const resource = option.resource ?? `${issuer}/mcp`;
143
234
  parseAbsoluteUrl(resource, "resource");
144
- const scopesSupported = option.scopesSupported ?? DEFAULT_SCOPES;
235
+ if (option.grants !== undefined && option.scopesSupported !== undefined) {
236
+ throw misconfigured("mcpOAuth: set grants or scopesSupported, not both");
237
+ }
238
+ const grants = option.grants === undefined ? undefined : resolveGrants(option.grants);
239
+ const scopesSupported =
240
+ grants?.map((grant) => grant.scope) ?? option.scopesSupported ?? DEFAULT_SCOPES;
145
241
  if (scopesSupported.length === 0) {
146
242
  throw misconfigured("mcpOAuth.scopesSupported must list at least one scope");
147
243
  }
@@ -164,6 +260,7 @@ export const resolveMcpOAuthOption = (
164
260
  ),
165
261
  consentUrl: option.consentUrl,
166
262
  dynamicClientRegistration,
263
+ grants,
167
264
  issuer,
168
265
  refreshTokenTtlSeconds: positiveInteger(
169
266
  option.refreshTokenTtlSeconds,
@@ -9,13 +9,20 @@ import {
9
9
  registerCollection,
10
10
  replaceCollectionOptions,
11
11
  } from "../collectionRegistry";
12
- import type {MCPConfig, MCPRegistryEntry, MCPToolArgs, MCPToolResult} from "./types";
12
+ import type {MCPConfig, MCPRegistryEntry, MCPToolAccess, MCPToolArgs, MCPToolResult} from "./types";
13
13
 
14
14
  export interface MCPCustomTool {
15
15
  description: string;
16
16
  handler: (args: MCPToolArgs, user?: User) => Promise<MCPToolResult>;
17
17
  name: string;
18
18
  zodSchema: ZodType;
19
+ /**
20
+ * `read` for tools that only read data, `write` for tools that can change it. Default:
21
+ * `"write"`, so a read-only OAuth grant cannot call the tool until it declares `"read"`.
22
+ */
23
+ access?: MCPToolAccess;
24
+ /** When set, an OAuth token must hold exactly this scope to see and call the tool. */
25
+ scope?: string;
19
26
  }
20
27
 
21
28
  const mcpCustomTools: MCPCustomTool[] = [];