@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
@@ -1,15 +1,26 @@
1
- import {beforeEach, describe, expect, it} from "bun:test";
1
+ import {afterEach, beforeEach, describe, expect, it} from "bun:test";
2
2
  import type {Server as HttpServer} from "node:http";
3
3
  import type {AddressInfo} from "node:net";
4
4
  import {Client, StreamableHTTPClientTransport} from "@modelcontextprotocol/client";
5
5
  import express from "express";
6
+ import jwt from "jsonwebtoken";
6
7
  import mongoose, {Schema} from "mongoose";
7
8
  import supertest from "supertest";
9
+ import {z} from "zod";
8
10
 
9
11
  import type {UserModel} from "../auth";
12
+ import type {BetterAuthInstance} from "../betterAuthSetup";
13
+ import {McpOAuthToken} from "../models/mcpOAuthToken";
14
+ import {McpRequestLog} from "../models/mcpRequestLog";
15
+ import {McpServiceToken} from "../models/mcpServiceToken";
16
+ import {McpToolSetting} from "../models/mcpToolSetting";
10
17
  import {Permissions} from "../permissions";
11
- import {clearMCPRegistry, registerMCPModel} from "./registry";
18
+ import {findOneOrNone} from "../plugins";
19
+ import {setupDb} from "../tests";
20
+ import {type McpOAuthGrant, type McpOAuthOptions, resolveMcpOAuthOption} from "./oauthMetadata";
21
+ import {clearMCPRegistry, registerMCPModel, registerMCPTool} from "./registry";
12
22
  import {mountMCPServer} from "./server";
23
+ import type {MCPConfig} from "./types";
13
24
 
14
25
  interface MCPServerDocFields {
15
26
  _id: mongoose.Types.ObjectId;
@@ -224,3 +235,409 @@ describe("mountMCPServer", () => {
224
235
  expect(res.body.jsonrpc).toBe("2.0");
225
236
  });
226
237
  });
238
+
239
+ // ---------------------------------------------------------------------------------------------
240
+ // Grant enforcement: which tools an OAuth token sees and can call, per its scopes.
241
+ // ---------------------------------------------------------------------------------------------
242
+
243
+ interface GrantUserFields {
244
+ _id: mongoose.Types.ObjectId;
245
+ betterAuthId?: string;
246
+ email?: string;
247
+ tokenEpoch?: number;
248
+ }
249
+
250
+ const grantUserSchema = new Schema({
251
+ betterAuthId: {description: "Better Auth user id", index: true, type: String},
252
+ email: {description: "User email", type: String},
253
+ tokenEpoch: {description: "Credential generation", type: Number},
254
+ });
255
+ grantUserSchema.plugin(findOneOrNone);
256
+ const GrantUser = getModel("MCPGrantUser", grantUserSchema) as unknown as mongoose.Model<
257
+ GrantUserFields,
258
+ Record<string, never>
259
+ >;
260
+
261
+ const GrantTodo = getModel(
262
+ "MCPGrantTodo",
263
+ new Schema({title: {description: "Todo title", type: String}})
264
+ ) as mongoose.Model<MCPServerDocFields>;
265
+
266
+ const GRANT_ISSUER = "https://api.example.com";
267
+ const ACCEPT = "application/json, text/event-stream";
268
+ const ALL_SIX_TOOLS = [
269
+ "lookup",
270
+ "notify",
271
+ "todos_create",
272
+ "todos_list",
273
+ "todos_mark_complete",
274
+ "todos_read",
275
+ ];
276
+
277
+ const todoPermissions = {
278
+ create: [Permissions.IsAuthenticated],
279
+ delete: [Permissions.IsAuthenticated],
280
+ list: [Permissions.IsAuthenticated],
281
+ read: [Permissions.IsAuthenticated],
282
+ update: [Permissions.IsAuthenticated],
283
+ };
284
+
285
+ const registerGrantTools = (mcp: MCPConfig = {methods: ["list", "read", "create"]}): void => {
286
+ registerMCPModel(GrantTodo, {toolPrefix: "todos", ...mcp}, {
287
+ instanceActions: {
288
+ markComplete: {
289
+ handler: async ({doc}) => doc,
290
+ mcp: {name: "todos_mark_complete"},
291
+ method: "POST",
292
+ permissions: [Permissions.IsAuthenticated],
293
+ },
294
+ },
295
+ permissions: todoPermissions,
296
+ queryFields: ["title"],
297
+ } as never);
298
+ registerMCPTool({
299
+ access: "read",
300
+ description: "Look something up",
301
+ handler: async () => ({content: [{text: "found", type: "text"}]}),
302
+ name: "lookup",
303
+ zodSchema: z.object({}).strict(),
304
+ } as never);
305
+ // No access declared: defaults to write
306
+ registerMCPTool({
307
+ description: "Send a notification",
308
+ handler: async () => ({content: [{text: "sent", type: "text"}]}),
309
+ name: "notify",
310
+ zodSchema: z.object({}).strict(),
311
+ } as never);
312
+ };
313
+
314
+ const fakeBetterAuth = (): BetterAuthInstance => {
315
+ return {
316
+ api: {
317
+ getSession: async ({headers}: {headers: Record<string, string>}) =>
318
+ headers.cookie ? {session: {id: "session-1"}, user: {id: "ba-grants"}} : null,
319
+ },
320
+ } as unknown as BetterAuthInstance;
321
+ };
322
+
323
+ const buildGrantApp = ({
324
+ grants,
325
+ requestLog,
326
+ toolSettings,
327
+ }: {
328
+ grants?: McpOAuthOptions["grants"];
329
+ requestLog?: boolean;
330
+ toolSettings?: boolean;
331
+ } = {}): express.Application => {
332
+ const app = express();
333
+ app.use(express.json());
334
+ mountMCPServer(app, {
335
+ betterAuth: fakeBetterAuth(),
336
+ mcpOAuth: resolveMcpOAuthOption({
337
+ consentUrl: "https://app.example.com/oauth/consent",
338
+ enabled: true,
339
+ grants,
340
+ issuer: GRANT_ISSUER,
341
+ }),
342
+ mcpServiceTokens: true,
343
+ requestLog: requestLog ? {retentionDays: 7} : undefined,
344
+ toolSettings,
345
+ userModel: GrantUser as unknown as UserModel,
346
+ });
347
+ return app;
348
+ };
349
+
350
+ const rpcPayload = (text: string): {error?: unknown; result?: Record<string, unknown>} => {
351
+ const dataLine = text.split("\n").find((line) => line.startsWith("data:"));
352
+ return JSON.parse(dataLine ? dataLine.slice("data:".length) : text);
353
+ };
354
+
355
+ const mcpPost = (app: express.Application, body: object, headers: Record<string, string>) => {
356
+ const request = supertest(app).post("/mcp").set("accept", ACCEPT);
357
+ for (const [key, value] of Object.entries(headers)) {
358
+ request.set(key, value);
359
+ }
360
+ return request.send(body);
361
+ };
362
+
363
+ const toolNames = async (
364
+ app: express.Application,
365
+ headers: Record<string, string>
366
+ ): Promise<string[]> => {
367
+ const res = await mcpPost(
368
+ app,
369
+ {id: 2, jsonrpc: "2.0", method: "tools/list", params: {}},
370
+ headers
371
+ );
372
+ expect(res.status).toBe(200);
373
+ const tools = (rpcPayload(res.text).result?.tools ?? []) as {name: string}[];
374
+ return tools.map((tool) => tool.name).sort();
375
+ };
376
+
377
+ const callGrantTool = (
378
+ app: express.Application,
379
+ name: string,
380
+ headers: Record<string, string>,
381
+ args: Record<string, unknown> = {}
382
+ ) =>
383
+ mcpPost(
384
+ app,
385
+ {id: 3, jsonrpc: "2.0", method: "tools/call", params: {arguments: args, name}},
386
+ headers
387
+ );
388
+
389
+ const isRefusal = (text: string): boolean => {
390
+ const payload = rpcPayload(text);
391
+ return Boolean(payload.error) || payload.result?.isError === true;
392
+ };
393
+
394
+ describe("MCP grant enforcement", () => {
395
+ let user: GrantUserFields;
396
+ let bearer: (scope: string) => Promise<Record<string, string>>;
397
+
398
+ beforeEach(async () => {
399
+ await setupDb();
400
+ clearMCPRegistry();
401
+ await Promise.all([
402
+ GrantUser.deleteMany({}),
403
+ GrantTodo.deleteMany({}),
404
+ McpOAuthToken.deleteMany({}),
405
+ McpServiceToken.deleteMany({}),
406
+ McpRequestLog.deleteMany({}),
407
+ McpToolSetting.deleteMany({}),
408
+ ]);
409
+ user = (await GrantUser.create({betterAuthId: "ba-grants", email: "g@example.com"})) as never;
410
+ bearer = async (scope: string): Promise<Record<string, string>> => {
411
+ const issued = await McpOAuthToken.issue({
412
+ accessTokenTtlSeconds: 60,
413
+ clientId: "client",
414
+ refreshTokenTtlSeconds: 600,
415
+ scope,
416
+ userId: user._id,
417
+ });
418
+ return {authorization: `Bearer ${issued.accessToken}`};
419
+ };
420
+ });
421
+
422
+ afterEach(() => {
423
+ clearMCPRegistry();
424
+ });
425
+
426
+ it("shows a mcp:read token only the read tools", async () => {
427
+ registerGrantTools();
428
+ const app = buildGrantApp({grants: "readWrite"});
429
+
430
+ expect(await toolNames(app, await bearer("mcp:read"))).toEqual([
431
+ "lookup",
432
+ "todos_list",
433
+ "todos_read",
434
+ ]);
435
+ });
436
+
437
+ it("refuses a write tool call from a mcp:read token and creates nothing", async () => {
438
+ registerGrantTools();
439
+ const app = buildGrantApp({grants: "readWrite"});
440
+
441
+ const res = await callGrantTool(app, "todos_create", await bearer("mcp:read"), {title: "x"});
442
+
443
+ expect(isRefusal(res.text)).toBe(true);
444
+ expect(await GrantTodo.countDocuments({})).toBe(0);
445
+ });
446
+
447
+ it("refuses a write action tool and an untagged custom tool from a mcp:read token", async () => {
448
+ registerGrantTools();
449
+ const app = buildGrantApp({grants: "readWrite"});
450
+ const headers = await bearer("mcp:read");
451
+ const todo = await GrantTodo.create({title: "t"});
452
+
453
+ const action = await callGrantTool(app, "todos_mark_complete", headers, {id: String(todo._id)});
454
+ const notify = await callGrantTool(app, "notify", headers);
455
+
456
+ expect(isRefusal(action.text)).toBe(true);
457
+ expect(isRefusal(notify.text)).toBe(true);
458
+ expect(notify.text).not.toContain("sent");
459
+ });
460
+
461
+ it("still lets a mcp:read token call a read tool", async () => {
462
+ registerGrantTools();
463
+ const app = buildGrantApp({grants: "readWrite"});
464
+
465
+ const res = await callGrantTool(app, "lookup", await bearer("mcp:read"));
466
+
467
+ expect(isRefusal(res.text)).toBe(false);
468
+ expect(res.text).toContain("found");
469
+ });
470
+
471
+ it("shows a mcp:read mcp:write token all 6 tools and lets it create", async () => {
472
+ registerGrantTools();
473
+ const app = buildGrantApp({grants: "readWrite"});
474
+ const headers = await bearer("mcp:read mcp:write");
475
+
476
+ expect(await toolNames(app, headers)).toEqual(ALL_SIX_TOOLS);
477
+ const res = await callGrantTool(app, "todos_create", headers, {title: "made"});
478
+ expect(isRefusal(res.text)).toBe(false);
479
+ expect(await GrantTodo.countDocuments({title: "made"})).toBe(1);
480
+ });
481
+
482
+ it("shows a mcp:write-only token all 6 tools (write implies read)", async () => {
483
+ registerGrantTools();
484
+ const app = buildGrantApp({grants: "readWrite"});
485
+
486
+ expect(await toolNames(app, await bearer("mcp:write"))).toEqual(ALL_SIX_TOOLS);
487
+ });
488
+
489
+ it("shows a Better Auth session all 6 tools", async () => {
490
+ registerGrantTools();
491
+ const app = buildGrantApp({grants: "readOnly"});
492
+
493
+ expect(await toolNames(app, {cookie: "session=1"})).toEqual(ALL_SIX_TOOLS);
494
+ });
495
+
496
+ it("shows a JWT bearer all 6 tools", async () => {
497
+ registerGrantTools();
498
+ const app = buildGrantApp({grants: "readOnly"});
499
+ const token = jwt.sign({id: String(user._id)}, process.env.TOKEN_SECRET as string, {
500
+ issuer: process.env.TOKEN_ISSUER,
501
+ });
502
+
503
+ expect(await toolNames(app, {authorization: `Bearer ${token}`})).toEqual(ALL_SIX_TOOLS);
504
+ });
505
+
506
+ it("shows an mcp_ service token all 6 tools", async () => {
507
+ registerGrantTools();
508
+ const app = buildGrantApp({grants: "readOnly"});
509
+ const {token} = await McpServiceToken.issueFor(user, {name: "Agent"});
510
+
511
+ expect(await toolNames(app, {authorization: `Bearer ${token}`})).toEqual(ALL_SIX_TOOLS);
512
+ });
513
+
514
+ it("lets a service token call a write tool under readOnly grants", async () => {
515
+ registerGrantTools();
516
+ const app = buildGrantApp({grants: "readOnly"});
517
+ const {token} = await McpServiceToken.issueFor(user, {name: "Agent"});
518
+
519
+ const res = await callGrantTool(
520
+ app,
521
+ "todos_create",
522
+ {authorization: `Bearer ${token}`},
523
+ {
524
+ title: "svc",
525
+ }
526
+ );
527
+
528
+ expect(isRefusal(res.text)).toBe(false);
529
+ expect(await GrantTodo.countDocuments({title: "svc"})).toBe(1);
530
+ });
531
+
532
+ it("shows every tool to an mcp-scoped token when grants is unset", async () => {
533
+ registerGrantTools();
534
+ const app = buildGrantApp();
535
+
536
+ expect(await toolNames(app, await bearer("mcp"))).toEqual(ALL_SIX_TOOLS);
537
+ });
538
+
539
+ it("shows a legacy mcp-scoped token no tools once grants is set", async () => {
540
+ registerGrantTools();
541
+ const app = buildGrantApp({grants: "readWrite"});
542
+
543
+ expect(await toolNames(app, await bearer("mcp"))).toEqual([]);
544
+ });
545
+
546
+ it("refuses a call from a legacy mcp-scoped token once grants is set", async () => {
547
+ registerGrantTools();
548
+ const app = buildGrantApp({grants: "readWrite"});
549
+
550
+ const res = await callGrantTool(app, "lookup", await bearer("mcp"));
551
+
552
+ expect(isRefusal(res.text)).toBe(true);
553
+ // Match the tool's text payload: the SDK's refusal "Tool lookup not found" contains "found"
554
+ expect(res.text).not.toContain('"text":"found"');
555
+ });
556
+
557
+ it("shows a token with an unrelated scope no tools", async () => {
558
+ registerGrantTools();
559
+ const app = buildGrantApp({grants: "readWrite"});
560
+
561
+ expect(await toolNames(app, await bearer("other"))).toEqual([]);
562
+ });
563
+
564
+ describe("per-method scopes", () => {
565
+ const customGrants: McpOAuthGrant[] = [
566
+ {access: "read", label: "Read", scope: "mcp:read"},
567
+ {access: "write", label: "Write", scope: "mcp:write"},
568
+ {access: "write", label: "Todo admin", scope: "todos:admin"},
569
+ ];
570
+ const withDelete: MCPConfig = {
571
+ methods: ["list", "read", "create", "delete"],
572
+ scopes: {delete: "todos:admin"},
573
+ };
574
+
575
+ it("hides a scoped tool from a token that lacks the scope", async () => {
576
+ registerGrantTools(withDelete);
577
+ const app = buildGrantApp({grants: customGrants});
578
+
579
+ const names = await toolNames(app, await bearer("mcp:read mcp:write"));
580
+
581
+ expect(names).not.toContain("todos_delete");
582
+ expect(names).toContain("todos_create");
583
+ });
584
+
585
+ it("refuses a call to a scoped tool without the scope and deletes nothing", async () => {
586
+ registerGrantTools(withDelete);
587
+ const app = buildGrantApp({grants: customGrants});
588
+ const todo = await GrantTodo.create({title: "keep"});
589
+
590
+ const res = await callGrantTool(app, "todos_delete", await bearer("mcp:read mcp:write"), {
591
+ id: String(todo._id),
592
+ });
593
+
594
+ expect(isRefusal(res.text)).toBe(true);
595
+ expect(await GrantTodo.countDocuments({_id: todo._id})).toBe(1);
596
+ });
597
+
598
+ it("shows a scoped tool to a token that holds the scope", async () => {
599
+ registerGrantTools(withDelete);
600
+ const app = buildGrantApp({grants: customGrants});
601
+
602
+ const names = await toolNames(app, await bearer("mcp:read todos:admin"));
603
+
604
+ expect(names).toContain("todos_delete");
605
+ });
606
+ });
607
+
608
+ describe("blast radius", () => {
609
+ it("still records every tool in McpToolSetting regardless of grants", async () => {
610
+ registerGrantTools();
611
+ buildGrantApp({grants: "readWrite", toolSettings: true});
612
+
613
+ for (let attempt = 0; attempt < 50; attempt++) {
614
+ if ((await McpToolSetting.countDocuments({})) >= 6) {
615
+ break;
616
+ }
617
+ await new Promise((resolve) => setTimeout(resolve, 10));
618
+ }
619
+ const rows = await McpToolSetting.find({}).lean();
620
+ expect(rows.map((row) => row.name).sort()).toEqual(ALL_SIX_TOOLS);
621
+ });
622
+
623
+ it("logs no ok outcome for a refused call", async () => {
624
+ registerGrantTools();
625
+ const app = buildGrantApp({grants: "readWrite", requestLog: true});
626
+ const headers = await bearer("mcp:read");
627
+
628
+ await callGrantTool(app, "todos_create", headers, {title: "x"});
629
+ // An allowed call flushes the fire-and-forget log writer before we inspect the rows
630
+ await callGrantTool(app, "lookup", headers);
631
+ for (let attempt = 0; attempt < 50; attempt++) {
632
+ if ((await McpRequestLog.countDocuments({toolName: "lookup"})) >= 1) {
633
+ break;
634
+ }
635
+ await new Promise((resolve) => setTimeout(resolve, 10));
636
+ }
637
+
638
+ const refused = await McpRequestLog.find({toolName: "todos_create"}).lean();
639
+ expect(refused.filter((row) => row.outcome === "ok")).toEqual([]);
640
+ expect(await McpRequestLog.countDocuments({outcome: "ok", toolName: "lookup"})).toBe(1);
641
+ });
642
+ });
643
+ });
package/src/mcp/server.ts CHANGED
@@ -15,6 +15,7 @@ import {
15
15
  syncMcpToolSettings,
16
16
  } from "./adminTracking";
17
17
  import {extractAuthFromHeaders, type MCPAuthContext, type MCPAuthResult} from "./auth";
18
+ import {canUseMcpTool} from "./grantAccess";
18
19
  import {type ResolvedMcpOAuthOptions, sendMcpOAuthChallenge} from "./oauthMetadata";
19
20
  import {getAllMCPTools, type MCPToolDefinition} from "./toolGenerator";
20
21
 
@@ -61,7 +62,13 @@ export const mountMCPServer = (app: Application, options: MCPServerOptions): voi
61
62
  }
62
63
 
63
64
  const buildServer = async (auth: MCPAuthResult | undefined): Promise<McpServer> => {
64
- const served = options.toolSettings ? await filterEnabledMcpTools(tools) : tools;
65
+ const enabled = options.toolSettings ? await filterEnabledMcpTools(tools) : tools;
66
+ // Tools the caller's OAuth grants do not allow are left off this request's server, so
67
+ // tools/list hides them and tools/call fails as for an unknown tool.
68
+ const grants = options.mcpOAuth?.grants;
69
+ const served = enabled.filter((tool) =>
70
+ canUseMcpTool({credential: auth?.credential, grants, tokenScopes: auth?.scopes, tool})
71
+ );
65
72
  const onToolCall = options.requestLog
66
73
  ? (record: Omit<McpToolCallRecord, "auth">): void => {
67
74
  recordMcpToolCall({...record, auth}, options.requestLog as ResolvedMcpRequestLogOptions);
@@ -15,6 +15,7 @@ import {executeTool} from "./toolExecution";
15
15
  import type {
16
16
  MCPMethod,
17
17
  MCPRegistryEntry,
18
+ MCPToolAccess,
18
19
  MCPToolArgs,
19
20
  MCPToolInputSchema,
20
21
  MCPToolResult,
@@ -26,8 +27,20 @@ export interface MCPToolDefinition {
26
27
  inputSchema: MCPToolInputSchema;
27
28
  zodSchema: ZodType;
28
29
  handler: (args: MCPToolArgs, user?: User) => Promise<MCPToolResult>;
30
+ /** `read` tools only read data; `write` tools can change it. Enforced for OAuth grants. */
31
+ access: MCPToolAccess;
32
+ /** When set, an OAuth token must hold exactly this scope to see and call the tool. */
33
+ scope?: string;
29
34
  }
30
35
 
36
+ const METHOD_ACCESS: Record<MCPMethod, MCPToolAccess> = {
37
+ create: "write",
38
+ delete: "write",
39
+ list: "read",
40
+ read: "read",
41
+ update: "write",
42
+ };
43
+
31
44
  const getToolPrefix = (entry: MCPRegistryEntry): string => {
32
45
  if (entry.config.toolPrefix) {
33
46
  return entry.config.toolPrefix;
@@ -82,6 +95,7 @@ export const generateToolsForEntry = (entry: MCPRegistryEntry): MCPToolDefinitio
82
95
  const toolName = `${prefix}_${method}`;
83
96
 
84
97
  tools.push({
98
+ access: METHOD_ACCESS[method],
85
99
  description: generateToolDescription(
86
100
  entry.model,
87
101
  method,
@@ -98,6 +112,7 @@ export const generateToolsForEntry = (entry: MCPRegistryEntry): MCPToolDefinitio
98
112
  }),
99
113
  inputSchema: inputSchema as MCPToolInputSchema,
100
114
  name: toolName,
115
+ scope: entry.config.scopes?.[method],
101
116
  zodSchema,
102
117
  });
103
118
  }
@@ -120,10 +135,12 @@ export const generateAllTools = (entries: MCPRegistryEntry[]): MCPToolDefinition
120
135
  export const getAllMCPTools = (): MCPToolDefinition[] => {
121
136
  const customTools: MCPToolDefinition[] = getMCPCustomTools().map((tool) => {
122
137
  return {
138
+ access: tool.access ?? "write",
123
139
  description: tool.description,
124
140
  handler: tool.handler,
125
141
  inputSchema: toJSONSchema(tool.zodSchema) as MCPToolInputSchema,
126
142
  name: tool.name,
143
+ scope: tool.scope,
127
144
  zodSchema: tool.zodSchema,
128
145
  };
129
146
  });
package/src/mcp/types.ts CHANGED
@@ -5,6 +5,12 @@ import type {User} from "../auth";
5
5
 
6
6
  export type MCPMethod = "create" | "list" | "read" | "update" | "delete";
7
7
 
8
+ /**
9
+ * Whether a tool only reads data or can change it. Under `mcpOAuth.grants`, a `read` grant
10
+ * allows `read` tools and a `write` grant allows both.
11
+ */
12
+ export type MCPToolAccess = "read" | "write";
13
+
8
14
  /** Arguments an MCP client sends for a tool call, validated against the tool's Zod schema. */
9
15
  export type MCPToolArgs = Record<string, unknown>;
10
16
 
@@ -79,6 +85,12 @@ export interface MCPConfig {
79
85
  excludeFields?: string[];
80
86
  /** Max items returned by list tool (default: 50) */
81
87
  maxLimit?: number;
88
+ /**
89
+ * OAuth scope a token must hold to see and call a method's tool, for example
90
+ * `{delete: "todos:admin"}`. Only enforced when `mcpOAuth.grants` is set. A method without an
91
+ * explicit scope follows its access level: `list` and `read` are `read`, the rest `write`.
92
+ */
93
+ scopes?: Partial<Record<MCPMethod, string>>;
82
94
  /** MCP-specific serialization (separate from REST responseHandler) */
83
95
  mcpResponseHandler?: (value: unknown, method: MCPMethod, user?: User) => Promise<JSONValue>;
84
96
  }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Pieces of the modelRouter write contract shared by the single-document routes (`api.ts`,
3
+ * `permissions.ts`) and `POST /bulk` (`bulk.ts`), so a bulk item answers exactly as the single
4
+ * route would.
5
+ */
6
+ import {DateTime} from "luxon";
7
+
8
+ import {APIError} from "./errors";
9
+ import type {ExecutorConcurrencyCheck} from "./sync/executors";
10
+
11
+ /** The 405 every modelRouter write answers when the method permission denies the user. */
12
+ export const methodPermissionDeniedError = ({
13
+ method,
14
+ modelName,
15
+ userId,
16
+ }: {
17
+ method: string;
18
+ modelName: string;
19
+ userId?: string;
20
+ }): APIError =>
21
+ new APIError({
22
+ status: 405,
23
+ title: `Access to ${method.toUpperCase()} on ${modelName} denied for ${userId}`,
24
+ });
25
+
26
+ /**
27
+ * The last-write-wins check an update builds from the client's timestamp. The precise header wins
28
+ * over the HTTP header, which wins over the body's `_updatedAt`. None set means no check.
29
+ */
30
+ export const timestampConcurrencyCheck = ({
31
+ preciseHeader,
32
+ httpHeader,
33
+ bodyUpdatedAt,
34
+ }: {
35
+ preciseHeader?: string;
36
+ httpHeader?: string;
37
+ bodyUpdatedAt?: unknown;
38
+ }): ExecutorConcurrencyCheck | undefined => {
39
+ if (preciseHeader) {
40
+ return {
41
+ ifUnmodifiedSince: DateTime.fromISO(preciseHeader).toJSDate(),
42
+ invalidTimestampDetail: "X-Unmodified-Since-ISO header could not be parsed as an ISO date",
43
+ type: "timestamp",
44
+ };
45
+ }
46
+ if (httpHeader) {
47
+ return {
48
+ ifUnmodifiedSince: DateTime.fromHTTP(httpHeader).toJSDate(),
49
+ invalidTimestampDetail: "If-Unmodified-Since header could not be parsed as an HTTP date",
50
+ type: "timestamp",
51
+ };
52
+ }
53
+ if (!bodyUpdatedAt) {
54
+ return undefined;
55
+ }
56
+ // An unparseable value round-trips as an invalid Date; the executor turns it into the 400
57
+ // "Invalid conflict-detection timestamp" error after preUpdate has run.
58
+ return {
59
+ ifUnmodifiedSince: DateTime.fromISO(String(bodyUpdatedAt)).toJSDate(),
60
+ invalidTimestampDetail: "_updatedAt body field could not be parsed as an ISO date",
61
+ type: "timestamp",
62
+ };
63
+ };
64
+
65
+ /** The 409 body an update returns when the document changed since the client read it. */
66
+ export const conflictResponseBody = (
67
+ data: unknown
68
+ ): {data: unknown; error: string; message: string} => ({
69
+ data,
70
+ error: "Conflict",
71
+ message: "Document was modified since your last read",
72
+ });
package/src/openApi.ts CHANGED
@@ -15,7 +15,7 @@ const m2sOptions = {
15
15
  props: ["readOnly", "required", "enum", "default"],
16
16
  };
17
17
 
18
- const apiErrorContent = {
18
+ export const apiErrorContent = {
19
19
  "application/json": {
20
20
  schema: {$ref: "#/components/schemas/APIError"},
21
21
  },
@@ -6,6 +6,7 @@ import type {ModelRouterOptions, RESTMethod} from "./api";
6
6
  import type {User} from "./auth";
7
7
  import {loadDocOr404} from "./docLoader";
8
8
  import {APIError} from "./errors";
9
+ import {methodPermissionDeniedError} from "./modelRouterWrites";
9
10
  import {isOrgMemberPermission, OrgQueryFilter} from "./orgs/orgPermissions";
10
11
  import {getCurrentRequestContext} from "./requestContext";
11
12
 
@@ -177,11 +178,10 @@ export const permissionMiddleware = <T>(
177
178
  // All methods check for permissions.
178
179
  const methodPermissions = options.permissions?.[method] ?? [];
179
180
  if (!(await checkPermissions(method, methodPermissions, req.user))) {
180
- throw new APIError({
181
- status: 405,
182
- title:
183
- `Access to ${method.toUpperCase()} on ${model.modelName} ` +
184
- `denied for ${req.user?.id}`,
181
+ throw methodPermissionDeniedError({
182
+ method,
183
+ modelName: model.modelName,
184
+ userId: req.user?.id,
185
185
  });
186
186
  }
187
187
 
@@ -6,7 +6,7 @@ import {createIsPermitted, createRequireAccess} from "./middleware";
6
6
  import {createPermissionResolver} from "./resolve";
7
7
  import {createRoleManager} from "./roleManager";
8
8
  import {createRbacRoleModel, organizationOperatorRole} from "./roleModel";
9
- import {mergeStatements, type Statements} from "./statements";
9
+ import {mergeStatementDescriptions, mergeStatements, type Statements} from "./statements";
10
10
  import type {
11
11
  AccessCheckArgs,
12
12
  AccessOptions,
@@ -39,6 +39,7 @@ export const createAccess = <S extends Statements>(options: AccessOptions<S>): T
39
39
  }
40
40
 
41
41
  const mergedStatements = mergeStatements(options.statements) as S;
42
+ const statementDescriptions = mergeStatementDescriptions(options.statementDescriptions);
42
43
  const rbacRoleModel = createRbacRoleModel(options.connection);
43
44
  const extraRoles = [...(options.defaultRoles ?? [])];
44
45
  if (options.organizations && !extraRoles.some((role) => role.name === "operator")) {
@@ -211,6 +212,7 @@ export const createAccess = <S extends Statements>(options: AccessOptions<S>): T
211
212
  permission: createIsPermitted({can}),
212
213
  queryFilter,
213
214
  roles: roleManager,
215
+ statementDescriptions,
214
216
  statements: mergedStatements,
215
217
  userModel: options.userModel,
216
218
  };