@mastra/server-adapters-test-suite 0.3.0-alpha.4 → 0.3.0-alpha.5

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.
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { ErrorCategory, ErrorDomain, MastraError } from "@mastra/core/error";
2
- import { registerApiRoute } from "@mastra/core/server";
2
+ import { CompositeAuth, SimpleAuth, registerApiRoute } from "@mastra/core/server";
3
3
  import { handleError } from "@mastra/server/handlers/error";
4
- import { HTTPException, KNOWLEDGE_ROUTES, MASTRA_KNOWLEDGE_PRINCIPALS_KEY, SERVER_ROUTES, WorkflowRegistry, createRoute, serializeStreamChunk } from "@mastra/server/server-adapter";
4
+ import { HTTPException, KNOWLEDGE_ROUTES, MASTRA_KNOWLEDGE_PRINCIPALS_KEY, SERVER_ROUTES, WorkflowRegistry, createRoute, dispatchRoute, serializeStreamChunk } from "@mastra/server/server-adapter";
5
5
  import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
6
6
  import * as zod from "zod";
7
7
  import { z } from "zod";
@@ -17,7 +17,7 @@ import { createScorer } from "@mastra/core/evals";
17
17
  import { LogLevel } from "@mastra/core/logger";
18
18
  import { MockMemory } from "@mastra/core/memory";
19
19
  import { SpanType } from "@mastra/core/observability";
20
- import { EntityType, InMemoryStore } from "@mastra/core/storage";
20
+ import { EntityType, InMemoryStore, MastraCompositeStore } from "@mastra/core/storage";
21
21
  import { UnknownToolProviderError } from "@mastra/core/tool-provider";
22
22
  import { createTool, isValidationError } from "@mastra/core/tools";
23
23
  import { MastraVector } from "@mastra/core/vector";
@@ -32,11 +32,15 @@ import { MCPServerBase } from "@mastra/core/mcp";
32
32
  import { RequestContext } from "@mastra/core/request-context";
33
33
  import { standardSchemaToJSONSchema } from "@mastra/core/schema";
34
34
  import { z as z$2 } from "zod/v4";
35
+ import { DEFAULT_ROLES, FGADeniedError, StaticRBACProvider } from "@mastra/core/auth/ee";
36
+ import { MastraLanguageModelV2Mock, createMockModel } from "@mastra/core/test-utils/llm-mock";
37
+ import { MastraJwtAuth } from "@mastra/auth";
38
+ import { SignJWT, exportJWK, generateKeyPair } from "jose";
39
+ import { setFlagsFromString } from "v8";
40
+ import { runInNewContext } from "vm";
35
41
  import { Knowledge } from "@mastra/core/knowledge";
36
42
  import { once } from "events";
37
43
  import { DefaultObservabilityInstance, MastraPlatformExporter, MastraStorageExporter, Observability } from "@mastra/observability";
38
- import { setFlagsFromString } from "v8";
39
- import { runInNewContext } from "vm";
40
44
  // src/route-test-utils.ts
41
45
  /**
42
46
  * Normalizes a route path to ensure consistent formatting.
@@ -79,6 +83,7 @@ function getRouteSpecificSchemaDefaults(route) {
79
83
  path: "entityName"
80
84
  } };
81
85
  if (route.path === "/agent-controller/:controllerId/sessions" && route.method === "POST") return { body: { resourceId: "test-resource" } };
86
+ if (route.path === "/schedules" && route.method === "POST") return { body: { cron: "* * * * *" } };
82
87
  if (route.path === "/mcp/:serverId/events/:eventName/emit") return { body: { data: { id: "test-ticket" } } };
83
88
  if (route.path === "/datasets/:datasetId/compare") return { body: {
84
89
  experimentIds: ["test-experiment-a", "test-experiment-b"],
@@ -5141,6 +5146,15 @@ function createMCPTransportTestSuite(config) {
5141
5146
  return { aborted: !!signal?.aborted };
5142
5147
  }
5143
5148
  });
5149
+ const createWhoamiTool = () => createTool({
5150
+ id: "whoami",
5151
+ description: "Returns the caller as seen by the tool",
5152
+ inputSchema: z.object({}),
5153
+ execute: async (_input, context) => ({
5154
+ authInfo: context?.mcp?.extra?.authInfo ?? null,
5155
+ user: context?.requestContext?.get("user") ?? null
5156
+ })
5157
+ });
5144
5158
  let httpServer;
5145
5159
  let port;
5146
5160
  let mcpServer1;
@@ -5155,7 +5169,8 @@ function createMCPTransportTestSuite(config) {
5155
5169
  description: "Test MCP Server 1",
5156
5170
  tools: {
5157
5171
  getWeather: weatherTool,
5158
- calculate: calculatorTool
5172
+ calculate: calculatorTool,
5173
+ whoami: createWhoamiTool()
5159
5174
  }
5160
5175
  });
5161
5176
  mcpServer2 = new MCPServer({
@@ -5318,6 +5333,138 @@ function createMCPTransportTestSuite(config) {
5318
5333
  const server2Tools = Object.keys(tools).filter((k) => k.startsWith("server2_"));
5319
5334
  expect(server2Tools).toHaveLength(0);
5320
5335
  });
5336
+ it("gives tools no caller identity when the server has no auth configured", async () => {
5337
+ const result = await (await mcpClient.listTools())["server1_whoami"].execute({}, {});
5338
+ expectTextToolResult(result, {
5339
+ authInfo: null,
5340
+ user: null
5341
+ });
5342
+ });
5343
+ });
5344
+ describe("Authenticated MCP callers", () => {
5345
+ const users = {
5346
+ "alice-token": {
5347
+ id: "alice",
5348
+ name: "Alice"
5349
+ },
5350
+ "bob-token": {
5351
+ id: "bob",
5352
+ name: "Bob"
5353
+ }
5354
+ };
5355
+ const startAuthenticatedApp = async (mcpOptions) => {
5356
+ const whoamiServer = new MCPServer({
5357
+ name: "whoami-server",
5358
+ version: "1.0.0",
5359
+ tools: { whoami: createWhoamiTool() },
5360
+ mapAuthInfoToUser: ({ authInfo }) => authInfo.extra?.user
5361
+ });
5362
+ const authMastra = new Mastra$1({
5363
+ logger: false,
5364
+ mcpServers: { whoami: whoamiServer },
5365
+ server: {
5366
+ auth: new SimpleAuth({ tokens: users }),
5367
+ ...mcpOptions ? { mcpOptions } : {}
5368
+ }
5369
+ });
5370
+ const { server, port: authPort } = await createServer(authMastra);
5371
+ const url = new URL(`http://localhost:${authPort}/api/mcp/${whoamiServer.id}/mcp`);
5372
+ const clients = [];
5373
+ const callWhoami = async (token) => {
5374
+ const client = new MCPClient({
5375
+ id: `whoami-${token}-${authPort}`,
5376
+ servers: { app: {
5377
+ url,
5378
+ requestInit: { headers: { Authorization: `Bearer ${token}` } }
5379
+ } }
5380
+ });
5381
+ clients.push(client);
5382
+ const result = await (await client.listTools())["app_whoami"].execute({}, {});
5383
+ return JSON.parse(result.content[0].text);
5384
+ };
5385
+ const close = async () => {
5386
+ await Promise.all(clients.map((client) => client.disconnect()));
5387
+ await new Promise((resolve) => server.close(() => resolve()));
5388
+ await whoamiServer.close();
5389
+ };
5390
+ return {
5391
+ callWhoami,
5392
+ close
5393
+ };
5394
+ };
5395
+ it("lets an MCP tool see the user who authenticated with the server", async () => {
5396
+ const app = await startAuthenticatedApp();
5397
+ try {
5398
+ expect(await app.callWhoami("alice-token")).toEqual({
5399
+ authInfo: {
5400
+ token: "alice-token",
5401
+ clientId: "alice",
5402
+ scopes: [],
5403
+ extra: { user: {
5404
+ id: "alice",
5405
+ name: "Alice"
5406
+ } }
5407
+ },
5408
+ user: {
5409
+ id: "alice",
5410
+ name: "Alice"
5411
+ }
5412
+ });
5413
+ expect(await app.callWhoami("bob-token")).toMatchObject({
5414
+ authInfo: {
5415
+ token: "bob-token",
5416
+ clientId: "bob"
5417
+ },
5418
+ user: {
5419
+ id: "bob",
5420
+ name: "Bob"
5421
+ }
5422
+ });
5423
+ } finally {
5424
+ await app.close();
5425
+ }
5426
+ }, 3e4);
5427
+ it("keeps the authenticated caller in serverless mode", async () => {
5428
+ const app = await startAuthenticatedApp({ serverless: true });
5429
+ try {
5430
+ expect(await app.callWhoami("alice-token")).toMatchObject({
5431
+ authInfo: {
5432
+ token: "alice-token",
5433
+ clientId: "alice"
5434
+ },
5435
+ user: {
5436
+ id: "alice",
5437
+ name: "Alice"
5438
+ }
5439
+ });
5440
+ } finally {
5441
+ await app.close();
5442
+ }
5443
+ }, 3e4);
5444
+ it("lets a setRequestAuth hook in the Mastra server config decide what the MCP tool sees", async () => {
5445
+ const app = await startAuthenticatedApp({ setRequestAuth: (req, requestContext) => {
5446
+ const user = requestContext.get("mastra__user");
5447
+ req.auth = {
5448
+ token: "",
5449
+ clientId: `custom:${user.id}`,
5450
+ scopes: ["mcp:custom"],
5451
+ extra: { user: { id: user.id } }
5452
+ };
5453
+ } });
5454
+ try {
5455
+ expect(await app.callWhoami("alice-token")).toEqual({
5456
+ authInfo: {
5457
+ token: "",
5458
+ clientId: "custom:alice",
5459
+ scopes: ["mcp:custom"],
5460
+ extra: { user: { id: "alice" } }
5461
+ },
5462
+ user: { id: "alice" }
5463
+ });
5464
+ } finally {
5465
+ await app.close();
5466
+ }
5467
+ }, 3e4);
5321
5468
  });
5322
5469
  describe("Tool execution errors (MCPClient)", () => {
5323
5470
  let failingClient;
@@ -6536,153 +6683,3278 @@ function createCustomRouteFGATestSuite(config) {
6536
6683
  });
6537
6684
  });
6538
6685
  }
6539
- // src/knowledge-routes-test-suite.ts
6686
+ // src/route-dispatch-parity-test-suite.ts
6540
6687
  /**
6541
- * The opt-in Knowledge routes on every adapter: RBAC `knowledge:read` gates them, the Knowledge principals
6542
- * `authorize` sets through `context.get('requestContext')` reach the handler (no mapping is refused), and a
6543
- * repeated query param (`scopeId`) arrives as a list.
6688
+ * The route standing in for an in-process caller such as the `/api/mcp` server: it is authenticated
6689
+ * by the adapter like any custom route, then runs `run` with the server context the adapter gave it.
6544
6690
  */
6545
- function createKnowledgeRoutesTestSuite(config) {
6546
- const { suiteName = "Knowledge routes", startServer } = config;
6691
+ function createProbe(style, run) {
6692
+ if (style === "hono") return registerApiRoute("/__dispatch", {
6693
+ method: "ALL",
6694
+ handler: async (c) => c.json(await run(c.req.query(), {
6695
+ mastra: c.get("mastra"),
6696
+ requestContext: c.get("requestContext"),
6697
+ abortSignal: c.req.raw.signal,
6698
+ request: c.req.raw
6699
+ }))
6700
+ });
6701
+ return createRoute({
6702
+ method: "ALL",
6703
+ path: "/__dispatch",
6704
+ responseType: "json",
6705
+ queryParamSchema: z$2.object({
6706
+ case: z$2.string(),
6707
+ prefix: z$2.string().optional()
6708
+ }),
6709
+ handler: async ({ case: caseId, prefix, mastra, requestContext, abortSignal, registeredTools, taskStore, request }) => run({
6710
+ case: caseId,
6711
+ ...prefix === void 0 ? {} : { prefix }
6712
+ }, {
6713
+ mastra,
6714
+ requestContext,
6715
+ abortSignal,
6716
+ registeredTools,
6717
+ taskStore,
6718
+ request
6719
+ })
6720
+ });
6721
+ }
6722
+ const USERS$2 = {
6723
+ "owner-token": {
6724
+ id: "user-owner",
6725
+ role: "owner",
6726
+ studioRole: "owner"
6727
+ },
6728
+ "member-token": {
6729
+ id: "user-member",
6730
+ role: "member",
6731
+ studioRole: "member"
6732
+ },
6733
+ "member2-token": {
6734
+ id: "user-member2",
6735
+ role: "member",
6736
+ studioRole: "member"
6737
+ },
6738
+ "viewer-token": {
6739
+ id: "user-viewer",
6740
+ role: "viewer",
6741
+ studioRole: "member"
6742
+ }
6743
+ };
6744
+ /** `type:id` → user ids granted any permission on that resource (`*` = every user). */
6745
+ const FGA_GRANTS$1 = {
6746
+ "agent:test-agent": ["*"],
6747
+ "agent:locked-agent": ["user-owner"],
6748
+ "workflow:test-workflow": ["*"],
6749
+ "workflow:locked-workflow": ["user-owner"],
6750
+ "tool:test-tool": ["*"],
6751
+ "tool:locked-tool": ["user-owner"]
6752
+ };
6753
+ /**
6754
+ * In-memory relationship store standing in for an external FGA service (WorkOS, OpenFGA, ...).
6755
+ * Threads are granted to everyone so that thread ownership is decided by the handlers.
6756
+ */
6757
+ var TupleFGAProvider$1 = class {
6758
+ async check(user, { resource }) {
6759
+ if (resource.type === "thread") return true;
6760
+ const grantees = FGA_GRANTS$1[`${resource.type}:${resource.id}`] ?? [];
6761
+ return grantees.includes("*") || grantees.includes(user.id);
6762
+ }
6763
+ async require(user, params) {
6764
+ if (!await this.check(user, params)) throw new FGADeniedError(user, params.resource, params.permission);
6765
+ }
6766
+ async filterAccessible(user, resources, resourceType) {
6767
+ const allowed = [];
6768
+ for (const resource of resources) if (await this.check(user, { resource: {
6769
+ type: resourceType,
6770
+ id: resource.id
6771
+ } })) allowed.push(resource);
6772
+ return allowed;
6773
+ }
6774
+ };
6775
+ function findRoute(method, path) {
6776
+ const route = SERVER_ROUTES.find((r) => r.method === method && r.path === path);
6777
+ if (!route) throw new Error(`No server route ${method} ${path}`);
6778
+ return route;
6779
+ }
6780
+ function createParityMastra$1(probeCases, probeStyle) {
6781
+ const memory = new MockMemory({ storage: new InMemoryStore() });
6782
+ const makeAgent = (id) => new Agent({
6783
+ id,
6784
+ name: id,
6785
+ instructions: "You are a test agent",
6786
+ model: createMockModel({ mockText: `hello from ${id}` }),
6787
+ memory
6788
+ });
6789
+ const approvalStep = createStep({
6790
+ id: "approval",
6791
+ inputSchema: z$2.object({ value: z$2.string() }),
6792
+ outputSchema: z$2.object({ approved: z$2.boolean() }),
6793
+ resumeSchema: z$2.object({ approved: z$2.boolean() }),
6794
+ execute: async ({ resumeData, suspend }) => {
6795
+ if (!resumeData) return suspend({ reason: "needs approval" });
6796
+ return { approved: resumeData.approved };
6797
+ }
6798
+ });
6799
+ const makeWorkflow = (id) => createWorkflow({
6800
+ id,
6801
+ inputSchema: z$2.object({ value: z$2.string() }),
6802
+ outputSchema: z$2.object({ approved: z$2.boolean() })
6803
+ }).then(approvalStep).commit();
6804
+ const makeTool = (id) => createTool({
6805
+ id,
6806
+ description: "Echoes its input",
6807
+ inputSchema: z$2.object({ text: z$2.string() }),
6808
+ execute: async ({ text }) => ({ echoed: text })
6809
+ });
6810
+ const probe = createProbe(probeStyle, async ({ case: caseId }, context) => {
6811
+ const probeCase = probeCases.get(caseId);
6812
+ return dispatchRoute(probeCase.route, probeCase.input, {
6813
+ ...context,
6814
+ routePrefix: "/api"
6815
+ });
6816
+ });
6817
+ const tokens = Object.fromEntries(Object.entries(USERS$2));
6818
+ return {
6819
+ mastra: new Mastra$1({
6820
+ logger: false,
6821
+ storage: new InMemoryStore(),
6822
+ agents: {
6823
+ "test-agent": makeAgent("test-agent"),
6824
+ "locked-agent": makeAgent("locked-agent")
6825
+ },
6826
+ workflows: {
6827
+ "test-workflow": makeWorkflow("test-workflow"),
6828
+ "locked-workflow": makeWorkflow("locked-workflow")
6829
+ },
6830
+ tools: {
6831
+ "test-tool": makeTool("test-tool"),
6832
+ "locked-tool": makeTool("locked-tool")
6833
+ },
6834
+ server: {
6835
+ auth: new SimpleAuth({
6836
+ tokens,
6837
+ mapUserToResourceId: (user) => user.id
6838
+ }),
6839
+ rbac: new StaticRBACProvider({
6840
+ roles: DEFAULT_ROLES,
6841
+ getUserRoles: (user) => [user.role]
6842
+ }),
6843
+ fga: new TupleFGAProvider$1(),
6844
+ apiRoutes: [probe]
6845
+ },
6846
+ studio: {
6847
+ auth: new SimpleAuth({
6848
+ tokens,
6849
+ mapUserToResourceId: (user) => user.id
6850
+ }),
6851
+ rbac: new StaticRBACProvider({
6852
+ roles: DEFAULT_ROLES,
6853
+ getUserRoles: (user) => [user.studioRole]
6854
+ })
6855
+ }
6856
+ }),
6857
+ memory
6858
+ };
6859
+ }
6860
+ /**
6861
+ * `dispatchRoute` is how in-process callers (the upcoming `/api/mcp` server) invoke server routes.
6862
+ * It must allow and deny exactly what a real HTTP request to the same route allows and denies,
6863
+ * for the same authenticated user: RBAC (server and Studio providers), FGA, schema validation
6864
+ * and handler-level ownership checks.
6865
+ */
6866
+ function createRouteDispatchParityTestSuite(config) {
6867
+ const { suiteName = "Route dispatch parity", startServer, probe: probeStyle = "schema", sameErrorBodies = true } = config;
6547
6868
  describe(suiteName, () => {
6548
- let close;
6549
- afterEach(async () => {
6550
- await close?.();
6551
- close = void 0;
6869
+ const probeCases = /* @__PURE__ */ new Map();
6870
+ let server;
6871
+ let memory;
6872
+ beforeAll(async () => {
6873
+ const setup = createParityMastra$1(probeCases, probeStyle);
6874
+ memory = setup.memory;
6875
+ server = await startServer(setup.mastra);
6552
6876
  });
6553
- const setup = async () => {
6554
- const knowledge = new Knowledge({
6555
- id: "kb",
6556
- scopes: {},
6557
- storage: new InMemoryStore({ id: "kb" })
6877
+ afterAll(async () => {
6878
+ await server?.close?.();
6879
+ });
6880
+ const headersFor = (req) => ({
6881
+ authorization: `Bearer ${req.token}`,
6882
+ ...req.studio ? { "x-mastra-client-type": "studio" } : {}
6883
+ });
6884
+ const viaHttp = async (req) => {
6885
+ let path = req.path;
6886
+ for (const [key, value] of Object.entries(req.pathParams ?? {})) path = path.replace(`:${key}`, encodeURIComponent(value));
6887
+ const query = new URLSearchParams(req.query ?? {}).toString();
6888
+ const hasBody = req.body !== void 0;
6889
+ const response = await server.request(`/api${path}${query ? `?${query}` : ""}`, {
6890
+ method: req.method,
6891
+ headers: {
6892
+ ...headersFor(req),
6893
+ ...hasBody ? { "content-type": "application/json" } : {}
6894
+ },
6895
+ ...hasBody ? { body: JSON.stringify(req.body) } : {}
6558
6896
  });
6559
- const store = await knowledge.getStorage();
6560
- const provenance = { author: "test" };
6561
- const scopes = {};
6562
- for (const [team, page] of [
6563
- ["support", "Payments runbook"],
6564
- ["eng", "Payments service"],
6565
- ["sales", "Payments pricing"]
6566
- ]) {
6567
- const { scope } = await store.materializeScope({
6568
- address: `team:${team}`,
6569
- declaration: "team:$teamId",
6570
- name: team,
6571
- provenance
6572
- });
6573
- scopes[team] = scope.id;
6574
- await store.createPage({
6575
- parentId: scope.id,
6576
- name: page,
6577
- provenance
6578
- });
6579
- }
6580
- const permissions = {
6581
- "reader-token": ["knowledge:read"],
6582
- "unmapped-token": ["knowledge:read"],
6583
- "other-token": []
6897
+ const text = await response.text();
6898
+ return {
6899
+ status: response.status,
6900
+ body: text ? JSON.parse(text) : void 0
6584
6901
  };
6585
- const mastra = new Mastra({
6586
- logger: false,
6587
- knowledge: { main: knowledge },
6588
- server: { apiRoutes: [...KNOWLEDGE_ROUTES] }
6589
- });
6590
- const originalGetServer = mastra.getServer.bind(mastra);
6591
- mastra.getServer = () => ({
6592
- ...originalGetServer(),
6593
- rbac: {
6594
- getRoles: async () => ["member"],
6595
- getPermissions: async (user) => permissions[user.id] ?? []
6596
- },
6597
- auth: {
6598
- authenticateToken: async (token) => token in permissions ? { id: token } : null,
6599
- authorize: async (_path, _method, user, context) => {
6600
- if (user.id === "reader-token") context.get("requestContext").set(MASTRA_KNOWLEDGE_PRINCIPALS_KEY, "all");
6601
- return true;
6602
- }
6902
+ };
6903
+ const viaDispatch = async (req) => {
6904
+ const caseId = String(probeCases.size);
6905
+ probeCases.set(caseId, {
6906
+ route: findRoute(req.method, req.path),
6907
+ input: {
6908
+ pathParams: req.pathParams,
6909
+ query: req.query,
6910
+ body: req.body
6603
6911
  }
6604
6912
  });
6605
- const server = await startServer(mastra);
6606
- close = server.close;
6607
- const get = (path, token) => server.request(`/api/knowledge/main${path}`, token ? { headers: { authorization: `Bearer ${token}` } } : {});
6913
+ const response = await server.request(`/__dispatch?case=${caseId}`, { headers: headersFor(req) });
6914
+ expect(response.status).toBe(200);
6915
+ const outcome = await response.json();
6916
+ return outcome.ok ? {
6917
+ status: 200,
6918
+ body: outcome.result
6919
+ } : {
6920
+ status: outcome.status,
6921
+ body: outcome.body
6922
+ };
6923
+ };
6924
+ /** Sends the request both ways and asserts the same status (and same body on errors). */
6925
+ const expectParity = async (req, expectedStatus) => {
6926
+ const http = await viaHttp(req);
6927
+ const dispatched = await viaDispatch(req);
6928
+ expect(http.status, JSON.stringify(http.body)).toBe(expectedStatus);
6929
+ expect(dispatched.status).toBe(http.status);
6930
+ if (expectedStatus >= 400 && sameErrorBodies) expect(dispatched.body).toEqual(http.body);
6608
6931
  return {
6609
- get,
6610
- scopes
6932
+ http: http.body,
6933
+ dispatched: dispatched.body
6611
6934
  };
6612
6935
  };
6613
- it("serves a reader authorize mapped to Knowledge principals and refuses everyone else", async () => {
6614
- const { get } = await setup();
6615
- const roots = await get("/tree", "reader-token");
6616
- expect(roots.status).toBe(200);
6617
- const body = await roots.json();
6618
- expect(body.pages.map((page) => page.name).sort()).toEqual([
6619
- "eng",
6620
- "sales",
6621
- "support"
6622
- ]);
6623
- expect((await get("/tree", "unmapped-token")).status).toBe(403);
6624
- expect((await get("/tree", "other-token")).status).toBe(403);
6625
- expect((await get("/tree")).status).toBe(401);
6936
+ let threadCounter = 0;
6937
+ const generate = (token, agentId, body = {
6938
+ messages: "hi",
6939
+ memory: { thread: `generate-thread-${++threadCounter}` }
6940
+ }) => ({
6941
+ token,
6942
+ method: "POST",
6943
+ path: "/agents/:agentId/generate",
6944
+ pathParams: { agentId },
6945
+ body
6626
6946
  });
6627
- it("reads a repeated scopeId param as a list", async () => {
6628
- const { get, scopes } = await setup();
6629
- const res = await get(`/search?q=payments&scopeId=${scopes.support}&scopeId=${scopes.eng}`, "reader-token");
6630
- expect(res.status).toBe(200);
6631
- const body = await res.json();
6632
- expect(body.results.map((hit) => hit.page.name).sort()).toEqual(["Payments runbook", "Payments service"]);
6947
+ describe("agents", () => {
6948
+ it("denies generate without agents:execute (RBAC)", async () => {
6949
+ const { dispatched } = await expectParity(generate("viewer-token", "test-agent"), 403);
6950
+ expect(dispatched.message).toBe("Missing required permission: agents:execute");
6951
+ });
6952
+ it("allows generate for a member and returns the same text", async () => {
6953
+ const { http, dispatched } = await expectParity(generate("member-token", "test-agent"), 200);
6954
+ expect(http.text).toBe("hello from test-agent");
6955
+ expect(dispatched.text).toBe(http.text);
6956
+ });
6957
+ it("denies generate on an agent the FGA provider does not grant", async () => {
6958
+ const { dispatched } = await expectParity(generate("member-token", "locked-agent"), 403);
6959
+ expect(dispatched.message).toContain("FGA authorization denied");
6960
+ });
6961
+ it("allows the FGA-granted owner on the locked agent", async () => {
6962
+ await expectParity(generate("owner-token", "locked-agent"), 200);
6963
+ });
6964
+ it("rejects an invalid body with the same validation error", async () => {
6965
+ const { http } = await expectParity(generate("member-token", "test-agent", { messages: 42 }), 400);
6966
+ expect(http.error).toBeDefined();
6967
+ });
6968
+ it("uses the Studio RBAC provider for Studio requests", async () => {
6969
+ await expectParity(generate("viewer-token", "test-agent"), 403);
6970
+ await expectParity({
6971
+ ...generate("viewer-token", "test-agent"),
6972
+ studio: true
6973
+ }, 200);
6974
+ });
6975
+ it("applies read permissions and FGA to agent reads", async () => {
6976
+ await expectParity({
6977
+ token: "viewer-token",
6978
+ method: "GET",
6979
+ path: "/agents"
6980
+ }, 200);
6981
+ const read = (agentId) => ({
6982
+ token: "viewer-token",
6983
+ method: "GET",
6984
+ path: "/agents/:agentId",
6985
+ pathParams: { agentId }
6986
+ });
6987
+ await expectParity(read("test-agent"), 200);
6988
+ await expectParity(read("locked-agent"), 403);
6989
+ });
6633
6990
  });
6634
- });
6635
- }
6636
- // src/observability-signal-write-test-suite.ts
6637
- /** Shared HTTP contract for feedback/score writes, backed by real in-memory storage. */
6638
- function createObservabilitySignalWriteTestSuite({ startServer }) {
6639
- describe.each(["feedback", "scores"])("%s HTTP writes", (collection) => {
6640
- let server;
6641
- let store;
6642
- let trustedScope;
6643
- let allowAccess;
6644
- let authorLookupFails;
6645
- const isFeedback = collection === "feedback";
6646
- const field = isFeedback ? "feedback" : "score";
6647
- const idField = isFeedback ? "feedbackId" : "scoreId";
6648
- const payload = isFeedback ? {
6649
- feedbackType: "thumbs",
6650
- value: 1
6651
- } : {
6652
- scorerId: "accuracy",
6653
- score: .9
6654
- };
6655
- const path = `/api/observability/${collection}`;
6656
- beforeEach(async () => {
6657
- trustedScope = {};
6658
- allowAccess = true;
6659
- authorLookupFails = false;
6660
- const storage = new InMemoryStore();
6661
- store = await storage.getStore("observability");
6662
- server = await startServer(new Mastra({
6663
- storage,
6664
- logger: false,
6665
- server: { auth: {
6666
- authenticateToken: async () => ({}),
6667
- getCurrentUser: async () => null,
6668
- getUser: async (id) => {
6669
- if (authorLookupFails) throw new Error("Directory unavailable");
6670
- return id === "author-1" ? {
6671
- id,
6672
- name: "Alice",
6673
- email: "alice@example.com",
6674
- secret: "private"
6675
- } : null;
6676
- },
6677
- authorize: async (_path, _method, _user, c) => {
6678
- for (const [key, value] of Object.entries(trustedScope)) c.get("requestContext").set(key, value);
6679
- return allowAccess;
6991
+ describe("workflows", () => {
6992
+ const start = (token, workflowId = "test-workflow") => ({
6993
+ token,
6994
+ method: "POST",
6995
+ path: "/workflows/:workflowId/start-async",
6996
+ pathParams: { workflowId },
6997
+ body: { inputData: { value: "x" } }
6998
+ });
6999
+ const startRun = async (token = "member-token") => {
7000
+ const created = await viaHttp({
7001
+ token,
7002
+ method: "POST",
7003
+ path: "/workflows/:workflowId/create-run",
7004
+ pathParams: { workflowId: "test-workflow" }
7005
+ });
7006
+ expect(created.status).toBe(200);
7007
+ const runId = created.body.runId;
7008
+ const started = await viaHttp({
7009
+ ...start(token),
7010
+ query: { runId }
7011
+ });
7012
+ expect(started.body.status).toBe("suspended");
7013
+ return runId;
7014
+ };
7015
+ it("denies start without workflows:execute", async () => {
7016
+ await expectParity(start("viewer-token"), 403);
7017
+ });
7018
+ it("starts the workflow for a member and suspends both ways", async () => {
7019
+ const { http, dispatched } = await expectParity(start("member-token"), 200);
7020
+ expect(http.status).toBe("suspended");
7021
+ expect(dispatched.status).toBe("suspended");
7022
+ });
7023
+ it("denies start on a workflow the FGA provider does not grant", async () => {
7024
+ await expectParity(start("member-token", "locked-workflow"), 403);
7025
+ });
7026
+ it("resumes a suspended run for a member and denies a viewer", async () => {
7027
+ const resume = (token, runId) => ({
7028
+ token,
7029
+ method: "POST",
7030
+ path: "/workflows/:workflowId/resume-async",
7031
+ pathParams: { workflowId: "test-workflow" },
7032
+ query: { runId },
7033
+ body: {
7034
+ step: "approval",
7035
+ resumeData: { approved: true }
6680
7036
  }
6681
- } }
6682
- }));
7037
+ });
7038
+ const runA = await startRun();
7039
+ const runB = await startRun();
7040
+ const viaHttpResult = await viaHttp(resume("member-token", runA));
7041
+ const viaDispatchResult = await viaDispatch(resume("member-token", runB));
7042
+ expect(viaHttpResult.status).toBe(200);
7043
+ expect(viaDispatchResult.status).toBe(200);
7044
+ expect(viaHttpResult.body.status).toBe("success");
7045
+ expect(viaDispatchResult.body.status).toBe("success");
7046
+ expect(viaDispatchResult.body.result).toEqual(viaHttpResult.body.result);
7047
+ const runC = await startRun();
7048
+ await expectParity(resume("viewer-token", runC), 403);
7049
+ });
7050
+ it("lists runs for a viewer and denies FGA-ungranted workflows", async () => {
7051
+ const runs = (workflowId) => ({
7052
+ token: "viewer-token",
7053
+ method: "GET",
7054
+ path: "/workflows/:workflowId/runs",
7055
+ pathParams: { workflowId }
7056
+ });
7057
+ await expectParity(runs("test-workflow"), 200);
7058
+ await expectParity(runs("locked-workflow"), 403);
7059
+ });
7060
+ it("cancels for a member and denies a viewer", async () => {
7061
+ const cancel = (token, runId) => ({
7062
+ token,
7063
+ method: "POST",
7064
+ path: "/workflows/:workflowId/runs/:runId/cancel",
7065
+ pathParams: {
7066
+ workflowId: "test-workflow",
7067
+ runId
7068
+ }
7069
+ });
7070
+ const runId = await startRun();
7071
+ await expectParity(cancel("viewer-token", runId), 403);
7072
+ const runA = await startRun();
7073
+ const runB = await startRun();
7074
+ const httpCancel = await viaHttp(cancel("member-token", runA));
7075
+ const dispatchedCancel = await viaDispatch(cancel("member-token", runB));
7076
+ expect(httpCancel.status).toBe(200);
7077
+ expect(dispatchedCancel).toEqual(httpCancel);
7078
+ });
6683
7079
  });
6684
- afterEach(async () => {
6685
- await server?.close();
7080
+ describe("tools", () => {
7081
+ const execute = (token, toolId = "test-tool") => ({
7082
+ token,
7083
+ method: "POST",
7084
+ path: "/tools/:toolId/execute",
7085
+ pathParams: { toolId },
7086
+ body: { data: { text: "ping" } }
7087
+ });
7088
+ it("denies execute without tools:execute", async () => {
7089
+ await expectParity(execute("viewer-token"), 403);
7090
+ });
7091
+ it("executes for a member with the same result", async () => {
7092
+ const { http, dispatched } = await expectParity(execute("member-token"), 200);
7093
+ expect(http).toEqual({ echoed: "ping" });
7094
+ expect(dispatched).toEqual(http);
7095
+ });
7096
+ it("denies execute on a tool the FGA provider does not grant", async () => {
7097
+ await expectParity(execute("member-token", "locked-tool"), 403);
7098
+ });
7099
+ });
7100
+ describe("thread ownership", () => {
7101
+ it("lets the owner read their thread and denies another user's read", async () => {
7102
+ await memory.saveThread({ thread: {
7103
+ id: "thread-of-member",
7104
+ resourceId: "user-member",
7105
+ title: "private",
7106
+ metadata: {},
7107
+ createdAt: /* @__PURE__ */ new Date(),
7108
+ updatedAt: /* @__PURE__ */ new Date()
7109
+ } });
7110
+ const read = (token) => ({
7111
+ token,
7112
+ method: "GET",
7113
+ path: "/memory/threads/:threadId",
7114
+ pathParams: { threadId: "thread-of-member" },
7115
+ query: { agentId: "test-agent" }
7116
+ });
7117
+ const { http, dispatched } = await expectParity(read("member-token"), 200);
7118
+ expect(http.id).toBe("thread-of-member");
7119
+ expect(dispatched.id).toBe("thread-of-member");
7120
+ await expectParity(read("member2-token"), 403);
7121
+ });
7122
+ });
7123
+ describe("path params", () => {
7124
+ it("authorizes and runs the agent named in the path, not a same-named body field", async () => {
7125
+ const denied = await viaDispatch(generate("member-token", "locked-agent", {
7126
+ messages: "hi",
7127
+ agentId: "test-agent",
7128
+ memory: { thread: `generate-thread-${++threadCounter}` }
7129
+ }));
7130
+ expect(denied.status).toBe(403);
7131
+ expect(denied.body.message).toContain("agent:locked-agent");
7132
+ const allowed = await viaDispatch({
7133
+ ...generate("owner-token", "test-agent", {
7134
+ messages: "hi",
7135
+ agentId: "locked-agent",
7136
+ memory: { thread: `generate-thread-${++threadCounter}` }
7137
+ }),
7138
+ query: { agentId: "locked-agent" }
7139
+ });
7140
+ expect(allowed.status).toBe(200);
7141
+ expect(allowed.body.text).toBe("hello from test-agent");
7142
+ });
7143
+ });
7144
+ });
7145
+ describe(`${suiteName} with path-scoped authorization`, () => {
7146
+ const authenticateToken = async (token) => USERS$2[token] ?? null;
7147
+ const agentRules = [{
7148
+ path: ["/__dispatch", "/api/agents/*"],
7149
+ allow: true
7150
+ }];
7151
+ const variants = [
7152
+ {
7153
+ name: "server.auth.rules",
7154
+ auth: () => ({
7155
+ authenticateToken,
7156
+ rules: agentRules
7157
+ }),
7158
+ generate: 200,
7159
+ tool: 403
7160
+ },
7161
+ {
7162
+ name: "server.auth.authorize(path)",
7163
+ auth: () => ({
7164
+ authenticateToken,
7165
+ authorize: async (path) => !/^\/api\/agents\/[^/]+\/generate$/.test(path)
7166
+ }),
7167
+ generate: 403,
7168
+ tool: 200
7169
+ },
7170
+ {
7171
+ name: "authorizeUser(user, request)",
7172
+ auth: () => new SimpleAuth({
7173
+ tokens: USERS$2,
7174
+ authorizeUser: (_user, request) => Boolean(request.header("authorization")) && !new URL(request.raw.url).pathname.endsWith("/generate")
7175
+ }),
7176
+ generate: 403,
7177
+ tool: 200
7178
+ },
7179
+ {
7180
+ name: "server.auth.public paths and requiresAuth:true",
7181
+ auth: () => ({
7182
+ authenticateToken,
7183
+ public: ["/api/tools/*", "/custom/*"],
7184
+ rules: agentRules
7185
+ }),
7186
+ generate: 200,
7187
+ tool: 403,
7188
+ custom: {
7189
+ open: 200,
7190
+ secure: 403
7191
+ }
7192
+ },
7193
+ {
7194
+ name: "studio.auth rules for a Studio request dispatched without the outer request",
7195
+ auth: () => ({ authenticateToken }),
7196
+ studioAuth: () => ({
7197
+ authenticateToken,
7198
+ rules: agentRules
7199
+ }),
7200
+ studio: true,
7201
+ forwardRequest: false,
7202
+ generate: 200,
7203
+ tool: 403
7204
+ }
7205
+ ];
7206
+ for (const variant of variants) describe(variant.name, () => {
7207
+ const probeCases = /* @__PURE__ */ new Map();
7208
+ let server;
7209
+ const openRoute = createRoute({
7210
+ method: "GET",
7211
+ path: "/custom/open",
7212
+ responseType: "json",
7213
+ handler: async () => ({ open: true })
7214
+ });
7215
+ const secureRoute = createRoute({
7216
+ method: "GET",
7217
+ path: "/custom/secure",
7218
+ responseType: "json",
7219
+ requiresAuth: true,
7220
+ handler: async () => ({ secret: true })
7221
+ });
7222
+ beforeAll(async () => {
7223
+ const probe = createProbe(probeStyle, async ({ case: caseId }, { request, ...context }) => {
7224
+ const probeCase = probeCases.get(caseId);
7225
+ return dispatchRoute(probeCase.route, probeCase.input, {
7226
+ ...context,
7227
+ ...variant.forwardRequest === false ? {} : { request }
7228
+ });
7229
+ });
7230
+ const mastra = new Mastra$1({
7231
+ logger: false,
7232
+ agents: { "test-agent": new Agent({
7233
+ id: "test-agent",
7234
+ name: "test-agent",
7235
+ instructions: "You are a test agent",
7236
+ model: createMockModel({ mockText: "hello from test-agent" })
7237
+ }) },
7238
+ tools: { "test-tool": createTool({
7239
+ id: "test-tool",
7240
+ description: "Echoes its input",
7241
+ inputSchema: z$2.object({ text: z$2.string() }),
7242
+ execute: async ({ text }) => ({ echoed: text })
7243
+ }) },
7244
+ server: {
7245
+ auth: variant.auth(),
7246
+ apiRoutes: [
7247
+ probe,
7248
+ openRoute,
7249
+ secureRoute
7250
+ ]
7251
+ },
7252
+ ...variant.studioAuth ? { studio: { auth: variant.studioAuth() } } : {}
7253
+ });
7254
+ server = await startServer(mastra);
7255
+ });
7256
+ afterAll(async () => {
7257
+ await server?.close?.();
7258
+ });
7259
+ const both = async (method, route, httpPath, input) => {
7260
+ const headers = {
7261
+ authorization: "Bearer member-token",
7262
+ "content-type": "application/json",
7263
+ ...variant.studio ? { "x-mastra-client-type": "studio" } : {}
7264
+ };
7265
+ const httpResponse = await server.request(httpPath, {
7266
+ method,
7267
+ headers,
7268
+ ...input.body !== void 0 ? { body: JSON.stringify(input.body) } : {}
7269
+ });
7270
+ const httpText = await httpResponse.text();
7271
+ const caseId = String(probeCases.size);
7272
+ probeCases.set(caseId, {
7273
+ route,
7274
+ input
7275
+ });
7276
+ const probeResponse = await server.request(`/__dispatch?case=${caseId}`, { headers });
7277
+ expect(probeResponse.status).toBe(200);
7278
+ const outcome = await probeResponse.json();
7279
+ return {
7280
+ http: {
7281
+ status: httpResponse.status,
7282
+ body: httpText ? JSON.parse(httpText) : void 0
7283
+ },
7284
+ dispatched: outcome.ok ? {
7285
+ status: 200,
7286
+ body: outcome.result
7287
+ } : {
7288
+ status: outcome.status,
7289
+ body: outcome.body
7290
+ }
7291
+ };
7292
+ };
7293
+ const expectAgree = (result, expectedStatus) => {
7294
+ expect(result.http.status, `http ${JSON.stringify(result.http.body).slice(0, 120)}`).toBe(expectedStatus);
7295
+ expect(result.dispatched.status, `dispatch ${JSON.stringify(result.dispatched.body).slice(0, 120)}`).toBe(expectedStatus);
7296
+ if (expectedStatus >= 400 && sameErrorBodies) expect(result.dispatched.body).toEqual(result.http.body);
7297
+ };
7298
+ it(`agent generate → ${variant.generate} both ways`, async () => {
7299
+ expectAgree(await both("POST", findRoute("POST", "/agents/:agentId/generate"), "/api/agents/test-agent/generate", {
7300
+ pathParams: { agentId: "test-agent" },
7301
+ body: { messages: "hi" }
7302
+ }), variant.generate);
7303
+ });
7304
+ it(`tool execute → ${variant.tool} both ways`, async () => {
7305
+ expectAgree(await both("POST", findRoute("POST", "/tools/:toolId/execute"), "/api/tools/test-tool/execute", {
7306
+ pathParams: { toolId: "test-tool" },
7307
+ body: { data: { text: "ping" } }
7308
+ }), variant.tool);
7309
+ });
7310
+ if (variant.forwardRequest !== false) it("a requiresAuth:false route stays public both ways", async () => {
7311
+ expectAgree(await both("GET", findRoute("GET", "/auth/capabilities"), "/api/auth/capabilities", {}), 200);
7312
+ });
7313
+ if (variant.custom && probeStyle === "schema") {
7314
+ const { open, secure } = variant.custom;
7315
+ it(`a custom route on a public path → ${open} both ways`, async () => {
7316
+ expectAgree(await both("GET", openRoute, "/custom/open", {}), open);
7317
+ });
7318
+ it(`a requiresAuth:true custom route on a public path → ${secure} both ways`, async () => {
7319
+ expectAgree(await both("GET", secureRoute, "/custom/secure", {}), secure);
7320
+ });
7321
+ }
7322
+ });
7323
+ });
7324
+ describe(`${suiteName} without auth`, () => {
7325
+ const probeCases = /* @__PURE__ */ new Map();
7326
+ let server;
7327
+ beforeAll(async () => {
7328
+ const probe = createProbe(probeStyle, async ({ case: caseId }, context) => {
7329
+ const probeCase = probeCases.get(caseId);
7330
+ return dispatchRoute(probeCase.route, probeCase.input, context);
7331
+ });
7332
+ const mastra = new Mastra$1({
7333
+ logger: false,
7334
+ tools: { "test-tool": createTool({
7335
+ id: "test-tool",
7336
+ description: "Echoes its input",
7337
+ inputSchema: z$2.object({ text: z$2.string() }),
7338
+ execute: async ({ text }) => ({ echoed: text })
7339
+ }) },
7340
+ server: { apiRoutes: [probe] }
7341
+ });
7342
+ server = await startServer(mastra);
7343
+ });
7344
+ afterAll(async () => {
7345
+ await server?.close?.();
7346
+ });
7347
+ it("allows the same requests with no auth configured", async () => {
7348
+ const http = await server.request("/api/tools/test-tool/execute", {
7349
+ method: "POST",
7350
+ headers: { "content-type": "application/json" },
7351
+ body: JSON.stringify({ data: { text: "ping" } })
7352
+ });
7353
+ probeCases.set("0", {
7354
+ route: findRoute("POST", "/tools/:toolId/execute"),
7355
+ input: {
7356
+ pathParams: { toolId: "test-tool" },
7357
+ body: { data: { text: "ping" } }
7358
+ }
7359
+ });
7360
+ const dispatched = await (await server.request("/__dispatch?case=0")).json();
7361
+ expect(http.status).toBe(200);
7362
+ expect(dispatched).toEqual({
7363
+ ok: true,
7364
+ result: await http.json()
7365
+ });
7366
+ });
7367
+ });
7368
+ describe(`${suiteName} when routes are not served under /api`, () => {
7369
+ const probeCases = /* @__PURE__ */ new Map();
7370
+ let mastra;
7371
+ let server;
7372
+ let second;
7373
+ const headers = {
7374
+ authorization: "Bearer member-token",
7375
+ "content-type": "application/json"
7376
+ };
7377
+ beforeAll(async () => {
7378
+ const probe = createProbe(probeStyle, async ({ case: caseId, prefix }, context) => {
7379
+ const probeCase = probeCases.get(caseId);
7380
+ return dispatchRoute(probeCase.route, probeCase.input, {
7381
+ ...context,
7382
+ ...prefix === void 0 ? {} : { routePrefix: prefix }
7383
+ });
7384
+ });
7385
+ mastra = new Mastra$1({
7386
+ logger: false,
7387
+ agents: { "test-agent": new Agent({
7388
+ id: "test-agent",
7389
+ name: "test-agent",
7390
+ instructions: "You are a test agent",
7391
+ model: createMockModel({ mockText: "hello from test-agent" })
7392
+ }) },
7393
+ tools: { "test-tool": createTool({
7394
+ id: "test-tool",
7395
+ description: "Echoes its input",
7396
+ inputSchema: z$2.object({ text: z$2.string() }),
7397
+ execute: async ({ text }) => ({ echoed: text })
7398
+ }) },
7399
+ server: {
7400
+ auth: {
7401
+ authenticateToken: async (token) => USERS$2[token] ?? null,
7402
+ protected: ["/mastra/*", "/internal/*"],
7403
+ rules: [{
7404
+ path: [
7405
+ "/__dispatch",
7406
+ "/mastra/agents/*",
7407
+ "/internal/agents/*"
7408
+ ],
7409
+ allow: true
7410
+ }]
7411
+ },
7412
+ apiRoutes: [probe]
7413
+ }
7414
+ });
7415
+ server = await startServer(mastra, { prefix: "/mastra" });
7416
+ });
7417
+ afterAll(async () => {
7418
+ await server?.close?.();
7419
+ await second?.close?.();
7420
+ });
7421
+ const generate = {
7422
+ route: () => findRoute("POST", "/agents/:agentId/generate"),
7423
+ path: "/agents/test-agent/generate",
7424
+ input: {
7425
+ pathParams: { agentId: "test-agent" },
7426
+ body: { messages: "hi" }
7427
+ }
7428
+ };
7429
+ const tool = {
7430
+ route: () => findRoute("POST", "/tools/:toolId/execute"),
7431
+ path: "/tools/test-tool/execute",
7432
+ input: {
7433
+ pathParams: { toolId: "test-tool" },
7434
+ body: { data: { text: "ping" } }
7435
+ }
7436
+ };
7437
+ const viaHttp = async (target, prefix, request) => {
7438
+ const response = await target.request(`${prefix}${request.path}`, {
7439
+ method: "POST",
7440
+ headers,
7441
+ body: JSON.stringify(request.input.body)
7442
+ });
7443
+ const text = await response.text();
7444
+ return {
7445
+ status: response.status,
7446
+ body: text ? JSON.parse(text) : void 0
7447
+ };
7448
+ };
7449
+ const probeResponse = (target, request, routePrefix) => {
7450
+ const caseId = String(probeCases.size);
7451
+ probeCases.set(caseId, {
7452
+ route: request.route(),
7453
+ input: request.input
7454
+ });
7455
+ const prefixQuery = routePrefix === void 0 ? "" : `&prefix=${encodeURIComponent(routePrefix)}`;
7456
+ return target.request(`/__dispatch?case=${caseId}${prefixQuery}`, { headers });
7457
+ };
7458
+ const viaDispatch = async (target, request, routePrefix) => {
7459
+ const response = await probeResponse(target, request, routePrefix);
7460
+ expect(response.status).toBe(200);
7461
+ const outcome = await response.json();
7462
+ return outcome.ok ? {
7463
+ status: 200,
7464
+ body: outcome.result
7465
+ } : {
7466
+ status: outcome.status,
7467
+ body: outcome.body
7468
+ };
7469
+ };
7470
+ it("applies the rules written for the real paths, both ways", async () => {
7471
+ expect((await viaHttp(server, "/mastra", generate)).status).toBe(200);
7472
+ expect((await viaDispatch(server, generate)).status).toBe(200);
7473
+ const http = await viaHttp(server, "/mastra", tool);
7474
+ expect(http.status).toBe(403);
7475
+ const dispatched = await viaDispatch(server, tool);
7476
+ expect(dispatched.status).toBe(403);
7477
+ if (sameErrorBodies) expect(dispatched.body).toEqual(http.body);
7478
+ });
7479
+ it("uses the paths of the adapter serving the request when several serve the same Mastra instance", async () => {
7480
+ second = await startServer(mastra, { prefix: "/internal" });
7481
+ for (const [target, prefix] of [[server, "/mastra"], [second, "/internal"]]) for (const routePrefix of [void 0, prefix]) {
7482
+ expect((await viaHttp(target, prefix, generate)).status).toBe(200);
7483
+ expect((await viaDispatch(target, generate, routePrefix)).status).toBe(200);
7484
+ const http = await viaHttp(target, prefix, tool);
7485
+ expect(http.status).toBe(403);
7486
+ const dispatched = await viaDispatch(target, tool, routePrefix);
7487
+ expect(dispatched.status).toBe(403);
7488
+ if (sameErrorBodies) expect(dispatched.body).toEqual(http.body);
7489
+ }
7490
+ const requestContext = new RequestContext();
7491
+ requestContext.set("mastra__user", USERS$2["member-token"]);
7492
+ await expect(dispatchRoute(generate.route(), generate.input, {
7493
+ mastra,
7494
+ requestContext,
7495
+ abortSignal: new AbortController().signal
7496
+ })).rejects.toThrow(/cannot tell which path/);
7497
+ });
7498
+ it("refuses to guess between two adapters serving the same prefix, outside a request", async () => {
7499
+ const third = await startServer(mastra, { prefix: "/mastra" });
7500
+ try {
7501
+ expect((await viaDispatch(third, generate, "/mastra")).status).toBe(200);
7502
+ expect((await viaDispatch(third, tool, "/mastra")).status).toBe(403);
7503
+ const requestContext = new RequestContext();
7504
+ requestContext.set("mastra__user", USERS$2["member-token"]);
7505
+ await expect(dispatchRoute(generate.route(), generate.input, {
7506
+ mastra,
7507
+ requestContext,
7508
+ abortSignal: new AbortController().signal,
7509
+ routePrefix: "/mastra"
7510
+ })).rejects.toThrow(/cannot tell which path/);
7511
+ } finally {
7512
+ await third.close?.();
7513
+ }
7514
+ });
7515
+ });
7516
+ }
7517
+ // src/builtin-mcp-oauth-test-suite.ts
7518
+ const ISSUER = "https://issuer.example.com/";
7519
+ const KID = "oauth-suite-key";
7520
+ /** A local signing key served as a real JWKS document over HTTP. */
7521
+ async function startJwks() {
7522
+ const { publicKey, privateKey } = await generateKeyPair("RS256");
7523
+ const jwk = {
7524
+ ...await exportJWK(publicKey),
7525
+ kid: KID,
7526
+ alg: "RS256",
7527
+ use: "sig"
7528
+ };
7529
+ const server = createServer((_req, res) => {
7530
+ res.setHeader("content-type", "application/json");
7531
+ res.end(JSON.stringify({ keys: [jwk] }));
7532
+ });
7533
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
7534
+ const { port } = server.address();
7535
+ return {
7536
+ jwksUri: `http://127.0.0.1:${port}/.well-known/jwks.json`,
7537
+ sign: (claims, expiresIn = "5m") => new SignJWT({
7538
+ sub: "user-1",
7539
+ ...claims
7540
+ }).setProtectedHeader({
7541
+ alg: "RS256",
7542
+ kid: KID
7543
+ }).setIssuer(ISSUER).setIssuedAt().setExpirationTime(expiresIn).sign(privateKey),
7544
+ close: () => new Promise((resolve) => server.close(() => resolve()))
7545
+ };
7546
+ }
7547
+ const echo = createTool({
7548
+ id: "echo",
7549
+ description: "Echoes its input",
7550
+ inputSchema: z$2.object({ text: z$2.string() }),
7551
+ execute: async ({ text }) => ({ echoed: text })
7552
+ });
7553
+ const MCP_INIT = {
7554
+ method: "POST",
7555
+ headers: {
7556
+ "content-type": "application/json",
7557
+ accept: "application/json, text/event-stream"
7558
+ },
7559
+ body: JSON.stringify({
7560
+ jsonrpc: "2.0",
7561
+ id: 1,
7562
+ method: "tools/list"
7563
+ })
7564
+ };
7565
+ /**
7566
+ * OAuth discovery (RFC 9728) and audience enforcement for the built-in `/api/mcp` endpoint, using a real
7567
+ * `MastraJwtAuth` verifying RS256 tokens against a local JWKS server.
7568
+ */
7569
+ function createBuiltinMCPOAuthTestSuite(config) {
7570
+ const { suiteName = "Built-in MCP OAuth", startServer } = config;
7571
+ describe(suiteName, () => {
7572
+ let jwks;
7573
+ const running = [];
7574
+ const clients = [];
7575
+ beforeAll(async () => {
7576
+ jwks = await startJwks();
7577
+ });
7578
+ afterAll(async () => {
7579
+ await Promise.all(clients.map((client) => client.disconnect()));
7580
+ await Promise.all(running.map((server) => server.close()));
7581
+ await jwks?.close();
7582
+ vi.unstubAllEnvs();
7583
+ });
7584
+ const serve = async (server, options = {}) => {
7585
+ const mastra = new Mastra$1({
7586
+ logger: false,
7587
+ tools: { echo },
7588
+ server,
7589
+ ...options
7590
+ });
7591
+ const started = await startServer(mastra);
7592
+ running.push(started);
7593
+ return {
7594
+ ...started,
7595
+ mastra
7596
+ };
7597
+ };
7598
+ const serveWithJwt = (oauth) => serve({
7599
+ auth: new MastraJwtAuth({
7600
+ jwksUri: jwks.jwksUri,
7601
+ issuer: ISSUER
7602
+ }),
7603
+ mcp: { oauth }
7604
+ });
7605
+ const postMCP = (url, token) => fetch(`${url}/api/mcp`, {
7606
+ ...MCP_INIT,
7607
+ headers: {
7608
+ ...MCP_INIT.headers,
7609
+ ...token ? { authorization: `Bearer ${token}` } : {}
7610
+ }
7611
+ });
7612
+ const listTools = async (url, token) => {
7613
+ const client = new MCPClient({
7614
+ id: `oauth-suite-${clients.length}`,
7615
+ servers: { mastra: {
7616
+ url: new URL(`${url}/api/mcp`),
7617
+ requestInit: { headers: { authorization: `Bearer ${token}` } }
7618
+ } }
7619
+ });
7620
+ clients.push(client);
7621
+ return Object.keys(await client.listTools());
7622
+ };
7623
+ const resourceMetadataUrl = (challenge) => /resource_metadata="([^"]+)"/.exec(challenge ?? "")?.[1];
7624
+ describe("discovery", () => {
7625
+ let server;
7626
+ beforeAll(async () => {
7627
+ server = await serveWithJwt();
7628
+ });
7629
+ it("answers an unauthenticated MCP request with 401 and a resource_metadata challenge", async () => {
7630
+ const response = await postMCP(server.url);
7631
+ expect(response.status).toBe(401);
7632
+ const challenge = response.headers.get("www-authenticate");
7633
+ expect(challenge).toBe(`Bearer resource_metadata="${server.url}/.well-known/oauth-protected-resource/api/mcp"`);
7634
+ const metadata = await fetch(resourceMetadataUrl(challenge));
7635
+ expect(metadata.status).toBe(200);
7636
+ expect(metadata.headers.get("content-type")).toContain("application/json");
7637
+ expect(metadata.headers.get("cache-control")).toBe("no-store");
7638
+ const document = await metadata.json();
7639
+ expect(document).toEqual({
7640
+ resource: `${server.url}/api/mcp`,
7641
+ authorization_servers: [ISSUER],
7642
+ bearer_methods_supported: ["header"]
7643
+ });
7644
+ const root = await fetch(`${server.url}/.well-known/oauth-protected-resource`);
7645
+ expect(root.status).toBe(200);
7646
+ expect(await root.json()).toEqual(document);
7647
+ });
7648
+ it("marks presented but invalid tokens with error=\"invalid_token\"", async () => {
7649
+ const response = await postMCP(server.url, "not-a-jwt");
7650
+ expect(response.status).toBe(401);
7651
+ expect(response.headers.get("www-authenticate")).toContain("error=\"invalid_token\"");
7652
+ expect(resourceMetadataUrl(response.headers.get("www-authenticate"))).toBeDefined();
7653
+ });
7654
+ it("marks expired tokens with error=\"invalid_token\"", async () => {
7655
+ const expired = await jwks.sign({ aud: "anything" }, Math.floor(Date.now() / 1e3) - 60);
7656
+ const response = await postMCP(server.url, expired);
7657
+ expect(response.status).toBe(401);
7658
+ expect(response.headers.get("www-authenticate")).toContain("error=\"invalid_token\"");
7659
+ });
7660
+ it("does not enforce the token audience while server.mcp.oauth.resource is unset", async () => {
7661
+ const token = await jwks.sign({ aud: "https://some-other-api.example.com" });
7662
+ expect(await listTools(server.url, token)).toContain("mastra_tool_echo");
7663
+ });
7664
+ it("leaves other routes unchanged", async () => {
7665
+ const response = await fetch(`${server.url}/api/tools`);
7666
+ expect(response.status).toBe(401);
7667
+ expect(response.headers.get("www-authenticate")).toBeNull();
7668
+ });
7669
+ });
7670
+ describe("audience enforcement (server.mcp.oauth.resource)", () => {
7671
+ const resource = "https://mcp.example.com/api/mcp";
7672
+ let server;
7673
+ beforeAll(async () => {
7674
+ server = await serveWithJwt({ resource });
7675
+ });
7676
+ it("serves MCP to tokens issued for the resource", async () => {
7677
+ const token = await jwks.sign({ aud: ["https://other.example.com", resource] });
7678
+ expect(await listTools(server.url, token)).toContain("mastra_tool_echo");
7679
+ });
7680
+ it("rejects tokens issued for another audience with 401 invalid_token", async () => {
7681
+ const token = await jwks.sign({ aud: "https://some-other-api.example.com" });
7682
+ const response = await postMCP(server.url, token);
7683
+ expect(response.status).toBe(401);
7684
+ const challenge = response.headers.get("www-authenticate");
7685
+ expect(challenge).toContain("error=\"invalid_token\"");
7686
+ expect(resourceMetadataUrl(challenge)).toBe("https://mcp.example.com/.well-known/oauth-protected-resource/api/mcp");
7687
+ });
7688
+ it("does not apply the MCP audience to other routes", async () => {
7689
+ const token = await jwks.sign({ aud: "https://some-other-api.example.com" });
7690
+ const response = await fetch(`${server.url}/api/tools`, { headers: { authorization: `Bearer ${token}` } });
7691
+ expect(response.status).toBe(200);
7692
+ });
7693
+ it("advertises the configured resource", async () => {
7694
+ const document = await (await fetch(`${server.url}/.well-known/oauth-protected-resource/api/mcp`)).json();
7695
+ expect(document.resource).toBe(resource);
7696
+ });
7697
+ });
7698
+ describe("providers that cannot check the audience (server.mcp.oauth.requireAudience)", () => {
7699
+ const resource = "https://mcp.example.com/api/mcp";
7700
+ const apiKeyAuth = () => new SimpleAuth({ tokens: { "api-key": { id: "key-user" } } });
7701
+ const jwtAuth = () => new MastraJwtAuth({
7702
+ jwksUri: jwks.jwksUri,
7703
+ issuer: ISSUER
7704
+ });
7705
+ it("serves an API key without oauth.resource", async () => {
7706
+ const server = await serve({
7707
+ auth: apiKeyAuth(),
7708
+ mcp: {}
7709
+ });
7710
+ expect(await listTools(server.url, "api-key")).toContain("mastra_tool_echo");
7711
+ });
7712
+ it("serves an API key with oauth.resource by default", async () => {
7713
+ const server = await serve({
7714
+ auth: apiKeyAuth(),
7715
+ mcp: { oauth: { resource } }
7716
+ });
7717
+ expect(await listTools(server.url, "api-key")).toContain("mastra_tool_echo");
7718
+ });
7719
+ it("rejects an API key with 401 invalid_token when requireAudience is on", async () => {
7720
+ const server = await serve({
7721
+ auth: apiKeyAuth(),
7722
+ mcp: { oauth: {
7723
+ resource,
7724
+ requireAudience: true
7725
+ } }
7726
+ });
7727
+ const response = await postMCP(server.url, "api-key");
7728
+ expect(response.status).toBe(401);
7729
+ expect(response.headers.get("www-authenticate")).toContain("error=\"invalid_token\"");
7730
+ const tools = await fetch(`${server.url}/api/tools`, { headers: { authorization: "Bearer api-key" } });
7731
+ expect(tools.status).toBe(200);
7732
+ });
7733
+ it("still serves a JWT issued for the resource when requireAudience is on", async () => {
7734
+ const server = await serve({
7735
+ auth: jwtAuth(),
7736
+ mcp: { oauth: {
7737
+ resource,
7738
+ requireAudience: true
7739
+ } }
7740
+ });
7741
+ expect(await listTools(server.url, await jwks.sign({ aud: resource }))).toContain("mastra_tool_echo");
7742
+ const wrongAudience = await postMCP(server.url, await jwks.sign({ aud: "https://other-api.example.com" }));
7743
+ expect(wrongAudience.status).toBe(401);
7744
+ });
7745
+ it("rejects a CompositeAuth provider that cannot check the audience when requireAudience is on", async () => {
7746
+ const server = await serve({
7747
+ auth: new CompositeAuth([jwtAuth(), apiKeyAuth()]),
7748
+ mcp: { oauth: {
7749
+ resource,
7750
+ requireAudience: true
7751
+ } }
7752
+ });
7753
+ expect(await listTools(server.url, await jwks.sign({ aud: resource }))).toContain("mastra_tool_echo");
7754
+ expect((await postMCP(server.url, "api-key")).status).toBe(401);
7755
+ });
7756
+ it("serves a CompositeAuth provider that cannot check the audience by default", async () => {
7757
+ const server = await serve({
7758
+ auth: new CompositeAuth([jwtAuth(), apiKeyAuth()]),
7759
+ mcp: { oauth: { resource } }
7760
+ });
7761
+ expect(await listTools(server.url, "api-key")).toContain("mastra_tool_echo");
7762
+ });
7763
+ });
7764
+ describe("RBAC with an access token that carries only sub", () => {
7765
+ let server;
7766
+ beforeAll(async () => {
7767
+ server = await serve({
7768
+ auth: new MastraJwtAuth({
7769
+ jwksUri: jwks.jwksUri,
7770
+ issuer: ISSUER
7771
+ }),
7772
+ rbac: new StaticRBACProvider({
7773
+ roles: [{
7774
+ id: "caller",
7775
+ name: "Caller",
7776
+ permissions: [
7777
+ "tools:read",
7778
+ "tools:execute",
7779
+ "mcp:read",
7780
+ "mcp:execute"
7781
+ ]
7782
+ }, {
7783
+ id: "nobody",
7784
+ name: "Nobody",
7785
+ permissions: []
7786
+ }],
7787
+ getUserRoles: (user) => [user.id === "user-1" ? "caller" : "nobody"]
7788
+ }),
7789
+ mcp: {}
7790
+ });
7791
+ });
7792
+ it("serves a protected route to a user whose role allows it", async () => {
7793
+ const response = await fetch(`${server.url}/api/tools`, { headers: { authorization: `Bearer ${await jwks.sign({})}` } });
7794
+ expect(response.status).toBe(200);
7795
+ });
7796
+ it("lists MCP tools for a user whose role allows it", async () => {
7797
+ expect(await listTools(server.url, await jwks.sign({}))).toContain("mastra_tool_echo");
7798
+ });
7799
+ it("still answers 403 to a user whose role does not allow the route", async () => {
7800
+ const token = await jwks.sign({ sub: "user-2" });
7801
+ const response = await fetch(`${server.url}/api/tools`, { headers: { authorization: `Bearer ${token}` } });
7802
+ expect(response.status).toBe(403);
7803
+ expect((await postMCP(server.url, token)).status).toBe(403);
7804
+ });
7805
+ });
7806
+ describe("ownership with an access token that carries only sub", () => {
7807
+ let server;
7808
+ beforeAll(async () => {
7809
+ const storage = new InMemoryStore();
7810
+ server = await serve({ auth: new MastraJwtAuth({
7811
+ jwksUri: jwks.jwksUri,
7812
+ issuer: ISSUER
7813
+ }) }, { storage });
7814
+ const agents = await storage.getStore("agents");
7815
+ for (const [id, authorId] of [["user-1-private", "user-1"], ["user-2-private", "user-2"]]) await agents.create({ agent: {
7816
+ id,
7817
+ authorId,
7818
+ visibility: "private",
7819
+ name: id,
7820
+ instructions: "x",
7821
+ model: {
7822
+ provider: "openai",
7823
+ name: "gpt-4o"
7824
+ }
7825
+ } });
7826
+ });
7827
+ const listIds = async (sub) => {
7828
+ const response = await fetch(`${server.url}/api/stored/agents?status=draft`, { headers: { authorization: `Bearer ${await jwks.sign({ sub })}` } });
7829
+ expect(response.status).toBe(200);
7830
+ return (await response.json()).agents.map((agent) => agent.id).sort();
7831
+ };
7832
+ it("does not list another user's private record", async () => {
7833
+ expect(await listIds("user-1")).toEqual(["user-1-private"]);
7834
+ expect(await listIds("user-2")).toEqual(["user-2-private"]);
7835
+ });
7836
+ });
7837
+ it("prefers configured authorization servers over the provider issuer", async () => {
7838
+ const server = await serveWithJwt({
7839
+ authorizationServers: ["https://login.example.com"],
7840
+ scopesSupported: ["mastra"]
7841
+ });
7842
+ const document = await (await fetch(`${server.url}/.well-known/oauth-protected-resource`)).json();
7843
+ expect(document.authorization_servers).toEqual(["https://login.example.com"]);
7844
+ expect(document.scopes_supported).toEqual(["mastra"]);
7845
+ });
7846
+ it("sends no challenge and serves no metadata while the built-in MCP server is disabled", async () => {
7847
+ const server = await serve({
7848
+ auth: new MastraJwtAuth({
7849
+ jwksUri: jwks.jwksUri,
7850
+ issuer: ISSUER
7851
+ }),
7852
+ mcp: { enabled: false }
7853
+ });
7854
+ const response = await postMCP(server.url);
7855
+ expect(response.headers.get("www-authenticate")).toBeNull();
7856
+ expect((await fetch(`${server.url}/.well-known/oauth-protected-resource/api/mcp`)).status).toBe(404);
7857
+ });
7858
+ it("keeps enforcing the audience for an invalid resource, but turns discovery off", async () => {
7859
+ const resource = "http://mcp.example.com/api/mcp";
7860
+ const server = await serveWithJwt({ resource });
7861
+ const anonymous = await postMCP(server.url);
7862
+ expect(anonymous.status).toBe(401);
7863
+ expect(resourceMetadataUrl(anonymous.headers.get("www-authenticate"))).toBeUndefined();
7864
+ expect((await fetch(`${server.url}/.well-known/oauth-protected-resource`)).status).toBe(404);
7865
+ const wrongAudience = await postMCP(server.url, await jwks.sign({ aud: "https://other-api.example.com" }));
7866
+ expect(wrongAudience.status).toBe(401);
7867
+ expect(wrongAudience.headers.get("www-authenticate")).toContain("error=\"invalid_token\"");
7868
+ expect(resourceMetadataUrl(wrongAudience.headers.get("www-authenticate"))).toBeUndefined();
7869
+ expect(await listTools(server.url, await jwks.sign({ aud: resource }))).toContain("mastra_tool_echo");
7870
+ });
7871
+ it("serves no discovery routes without server.auth", async () => {
7872
+ vi.stubEnv("MASTRA_DEV", "true");
7873
+ const server = await serve({});
7874
+ expect((await fetch(`${server.url}/.well-known/oauth-protected-resource`)).status).toBe(404);
7875
+ expect((await fetch(`${server.url}/.well-known/oauth-protected-resource/api/mcp`)).status).toBe(404);
7876
+ vi.unstubAllEnvs();
7877
+ });
7878
+ });
7879
+ }
7880
+ // src/builtin-mcp-parity-test-suite.ts
7881
+ const USERS$1 = {
7882
+ "owner-token": {
7883
+ id: "user-owner",
7884
+ role: "owner",
7885
+ studioRole: "owner"
7886
+ },
7887
+ "member-token": {
7888
+ id: "user-member",
7889
+ role: "member",
7890
+ studioRole: "member"
7891
+ },
7892
+ "member2-token": {
7893
+ id: "user-member2",
7894
+ role: "member",
7895
+ studioRole: "member"
7896
+ },
7897
+ "viewer-token": {
7898
+ id: "user-viewer",
7899
+ role: "viewer",
7900
+ studioRole: "owner"
7901
+ },
7902
+ "no-agents-token": {
7903
+ id: "user-no-agents",
7904
+ role: "no-agents",
7905
+ studioRole: "no-agents"
7906
+ },
7907
+ "no-workflows-token": {
7908
+ id: "user-no-workflows",
7909
+ role: "no-workflows",
7910
+ studioRole: "no-workflows"
7911
+ },
7912
+ "no-tools-token": {
7913
+ id: "user-no-tools",
7914
+ role: "no-tools",
7915
+ studioRole: "no-tools"
7916
+ },
7917
+ "no-mcp-execute-token": {
7918
+ id: "user-no-mcp-execute",
7919
+ role: "no-mcp-execute",
7920
+ studioRole: "no-mcp-execute"
7921
+ },
7922
+ "no-mcp-token": {
7923
+ id: "user-no-mcp",
7924
+ role: "no-mcp",
7925
+ studioRole: "no-mcp"
7926
+ }
7927
+ };
7928
+ const ROLES$1 = [
7929
+ ...DEFAULT_ROLES,
7930
+ {
7931
+ id: "no-agents",
7932
+ name: "No agent execution",
7933
+ permissions: [
7934
+ "*:read",
7935
+ "workflows:execute",
7936
+ "tools:execute",
7937
+ "mcp:execute"
7938
+ ]
7939
+ },
7940
+ {
7941
+ id: "no-workflows",
7942
+ name: "No workflow execution",
7943
+ permissions: [
7944
+ "*:read",
7945
+ "agents:execute",
7946
+ "tools:execute",
7947
+ "mcp:execute",
7948
+ "memory:*"
7949
+ ]
7950
+ },
7951
+ {
7952
+ id: "no-tools",
7953
+ name: "No tool execution",
7954
+ permissions: [
7955
+ "*:read",
7956
+ "agents:execute",
7957
+ "workflows:execute",
7958
+ "mcp:execute",
7959
+ "memory:*"
7960
+ ]
7961
+ },
7962
+ {
7963
+ id: "no-mcp-execute",
7964
+ name: "MCP discovery only",
7965
+ permissions: [
7966
+ "*:read",
7967
+ "agents:execute",
7968
+ "workflows:execute",
7969
+ "tools:execute",
7970
+ "memory:*"
7971
+ ]
7972
+ },
7973
+ {
7974
+ id: "no-mcp",
7975
+ name: "No MCP",
7976
+ permissions: [
7977
+ "agents:*",
7978
+ "workflows:*",
7979
+ "tools:*",
7980
+ "memory:*"
7981
+ ]
7982
+ }
7983
+ ];
7984
+ const FGA_GRANTS = {
7985
+ "agent:test-agent": ["*"],
7986
+ "agent:locked-agent": ["user-owner"],
7987
+ "workflow:test-workflow": ["*"],
7988
+ "workflow:locked-workflow": ["user-owner"],
7989
+ "tool:test-tool": ["*"],
7990
+ "tool:whoami": ["*"],
7991
+ "tool:locked-tool": ["user-owner"]
7992
+ };
7993
+ /** In-memory relationship store standing in for an external FGA service. Thread ownership is left to handlers. */
7994
+ var TupleFGAProvider = class {
7995
+ async check(user, { resource }) {
7996
+ if (resource.type === "thread") return true;
7997
+ const grantees = FGA_GRANTS[`${resource.type}:${resource.id}`] ?? ["*"];
7998
+ return grantees.includes("*") || grantees.includes(user.id);
7999
+ }
8000
+ async require(user, params) {
8001
+ if (!await this.check(user, params)) throw new FGADeniedError(user, params.resource, params.permission);
8002
+ }
8003
+ async filterAccessible(user, resources, resourceType) {
8004
+ const allowed = [];
8005
+ for (const resource of resources) if (await this.check(user, { resource: {
8006
+ type: resourceType,
8007
+ id: resource.id
8008
+ } })) allowed.push(resource);
8009
+ return allowed;
8010
+ }
8011
+ };
8012
+ function createParityMastra(mcp = {}) {
8013
+ const memory = new MockMemory({ storage: new InMemoryStore() });
8014
+ const makeAgent = (id, description) => new Agent({
8015
+ id,
8016
+ name: id,
8017
+ description,
8018
+ instructions: "You are a test agent",
8019
+ model: createMockModel({ mockText: `hello from ${id}` }),
8020
+ memory
8021
+ });
8022
+ const approvalStep = createStep({
8023
+ id: "approval",
8024
+ inputSchema: z$2.object({ value: z$2.string() }),
8025
+ outputSchema: z$2.object({ approved: z$2.boolean() }),
8026
+ resumeSchema: z$2.object({ approved: z$2.boolean() }),
8027
+ execute: async ({ resumeData, suspend }) => {
8028
+ if (!resumeData) return suspend({ reason: "needs approval" });
8029
+ return { approved: resumeData.approved };
8030
+ }
8031
+ });
8032
+ const makeWorkflow = (id) => createWorkflow({
8033
+ id,
8034
+ description: `The ${id} workflow`,
8035
+ inputSchema: z$2.object({ value: z$2.string() }),
8036
+ outputSchema: z$2.object({ approved: z$2.boolean() })
8037
+ }).then(approvalStep).commit();
8038
+ const makeTool = (id) => createTool({
8039
+ id,
8040
+ description: "Echoes its input",
8041
+ inputSchema: z$2.object({ text: z$2.string() }),
8042
+ execute: async ({ text }) => ({ echoed: text })
8043
+ });
8044
+ const whoami = createTool({
8045
+ id: "whoami",
8046
+ description: "Returns the calling user",
8047
+ inputSchema: z$2.object({}),
8048
+ execute: async (_input, context) => ({ userId: (context?.requestContext?.get("user"))?.id ?? null })
8049
+ });
8050
+ const tokens = Object.fromEntries(Object.entries(USERS$1));
8051
+ return {
8052
+ mastra: new Mastra$1({
8053
+ logger: false,
8054
+ storage: new InMemoryStore(),
8055
+ agents: {
8056
+ "test-agent": makeAgent("test-agent", "A helpful test agent"),
8057
+ "locked-agent": makeAgent("locked-agent", "Only the owner may call this agent")
8058
+ },
8059
+ workflows: {
8060
+ "test-workflow": makeWorkflow("test-workflow"),
8061
+ "locked-workflow": makeWorkflow("locked-workflow")
8062
+ },
8063
+ tools: {
8064
+ "test-tool": makeTool("test-tool"),
8065
+ "locked-tool": makeTool("locked-tool"),
8066
+ whoami
8067
+ },
8068
+ server: {
8069
+ auth: new SimpleAuth({
8070
+ tokens,
8071
+ mapUserToResourceId: (user) => user.id
8072
+ }),
8073
+ rbac: new StaticRBACProvider({
8074
+ roles: ROLES$1,
8075
+ getUserRoles: (user) => [user.role]
8076
+ }),
8077
+ fga: new TupleFGAProvider(),
8078
+ mcp
8079
+ },
8080
+ studio: {
8081
+ auth: new SimpleAuth({
8082
+ tokens,
8083
+ mapUserToResourceId: (user) => user.id
8084
+ }),
8085
+ rbac: new StaticRBACProvider({
8086
+ roles: ROLES$1,
8087
+ getUserRoles: (user) => [user.studioRole]
8088
+ })
8089
+ }
8090
+ }),
8091
+ memory,
8092
+ makeAgent,
8093
+ makeWorkflow,
8094
+ makeTool
8095
+ };
8096
+ }
8097
+ /** Text of an MCP tool result, which for errors carries `<status> <message>`. */
8098
+ function resultText(result) {
8099
+ return (result.content ?? []).map((part) => part.text ?? "").join("");
8100
+ }
8101
+ /** A successful MCP result's payload (structuredContent, else parsed text). */
8102
+ function payload(result) {
8103
+ if (result.structuredContent !== void 0) return result.structuredContent;
8104
+ if (!Array.isArray(result.content)) return result;
8105
+ const text = resultText(result);
8106
+ try {
8107
+ return JSON.parse(text);
8108
+ } catch {
8109
+ return text;
8110
+ }
8111
+ }
8112
+ /** MCP outcome: `ok`, the HTTP status in the error, `not offered`, or `invalid` (rejected by the advertised schema). */
8113
+ function mcpOutcome(result) {
8114
+ if (result.error === true) return "invalid";
8115
+ if (!result.isError) return "ok";
8116
+ const text = resultText(result);
8117
+ if (text.includes("not offered")) return "not offered";
8118
+ const status = /"?(\d{3}) /.exec(text)?.[1];
8119
+ return status ? Number(status) : 500;
8120
+ }
8121
+ /**
8122
+ * The built-in `/api/mcp` server must allow and deny exactly what the equivalent HTTP routes allow and deny
8123
+ * for the same user (RBAC, FGA, thread ownership), plus its own `mcp:read` / `mcp:execute` gates.
8124
+ */
8125
+ function createBuiltinMCPParityTestSuite(config) {
8126
+ const { suiteName = "Built-in MCP server parity", startServer } = config;
8127
+ describe(suiteName, () => {
8128
+ let server;
8129
+ let setup;
8130
+ const clients = [];
8131
+ beforeAll(async () => {
8132
+ setup = createParityMastra();
8133
+ server = await startServer(setup.mastra);
8134
+ });
8135
+ afterAll(async () => {
8136
+ await Promise.all(clients.map((client) => client.disconnect()));
8137
+ await server?.close();
8138
+ });
8139
+ const http = async (token, method, path, body) => {
8140
+ const response = await fetch(`${server.url}/api${path}`, {
8141
+ method,
8142
+ headers: {
8143
+ ...token ? { authorization: `Bearer ${token}` } : {},
8144
+ ...body !== void 0 ? { "content-type": "application/json" } : {}
8145
+ },
8146
+ ...body !== void 0 ? { body: JSON.stringify(body) } : {}
8147
+ });
8148
+ const text = await response.text();
8149
+ return {
8150
+ status: response.status,
8151
+ body: text ? JSON.parse(text) : void 0
8152
+ };
8153
+ };
8154
+ const connect = (token, options = {}) => {
8155
+ const client = new MCPClient({
8156
+ id: `mcp-${token}-${clients.length}`,
8157
+ servers: { mastra: {
8158
+ url: new URL(`${server.url}${options.path ?? "/api/mcp"}`),
8159
+ requestInit: { headers: {
8160
+ authorization: `Bearer ${token}`,
8161
+ ...options.headers
8162
+ } },
8163
+ onToolError: "return"
8164
+ } }
8165
+ });
8166
+ clients.push(client);
8167
+ return client;
8168
+ };
8169
+ /** Raw MCP tool list (names → definitions) as the server advertises it. */
8170
+ const listTools = async (token, options) => {
8171
+ const tools = await connect(token, options).listTools();
8172
+ return Object.fromEntries(Object.entries(tools).map(([name, tool]) => [name.replace(/^mastra_/, ""), tool]));
8173
+ };
8174
+ const callTool = async (token, name, args) => {
8175
+ const tool = (await connect(token).listTools())[`mastra_${name}`];
8176
+ if (!tool) return {
8177
+ isError: true,
8178
+ content: [{
8179
+ type: "text",
8180
+ text: `tool ${name} not offered`
8181
+ }]
8182
+ };
8183
+ return await tool.execute(args, {});
8184
+ };
8185
+ describe("transport auth", () => {
8186
+ it("rejects requests without a bearer token (401), like HTTP", async () => {
8187
+ const response = await fetch(`${server.url}/api/mcp`, {
8188
+ method: "POST",
8189
+ headers: {
8190
+ "content-type": "application/json",
8191
+ accept: "application/json, text/event-stream"
8192
+ },
8193
+ body: JSON.stringify({
8194
+ jsonrpc: "2.0",
8195
+ id: 1,
8196
+ method: "tools/list"
8197
+ })
8198
+ });
8199
+ expect(response.status).toBe(401);
8200
+ expect((await http(void 0, "GET", "/agents")).status).toBe(401);
8201
+ });
8202
+ it("does not accept the apiKey query parameter or cookies as MCP credentials", async () => {
8203
+ const init = {
8204
+ method: "POST",
8205
+ headers: {
8206
+ "content-type": "application/json",
8207
+ accept: "application/json, text/event-stream"
8208
+ },
8209
+ body: JSON.stringify({
8210
+ jsonrpc: "2.0",
8211
+ id: 1,
8212
+ method: "tools/list"
8213
+ })
8214
+ };
8215
+ expect((await fetch(`${server.url}/api/mcp?apiKey=owner-token`, init)).status).toBe(401);
8216
+ expect((await fetch(`${server.url}/api/mcp`, {
8217
+ ...init,
8218
+ headers: {
8219
+ ...init.headers,
8220
+ cookie: "mastra-token=owner-token"
8221
+ }
8222
+ })).status).toBe(401);
8223
+ expect((await fetch(`${server.url}/api/agents?apiKey=owner-token`)).status).toBe(200);
8224
+ });
8225
+ it("requires mcp:read to connect", async () => {
8226
+ const response = await fetch(`${server.url}/api/mcp`, {
8227
+ method: "POST",
8228
+ headers: {
8229
+ authorization: "Bearer no-mcp-token",
8230
+ "content-type": "application/json",
8231
+ accept: "application/json, text/event-stream"
8232
+ },
8233
+ body: JSON.stringify({
8234
+ jsonrpc: "2.0",
8235
+ id: 1,
8236
+ method: "tools/list"
8237
+ })
8238
+ });
8239
+ expect(response.status).toBe(403);
8240
+ expect(await listTools("no-mcp-token")).toEqual({});
8241
+ expect((await http("no-mcp-token", "GET", "/agents")).status).toBe(200);
8242
+ });
8243
+ it("ignores the Studio client-type header (always server.auth / server.rbac)", async () => {
8244
+ const viaStudioHeader = await listTools("viewer-token", { headers: { "x-mastra-client-type": "studio" } });
8245
+ expect(Object.keys(viaStudioHeader)).toEqual([]);
8246
+ });
8247
+ it("leaves Studio and cookie auth of ordinary routes unchanged", async () => {
8248
+ const execute = (headers) => fetch(`${server.url}/api/tools/test-tool/execute`, {
8249
+ method: "POST",
8250
+ headers: {
8251
+ "content-type": "application/json",
8252
+ ...headers
8253
+ },
8254
+ body: JSON.stringify({ data: { text: "x" } })
8255
+ });
8256
+ expect((await execute({ authorization: "Bearer viewer-token" })).status).toBe(403);
8257
+ expect((await execute({
8258
+ authorization: "Bearer viewer-token",
8259
+ "x-mastra-client-type": "studio"
8260
+ })).status).toBe(200);
8261
+ expect((await fetch(`${server.url}/api/agents`, { headers: { cookie: "mastra-token=owner-token" } })).status).toBe(200);
8262
+ });
8263
+ });
8264
+ describe("catalogue", () => {
8265
+ it("offers the operation tools and registered tools as entity tools by default", async () => {
8266
+ const names = Object.keys(await listTools("owner-token")).sort();
8267
+ expect(names).toEqual([
8268
+ "call_agent",
8269
+ "cancel_workflow_run",
8270
+ "get_agent",
8271
+ "get_workflow",
8272
+ "get_workflow_run",
8273
+ "list_agents",
8274
+ "list_workflows",
8275
+ "resume_workflow_run",
8276
+ "start_workflow",
8277
+ "tool_locked-tool",
8278
+ "tool_test-tool",
8279
+ "tool_whoami",
8280
+ "analyze_feedback",
8281
+ "analyze_metrics",
8282
+ "analyze_scores",
8283
+ "clone_thread",
8284
+ "create_thread",
8285
+ "get_memory_status",
8286
+ "get_observations",
8287
+ "get_span",
8288
+ "get_thread",
8289
+ "get_trace",
8290
+ "get_trace_trajectory",
8291
+ "list_feedback",
8292
+ "list_logs",
8293
+ "list_messages",
8294
+ "list_metric_names",
8295
+ "list_scores",
8296
+ "list_threads",
8297
+ "list_traces",
8298
+ "save_messages",
8299
+ "search_memory",
8300
+ "update_thread"
8301
+ ].sort());
8302
+ });
8303
+ it("lists only the agents the caller can see, like GET /agents", async () => {
8304
+ for (const token of ["owner-token", "member-token"]) {
8305
+ const result = await callTool(token, "list_agents", {});
8306
+ const httpResult = await http(token, "GET", "/agents");
8307
+ expect(payload(result).agents.map((a) => a.id).sort()).toEqual(Object.keys(httpResult.body).sort());
8308
+ }
8309
+ });
8310
+ it("hides tools whose backing route the caller would get 403 for", async () => {
8311
+ expect(Object.keys(await listTools("no-agents-token"))).not.toContain("call_agent");
8312
+ expect(Object.keys(await listTools("no-workflows-token"))).not.toContain("start_workflow");
8313
+ const noTools = Object.keys(await listTools("no-tools-token"));
8314
+ expect(noTools.filter((name) => name.startsWith("tool_"))).toEqual([]);
8315
+ expect(Object.keys(await listTools("member-token"))).not.toContain("tool_locked-tool");
8316
+ });
8317
+ it("offers no tools without mcp:execute, though HTTP still allows the same calls", async () => {
8318
+ expect(Object.keys(await listTools("no-mcp-execute-token"))).toEqual([]);
8319
+ expect(Object.keys(await listTools("viewer-token"))).toEqual([]);
8320
+ expect((await http("no-mcp-execute-token", "POST", "/tools/test-tool/execute", { data: { text: "x" } })).status).toBe(200);
8321
+ });
8322
+ it("tracks agents added after startup", async () => {
8323
+ setup.mastra.addAgent(setup.makeAgent("late-agent", "Added later"), "late-agent");
8324
+ const result = await callTool("owner-token", "list_agents", {});
8325
+ expect(payload(result).agents.map((a) => a.id)).toContain("late-agent");
8326
+ });
8327
+ it("narrows toolsets and read-only per request but never widens them", async () => {
8328
+ const agentsOnly = Object.keys(await listTools("owner-token", { path: "/api/mcp?toolsets=agents,bogus" }));
8329
+ expect(agentsOnly.sort()).toEqual([
8330
+ "call_agent",
8331
+ "get_agent",
8332
+ "list_agents"
8333
+ ]);
8334
+ const readOnly = Object.keys(await listTools("owner-token", { headers: {
8335
+ "x-mcp-readonly": "1",
8336
+ "x-mcp-toolsets": "agents,workflows,tools"
8337
+ } }));
8338
+ expect(readOnly.sort()).toEqual([
8339
+ "get_agent",
8340
+ "get_tool",
8341
+ "get_workflow",
8342
+ "get_workflow_run",
8343
+ "list_agents",
8344
+ "list_tools",
8345
+ "list_workflows"
8346
+ ]);
8347
+ const both = Object.keys(await listTools("owner-token", {
8348
+ path: "/api/mcp?readonly=1",
8349
+ headers: { "x-mcp-toolsets": "workflows" }
8350
+ }));
8351
+ expect(both.sort()).toEqual([
8352
+ "get_workflow",
8353
+ "get_workflow_run",
8354
+ "list_workflows"
8355
+ ]);
8356
+ });
8357
+ });
8358
+ describe("agents parity", () => {
8359
+ it("call_agent returns the same reply as POST /agents/:agentId/generate", async () => {
8360
+ const result = await callTool("member-token", "call_agent", {
8361
+ agentId: "test-agent",
8362
+ message: "hi"
8363
+ });
8364
+ expect(mcpOutcome(result)).toBe("ok");
8365
+ const httpResult = await http("member-token", "POST", "/agents/test-agent/generate", {
8366
+ messages: [{
8367
+ role: "user",
8368
+ content: "hi"
8369
+ }],
8370
+ memory: {
8371
+ thread: crypto.randomUUID(),
8372
+ resource: "user-member"
8373
+ }
8374
+ });
8375
+ expect(httpResult.status).toBe(200);
8376
+ expect(payload(result).text).toBe(httpResult.body.text);
8377
+ expect(payload(result).runId).toEqual(expect.any(String));
8378
+ });
8379
+ it("denies a FGA-locked agent over MCP and HTTP", async () => {
8380
+ const result = await callTool("member-token", "call_agent", {
8381
+ agentId: "locked-agent",
8382
+ message: "hi"
8383
+ });
8384
+ expect(mcpOutcome(result)).toBe("invalid");
8385
+ const httpResult = await http("member-token", "POST", "/agents/locked-agent/generate", { messages: [{
8386
+ role: "user",
8387
+ content: "hi"
8388
+ }] });
8389
+ expect(httpResult.status).toBe(403);
8390
+ expect(mcpOutcome(await callTool("owner-token", "call_agent", {
8391
+ agentId: "locked-agent",
8392
+ message: "hi"
8393
+ }))).toBe("ok");
8394
+ });
8395
+ it("enforces thread ownership: another user's thread is 403 over MCP and HTTP", async () => {
8396
+ const own = await callTool("member2-token", "call_agent", {
8397
+ agentId: "test-agent",
8398
+ message: "remember this",
8399
+ resourceId: "user-member2"
8400
+ });
8401
+ expect(mcpOutcome(own)).toBe("ok");
8402
+ const threadId = payload(own).threadId;
8403
+ expect(threadId).toEqual(expect.any(String));
8404
+ expect(mcpOutcome(await callTool("member2-token", "call_agent", {
8405
+ agentId: "test-agent",
8406
+ message: "again",
8407
+ threadId
8408
+ }))).toBe("ok");
8409
+ const stolen = await callTool("member-token", "call_agent", {
8410
+ agentId: "test-agent",
8411
+ message: "x",
8412
+ threadId
8413
+ });
8414
+ const httpStolen = await http("member-token", "POST", "/agents/test-agent/generate", {
8415
+ messages: [{
8416
+ role: "user",
8417
+ content: "x"
8418
+ }],
8419
+ memory: {
8420
+ thread: threadId,
8421
+ resource: "user-member"
8422
+ }
8423
+ });
8424
+ expect(httpStolen.status).toBe(403);
8425
+ expect(mcpOutcome(stolen)).toBe(403);
8426
+ });
8427
+ });
8428
+ describe("workflows parity", () => {
8429
+ it("start_workflow suspends and resume_workflow_run completes, like the HTTP routes", async () => {
8430
+ const started = await callTool("member-token", "start_workflow", {
8431
+ workflowId: "test-workflow",
8432
+ inputData: { value: "x" }
8433
+ });
8434
+ expect(mcpOutcome(started)).toBe("ok");
8435
+ const { status, runId, suspendPayload } = payload(started);
8436
+ expect(status).toBe("suspended");
8437
+ expect(suspendPayload).toBeDefined();
8438
+ const run = await http("member-token", "GET", `/workflows/test-workflow/runs/${runId}`);
8439
+ expect(run.status).toBe(200);
8440
+ expect(run.body.status).toBe("suspended");
8441
+ const resumed = await callTool("member-token", "resume_workflow_run", {
8442
+ workflowId: "test-workflow",
8443
+ runId,
8444
+ step: "approval",
8445
+ resumeData: { approved: true }
8446
+ });
8447
+ expect(mcpOutcome(resumed)).toBe("ok");
8448
+ expect(payload(resumed)).toMatchObject({
8449
+ status: "success",
8450
+ result: { approved: true }
8451
+ });
8452
+ });
8453
+ it("denies a FGA-locked workflow over MCP and HTTP", async () => {
8454
+ const result = await callTool("member-token", "start_workflow", {
8455
+ workflowId: "locked-workflow",
8456
+ inputData: { value: "x" }
8457
+ });
8458
+ expect(mcpOutcome(result)).toBe("invalid");
8459
+ const httpResult = await http("member-token", "POST", "/workflows/locked-workflow/start-async", { inputData: { value: "x" } });
8460
+ expect(httpResult.status).toBe(403);
8461
+ });
8462
+ });
8463
+ describe("tools parity", () => {
8464
+ it("entity tool returns the same result as POST /tools/:toolId/execute", async () => {
8465
+ const result = await callTool("member-token", "tool_test-tool", { text: "hello" });
8466
+ const httpResult = await http("member-token", "POST", "/tools/test-tool/execute", { data: { text: "hello" } });
8467
+ expect(httpResult.status).toBe(200);
8468
+ expect(mcpOutcome(result)).toBe("ok");
8469
+ expect(payload(result)).toEqual(httpResult.body);
8470
+ });
8471
+ it("runs tools with the RequestContext the /mcp route authenticated", async () => {
8472
+ const result = await callTool("member-token", "tool_whoami", {});
8473
+ expect(payload(result)).toEqual({ userId: "user-member" });
8474
+ });
8475
+ it("denies a tool the caller lacks tools:execute for, over MCP and HTTP", async () => {
8476
+ const result = await callTool("no-tools-token", "tool_test-tool", { text: "x" });
8477
+ expect(mcpOutcome(result)).toBe("not offered");
8478
+ const httpResult = await http("no-tools-token", "POST", "/tools/test-tool/execute", { data: { text: "x" } });
8479
+ expect(httpResult.status).toBe(403);
8480
+ });
8481
+ });
8482
+ });
8483
+ describe(`${suiteName} — enums disabled (enumLimit: 0)`, () => {
8484
+ let server;
8485
+ const clients = [];
8486
+ beforeAll(async () => {
8487
+ server = await startServer(createParityMastra({ enumLimit: 0 }).mastra);
8488
+ });
8489
+ afterAll(async () => {
8490
+ await Promise.all(clients.map((client) => client.disconnect()));
8491
+ await server?.close();
8492
+ });
8493
+ const tools = async (token) => {
8494
+ const client = new MCPClient({
8495
+ id: `mcp-enum-${token}-${clients.length}`,
8496
+ servers: { mastra: {
8497
+ url: new URL(`${server.url}/api/mcp`),
8498
+ requestInit: { headers: { authorization: `Bearer ${token}` } },
8499
+ onToolError: "return"
8500
+ } }
8501
+ });
8502
+ clients.push(client);
8503
+ return client.listTools();
8504
+ };
8505
+ const http = (token, path, body) => fetch(`${server.url}/api${path}`, {
8506
+ method: "POST",
8507
+ headers: {
8508
+ authorization: `Bearer ${token}`,
8509
+ "content-type": "application/json"
8510
+ },
8511
+ body: JSON.stringify(body)
8512
+ });
8513
+ const status = (result) => result.error === true ? "invalid" : result.isError ? Number(/(\d{3}) /.exec(resultText(result))?.[1]) : "ok";
8514
+ it("switches registered tools to list_tools/get_tool/call_tool", async () => {
8515
+ const names = Object.keys(await tools("owner-token")).map((name) => name.replace(/^mastra_/, ""));
8516
+ expect(names).toEqual(expect.arrayContaining([
8517
+ "list_tools",
8518
+ "get_tool",
8519
+ "call_tool"
8520
+ ]));
8521
+ expect(names.some((name) => name.startsWith("tool_"))).toBe(false);
8522
+ });
8523
+ it("denies a FGA-locked agent, workflow, and tool with 403, exactly like HTTP", async () => {
8524
+ const list = await tools("member-token");
8525
+ for (const c of [
8526
+ {
8527
+ tool: "call_agent",
8528
+ args: {
8529
+ agentId: "locked-agent",
8530
+ message: "hi"
8531
+ },
8532
+ path: "/agents/locked-agent/generate",
8533
+ body: { messages: [{
8534
+ role: "user",
8535
+ content: "hi"
8536
+ }] }
8537
+ },
8538
+ {
8539
+ tool: "start_workflow",
8540
+ args: {
8541
+ workflowId: "locked-workflow",
8542
+ inputData: { value: "x" }
8543
+ },
8544
+ path: "/workflows/locked-workflow/start-async",
8545
+ body: { inputData: { value: "x" } }
8546
+ },
8547
+ {
8548
+ tool: "call_tool",
8549
+ args: {
8550
+ toolId: "locked-tool",
8551
+ data: { text: "x" }
8552
+ },
8553
+ path: "/tools/locked-tool/execute",
8554
+ body: { data: { text: "x" } }
8555
+ }
8556
+ ]) {
8557
+ const result = await list[`mastra_${c.tool}`].execute(c.args, {});
8558
+ const httpStatus = (await http("member-token", c.path, c.body)).status;
8559
+ expect(httpStatus).toBe(403);
8560
+ expect(status(result)).toBe(httpStatus);
8561
+ }
8562
+ const ok = await (await tools("owner-token"))["mastra_call_tool"].execute({
8563
+ toolId: "locked-tool",
8564
+ data: { text: "x" }
8565
+ }, {});
8566
+ expect(status(ok)).toBe("ok");
8567
+ });
8568
+ });
8569
+ describe(`${suiteName} — include/exclude match ids and registration keys`, () => {
8570
+ const running = [];
8571
+ const clients = [];
8572
+ afterAll(async () => {
8573
+ await Promise.all(clients.map((client) => client.disconnect()));
8574
+ await Promise.all(running.map((server) => server.close()));
8575
+ });
8576
+ const BY_ID = {
8577
+ agents: ["billing-agent"],
8578
+ workflows: ["greet-workflow"],
8579
+ tools: ["delete-account"]
8580
+ };
8581
+ const BY_KEY = {
8582
+ agents: ["billingAgent"],
8583
+ workflows: ["greetWorkflow"],
8584
+ tools: ["deleteAccountTool"]
8585
+ };
8586
+ const ALIASES = {
8587
+ agent: ["billing-agent", "billingAgent"],
8588
+ workflow: ["greet-workflow", "greetWorkflow"],
8589
+ tool: ["delete-account", "deleteAccountTool"]
8590
+ };
8591
+ const KINDS = [
8592
+ "agent",
8593
+ "workflow",
8594
+ "tool"
8595
+ ];
8596
+ /** Serves the parity app plus one agent, workflow, and tool whose registration key differs from its id. */
8597
+ const serve = async (mcp) => {
8598
+ const { mastra, makeAgent, makeWorkflow, makeTool } = createParityMastra(mcp);
8599
+ mastra.addAgent(makeAgent("billing-agent", "Bills customers"), "billingAgent");
8600
+ mastra.addWorkflow(makeWorkflow("greet-workflow"), "greetWorkflow");
8601
+ mastra.addTool(makeTool("delete-account"), "deleteAccountTool");
8602
+ const started = await startServer(mastra);
8603
+ running.push(started);
8604
+ const client = new MCPClient({
8605
+ id: `mcp-alias-${clients.length}`,
8606
+ servers: { mastra: {
8607
+ url: new URL(`${started.url}/api/mcp`),
8608
+ requestInit: { headers: { authorization: "Bearer owner-token" } },
8609
+ onToolError: "return"
8610
+ } }
8611
+ });
8612
+ clients.push(client);
8613
+ const tools = Object.fromEntries(Object.entries(await client.listTools()).map(([name, tool]) => [name.replace(/^mastra_/, ""), tool]));
8614
+ const run = async (name, args) => tools[name] ? mcpOutcome(await tools[name].execute(args, {})) : "not offered";
8615
+ const listed = async (name, key) => tools[name] ? payload(await tools[name].execute({}, {}))[key].map((e) => e.id) : [];
8616
+ return {
8617
+ names: Object.keys(tools),
8618
+ run,
8619
+ listed,
8620
+ call: {
8621
+ agent: (id) => run("call_agent", {
8622
+ agentId: id,
8623
+ message: "hi"
8624
+ }),
8625
+ workflow: (id) => run("start_workflow", {
8626
+ workflowId: id,
8627
+ inputData: { value: "x" }
8628
+ }),
8629
+ tool: (id) => run("call_tool", {
8630
+ toolId: id,
8631
+ data: { text: "x" }
8632
+ })
8633
+ }
8634
+ };
8635
+ };
8636
+ for (const [label, exclude] of [["by id", BY_ID], ["by registration key", BY_KEY]]) {
8637
+ it(`exclude ${label} hides and refuses every alias above enumLimit`, async () => {
8638
+ const app = await serve({
8639
+ exclude,
8640
+ enumLimit: 0,
8641
+ featured: { agents: BY_KEY.agents }
8642
+ });
8643
+ const aliases = Object.values(ALIASES).flat();
8644
+ for (const [tool, key] of [
8645
+ ["list_agents", "agents"],
8646
+ ["list_workflows", "workflows"],
8647
+ ["list_tools", "tools"]
8648
+ ]) {
8649
+ const ids = await app.listed(tool, key);
8650
+ expect(ids.length).toBeGreaterThan(0);
8651
+ expect(ids.filter((id) => aliases.includes(id))).toEqual([]);
8652
+ }
8653
+ expect(app.names.filter((name) => /billing|greet|delete/i.test(name))).toEqual([]);
8654
+ for (const kind of KINDS) for (const alias of ALIASES[kind]) expect([alias, await app.call[kind](alias)]).toEqual([alias, 404]);
8655
+ });
8656
+ it(`exclude ${label} keeps every alias out of enums, entity tools, and featured tools`, async () => {
8657
+ const app = await serve({
8658
+ exclude,
8659
+ featured: {
8660
+ agents: BY_KEY.agents,
8661
+ workflows: BY_ID.workflows
8662
+ }
8663
+ });
8664
+ expect(app.names).not.toContain("call_tool");
8665
+ expect(app.names.filter((name) => /billing|greet|delete/i.test(name))).toEqual([]);
8666
+ for (const kind of ["agent", "workflow"]) for (const alias of ALIASES[kind]) expect([alias, await app.call[kind](alias)]).toEqual([alias, "invalid"]);
8667
+ });
8668
+ }
8669
+ for (const [label, include] of [["by id", BY_ID], ["by registration key", BY_KEY]]) {
8670
+ it(`include ${label} offers only them, callable by either alias`, async () => {
8671
+ const app = await serve({
8672
+ include,
8673
+ enumLimit: 0
8674
+ });
8675
+ expect(await app.listed("list_agents", "agents")).toEqual(["billing-agent"]);
8676
+ expect(await app.listed("list_workflows", "workflows")).toEqual(["greetWorkflow"]);
8677
+ expect(await app.listed("list_tools", "tools")).toEqual(["delete-account"]);
8678
+ for (const kind of KINDS) for (const alias of ALIASES[kind]) expect([alias, await app.call[kind](alias)]).toEqual([alias, "ok"]);
8679
+ expect(await app.call.agent("test-agent")).toBe(404);
8680
+ expect(await app.call.workflow("test-workflow")).toBe(404);
8681
+ expect(await app.call.tool("test-tool")).toBe(404);
8682
+ });
8683
+ it(`include ${label} names entity and featured tools from the id`, async () => {
8684
+ const app = await serve({
8685
+ include,
8686
+ featured: {
8687
+ agents: include.agents,
8688
+ workflows: include.workflows
8689
+ }
8690
+ });
8691
+ expect(app.names).toEqual(expect.arrayContaining([
8692
+ "agent_billing-agent",
8693
+ "workflow_greet-workflow",
8694
+ "tool_delete-account"
8695
+ ]));
8696
+ expect(app.names.filter((name) => /^(agent|workflow|tool)_/.test(name)).sort()).toEqual([
8697
+ "agent_billing-agent",
8698
+ "tool_delete-account",
8699
+ "workflow_greet-workflow"
8700
+ ]);
8701
+ expect(await app.run("tool_delete-account", { text: "x" })).toBe("ok");
8702
+ expect(await app.run("agent_billing-agent", { message: "hi" })).toBe("ok");
8703
+ });
8704
+ }
8705
+ });
8706
+ describe(`${suiteName} — abort`, () => {
8707
+ it("aborts the agent's model call when the client aborts call_agent", async () => {
8708
+ let modelSignal;
8709
+ let modelStarted;
8710
+ const started = new Promise((resolve) => modelStarted = resolve);
8711
+ const hang = async ({ abortSignal }) => {
8712
+ modelSignal = abortSignal;
8713
+ modelStarted();
8714
+ return new Promise((_, reject) => abortSignal?.addEventListener("abort", () => reject(abortSignal.reason)));
8715
+ };
8716
+ const model = new MastraLanguageModelV2Mock({
8717
+ doGenerate: hang,
8718
+ doStream: hang
8719
+ });
8720
+ const { mastra, memory } = createParityMastra();
8721
+ mastra.addAgent(new Agent({
8722
+ id: "slow-agent",
8723
+ name: "slow-agent",
8724
+ instructions: "x",
8725
+ model,
8726
+ memory
8727
+ }));
8728
+ const running = await startServer(mastra);
8729
+ const client = new MCPClient({
8730
+ id: "mcp-abort",
8731
+ servers: { mastra: {
8732
+ url: new URL(`${running.url}/api/mcp`),
8733
+ requestInit: { headers: { authorization: "Bearer owner-token" } },
8734
+ onToolError: "return"
8735
+ } }
8736
+ });
8737
+ try {
8738
+ const tools = await client.listTools();
8739
+ const controller = new AbortController();
8740
+ const call = tools["mastra_call_agent"].execute({
8741
+ agentId: "slow-agent",
8742
+ message: "hi"
8743
+ }, { abortSignal: controller.signal }).catch((error) => error);
8744
+ await Promise.race([started, call]);
8745
+ expect(modelSignal?.aborted).toBe(false);
8746
+ controller.abort();
8747
+ await call;
8748
+ await expect.poll(() => modelSignal?.aborted, { timeout: 5e3 }).toBe(true);
8749
+ } finally {
8750
+ await client.disconnect();
8751
+ await running.close();
8752
+ }
8753
+ }, 15e3);
8754
+ });
8755
+ describe(`${suiteName} — gating`, () => {
8756
+ const originalDev = process.env.MASTRA_DEV;
8757
+ afterEach(() => {
8758
+ if (originalDev === void 0) delete process.env.MASTRA_DEV;
8759
+ else process.env.MASTRA_DEV = originalDev;
8760
+ });
8761
+ const mcpStatus = async (mastra, path = "/api/mcp", token) => {
8762
+ const started = await startServer(mastra);
8763
+ try {
8764
+ return (await fetch(`${started.url}${path}`, {
8765
+ method: "POST",
8766
+ headers: {
8767
+ "content-type": "application/json",
8768
+ accept: "application/json, text/event-stream",
8769
+ ...token ? { authorization: `Bearer ${token}` } : {}
8770
+ },
8771
+ body: JSON.stringify({
8772
+ jsonrpc: "2.0",
8773
+ id: 1,
8774
+ method: "initialize",
8775
+ params: {
8776
+ protocolVersion: "2025-11-25",
8777
+ capabilities: {},
8778
+ clientInfo: {
8779
+ name: "t",
8780
+ version: "1"
8781
+ }
8782
+ }
8783
+ })
8784
+ })).status;
8785
+ } finally {
8786
+ await started.close();
8787
+ }
8788
+ };
8789
+ it("is not served in a production build without server.auth", async () => {
8790
+ delete process.env.MASTRA_DEV;
8791
+ expect(await mcpStatus(new Mastra$1({ logger: false }))).toBe(404);
8792
+ });
8793
+ it("is served under mastra dev without auth, answering 2025-11-25 clients", async () => {
8794
+ process.env.MASTRA_DEV = "true";
8795
+ expect(await mcpStatus(new Mastra$1({ logger: false }))).toBe(200);
8796
+ });
8797
+ it("is served without auth when enabled explicitly, and never when disabled", async () => {
8798
+ delete process.env.MASTRA_DEV;
8799
+ expect(await mcpStatus(new Mastra$1({
8800
+ logger: false,
8801
+ server: { mcp: { enabled: true } }
8802
+ }))).toBe(200);
8803
+ process.env.MASTRA_DEV = "true";
8804
+ expect(await mcpStatus(new Mastra$1({
8805
+ logger: false,
8806
+ server: { mcp: { enabled: false } }
8807
+ }))).toBe(404);
8808
+ });
8809
+ it("still reads the request body when garbage is collected before the transport runs", async () => {
8810
+ setFlagsFromString("--expose-gc");
8811
+ const collectGarbage = runInNewContext("gc");
8812
+ class CollectingAuth extends SimpleAuth {
8813
+ async authenticateToken(...args) {
8814
+ for (let round = 0; round < 2; round++) {
8815
+ collectGarbage();
8816
+ await new Promise((resolve) => setTimeout(resolve, 20));
8817
+ }
8818
+ return super.authenticateToken(...args);
8819
+ }
8820
+ }
8821
+ const auth = new CollectingAuth({
8822
+ tokens: { ...USERS$1 },
8823
+ mapUserToResourceId: (user) => user.id
8824
+ });
8825
+ const mastra = new Mastra$1({
8826
+ logger: false,
8827
+ server: { auth }
8828
+ });
8829
+ expect(await mcpStatus(mastra, "/api/mcp", Object.keys(USERS$1)[0])).toBe(200);
8830
+ });
8831
+ it("serves at server.mcp.path without shadowing the MCP server registry", async () => {
8832
+ process.env.MASTRA_DEV = "true";
8833
+ const mastra = new Mastra$1({
8834
+ logger: false,
8835
+ server: { mcp: { path: "/tools-mcp" } }
8836
+ });
8837
+ expect(await mcpStatus(mastra, "/api/tools-mcp")).toBe(200);
8838
+ const started = await startServer(mastra);
8839
+ try {
8840
+ expect((await fetch(`${started.url}/api/mcp/v0/servers`)).status).toBe(200);
8841
+ } finally {
8842
+ await started.close();
8843
+ }
8844
+ });
8845
+ });
8846
+ describe(`${suiteName} — Studio descriptor route`, () => {
8847
+ const originalDev = process.env.MASTRA_DEV;
8848
+ afterEach(() => {
8849
+ if (originalDev === void 0) delete process.env.MASTRA_DEV;
8850
+ else process.env.MASTRA_DEV = originalDev;
8851
+ });
8852
+ /** GET /api/mcp/builtin (or `path`) on a freshly served `mastra`. */
8853
+ const describeOn = async (mastra, headers = {}, path = "/api/mcp/builtin") => {
8854
+ const started = await startServer(mastra);
8855
+ try {
8856
+ const response = await fetch(`${started.url}${path}`, { headers });
8857
+ const text = await response.text();
8858
+ return {
8859
+ status: response.status,
8860
+ text,
8861
+ body: text ? JSON.parse(text) : void 0
8862
+ };
8863
+ } finally {
8864
+ await started.close();
8865
+ }
8866
+ };
8867
+ describe("when server.auth and server.rbac are configured", () => {
8868
+ let server;
8869
+ beforeAll(async () => {
8870
+ server = await startServer(createParityMastra().mastra);
8871
+ });
8872
+ afterAll(async () => {
8873
+ await server?.close();
8874
+ });
8875
+ const get = async (headers) => {
8876
+ const response = await fetch(`${server.url}/api/mcp/builtin`, { headers });
8877
+ const text = await response.text();
8878
+ return {
8879
+ status: response.status,
8880
+ text,
8881
+ body: text ? JSON.parse(text) : void 0
8882
+ };
8883
+ };
8884
+ it("describes the endpoint, served toolsets, and auth to an mcp:read caller", async () => {
8885
+ const { status, body } = await get({ authorization: "Bearer owner-token" });
8886
+ expect(status).toBe(200);
8887
+ expect(body).toEqual({
8888
+ enabled: true,
8889
+ path: "/api/mcp",
8890
+ mcpPackageInstalled: true,
8891
+ toolsets: expect.arrayContaining([
8892
+ "agents",
8893
+ "workflows",
8894
+ "tools",
8895
+ "memory"
8896
+ ]),
8897
+ readOnly: false,
8898
+ auth: {
8899
+ type: "protected",
8900
+ provider: null
8901
+ }
8902
+ });
8903
+ expect(body.toolsets).not.toContain("stored_agents");
8904
+ });
8905
+ it("names no agents, workflows, or tools", async () => {
8906
+ const { text } = await get({ authorization: "Bearer owner-token" });
8907
+ for (const id of [
8908
+ "test-agent",
8909
+ "locked-agent",
8910
+ "test-workflow",
8911
+ "locked-workflow",
8912
+ "test-tool",
8913
+ "whoami"
8914
+ ]) expect(text).not.toContain(id);
8915
+ });
8916
+ it("accepts Studio credentials (Studio header and cookie), unlike /api/mcp", async () => {
8917
+ expect((await get({
8918
+ authorization: "Bearer viewer-token",
8919
+ "x-mastra-client-type": "studio"
8920
+ })).status).toBe(200);
8921
+ expect((await get({ cookie: "mastra-token=owner-token" })).status).toBe(200);
8922
+ });
8923
+ it("refuses callers without mcp:read with 403, over bearer and Studio", async () => {
8924
+ expect((await get({ authorization: "Bearer no-mcp-token" })).status).toBe(403);
8925
+ expect((await get({
8926
+ authorization: "Bearer no-mcp-token",
8927
+ "x-mastra-client-type": "studio"
8928
+ })).status).toBe(403);
8929
+ expect((await get({ cookie: "mastra-token=no-mcp-token" })).status).toBe(403);
8930
+ });
8931
+ it("refuses unauthenticated callers with 401", async () => {
8932
+ expect((await get({})).status).toBe(401);
8933
+ });
8934
+ });
8935
+ it("keeps the endpoint bearer-protected, and reported as protected, when auth.public lists its path", async () => {
8936
+ delete process.env.MASTRA_DEV;
8937
+ const auth = new SimpleAuth({
8938
+ tokens: { ...USERS$1 },
8939
+ public: ["/api/mcp", "/api/mcp/builtin"]
8940
+ });
8941
+ const started = await startServer(new Mastra$1({
8942
+ logger: false,
8943
+ server: { auth }
8944
+ }));
8945
+ try {
8946
+ const initialize = (headers) => fetch(`${started.url}/api/mcp`, {
8947
+ method: "POST",
8948
+ headers: {
8949
+ "content-type": "application/json",
8950
+ accept: "application/json, text/event-stream",
8951
+ ...headers
8952
+ },
8953
+ body: JSON.stringify({
8954
+ jsonrpc: "2.0",
8955
+ id: 1,
8956
+ method: "initialize",
8957
+ params: {
8958
+ protocolVersion: "2025-06-18",
8959
+ capabilities: {},
8960
+ clientInfo: {
8961
+ name: "test",
8962
+ version: "1"
8963
+ }
8964
+ }
8965
+ })
8966
+ });
8967
+ expect((await initialize({})).status).toBe(401);
8968
+ expect((await initialize({ authorization: "Bearer owner-token" })).status).toBe(200);
8969
+ expect((await fetch(`${started.url}/api/mcp/builtin`)).status).toBe(401);
8970
+ const descriptor = await fetch(`${started.url}/api/mcp/builtin`, { headers: { authorization: "Bearer owner-token" } });
8971
+ expect((await descriptor.json()).auth).toEqual({
8972
+ type: "protected",
8973
+ provider: null
8974
+ });
8975
+ } finally {
8976
+ await started.close();
8977
+ }
8978
+ });
8979
+ it("reports open dev-only access under mastra dev without auth", async () => {
8980
+ process.env.MASTRA_DEV = "true";
8981
+ const { status, body } = await describeOn(new Mastra$1({ logger: false }));
8982
+ expect(status).toBe(200);
8983
+ expect(body).toEqual({
8984
+ enabled: true,
8985
+ path: "/api/mcp",
8986
+ mcpPackageInstalled: true,
8987
+ toolsets: [
8988
+ "agents",
8989
+ "workflows",
8990
+ "tools",
8991
+ "observability",
8992
+ "observability_analytics"
8993
+ ],
8994
+ readOnly: false,
8995
+ auth: {
8996
+ type: "open",
8997
+ devOnly: true
8998
+ }
8999
+ });
9000
+ });
9001
+ it("reports open access that is not dev-only when enabled explicitly without auth", async () => {
9002
+ delete process.env.MASTRA_DEV;
9003
+ const { body } = await describeOn(new Mastra$1({
9004
+ logger: false,
9005
+ server: { mcp: { enabled: true } }
9006
+ }));
9007
+ expect(body.auth).toEqual({
9008
+ type: "open",
9009
+ devOnly: false
9010
+ });
9011
+ });
9012
+ it("reports only the reason in a production build without server.auth", async () => {
9013
+ delete process.env.MASTRA_DEV;
9014
+ const { status, body } = await describeOn(new Mastra$1({ logger: false }));
9015
+ expect(status).toBe(200);
9016
+ expect(body).toEqual({
9017
+ enabled: false,
9018
+ disabledReason: "production-without-auth"
9019
+ });
9020
+ });
9021
+ it("reports a server disabled by config", async () => {
9022
+ process.env.MASTRA_DEV = "true";
9023
+ const { body } = await describeOn(new Mastra$1({
9024
+ logger: false,
9025
+ server: { mcp: { enabled: false } }
9026
+ }));
9027
+ expect(body).toEqual({
9028
+ enabled: false,
9029
+ disabledReason: "config"
9030
+ });
9031
+ });
9032
+ it("reports server.mcp.path, configured toolsets, and read-only", async () => {
9033
+ process.env.MASTRA_DEV = "true";
9034
+ const { body } = await describeOn(new Mastra$1({
9035
+ logger: false,
9036
+ server: { mcp: {
9037
+ path: "/tools-mcp",
9038
+ toolsets: ["tools", "memory"],
9039
+ readOnly: true
9040
+ } }
9041
+ }));
9042
+ expect(body).toMatchObject({
9043
+ path: "/api/tools-mcp",
9044
+ toolsets: ["tools"],
9045
+ readOnly: true
9046
+ });
9047
+ });
9048
+ it("reports the /mcp fallback when server.mcp.path collides with this route", async () => {
9049
+ process.env.MASTRA_DEV = "true";
9050
+ const { body } = await describeOn(new Mastra$1({
9051
+ logger: false,
9052
+ server: { mcp: { path: "/mcp/builtin" } }
9053
+ }));
9054
+ expect(body.path).toBe("/api/mcp");
9055
+ });
9056
+ it("leaves a user MCP server with the id 'builtin' reachable", async () => {
9057
+ process.env.MASTRA_DEV = "true";
9058
+ const ping = createTool({
9059
+ id: "ping",
9060
+ description: "Answers pong",
9061
+ inputSchema: z$2.object({}),
9062
+ execute: async () => ({ pong: true })
9063
+ });
9064
+ const builtin = new MCPServer({
9065
+ id: "builtin",
9066
+ name: "User builtin",
9067
+ version: "1.0.0",
9068
+ tools: { ping }
9069
+ });
9070
+ const started = await startServer(new Mastra$1({
9071
+ logger: false,
9072
+ mcpServers: { builtin }
9073
+ }));
9074
+ const client = new MCPClient({
9075
+ id: "user-builtin-client",
9076
+ servers: { user: { url: new URL(`${started.url}/api/mcp/builtin/mcp`) } }
9077
+ });
9078
+ try {
9079
+ const servers = await (await fetch(`${started.url}/api/mcp/v0/servers`)).json();
9080
+ expect(servers.servers.map((s) => s.id)).toEqual(["builtin"]);
9081
+ expect(Object.keys(await client.listTools())).toEqual(["user_ping"]);
9082
+ const descriptor = await (await fetch(`${started.url}/api/mcp/builtin`)).json();
9083
+ expect(descriptor.enabled).toBe(true);
9084
+ } finally {
9085
+ await client.disconnect();
9086
+ await started.close();
9087
+ }
9088
+ });
9089
+ });
9090
+ }
9091
+ // src/builtin-mcp-toolsets-test-suite.ts
9092
+ const USERS = {
9093
+ alice: {
9094
+ id: "alice",
9095
+ role: "user"
9096
+ },
9097
+ bob: {
9098
+ id: "bob",
9099
+ role: "user"
9100
+ },
9101
+ "no-obs": {
9102
+ id: "no-obs",
9103
+ role: "no-obs"
9104
+ },
9105
+ reader: {
9106
+ id: "reader",
9107
+ role: "memory-reader"
9108
+ }
9109
+ };
9110
+ const ROLES = [
9111
+ {
9112
+ id: "user",
9113
+ name: "User",
9114
+ permissions: [
9115
+ "*:read",
9116
+ "*:write",
9117
+ "*:execute"
9118
+ ]
9119
+ },
9120
+ {
9121
+ id: "no-obs",
9122
+ name: "No observability",
9123
+ permissions: [
9124
+ "agents:*",
9125
+ "memory:*",
9126
+ "mcp:*"
9127
+ ]
9128
+ },
9129
+ {
9130
+ id: "memory-reader",
9131
+ name: "Memory reader",
9132
+ permissions: [
9133
+ "agents:read",
9134
+ "memory:read",
9135
+ "mcp:*"
9136
+ ]
9137
+ }
9138
+ ];
9139
+ const OBSERVER_DELAY_MS = 1500;
9140
+ const OBSERVED = "User keeps bees on a Lisbon rooftop";
9141
+ const HUGE_OBSERVATIONS_START = "Huge observations: ";
9142
+ /** Most MCP clients drop larger tool results (the server's MAX_RESULT_CHARS). */
9143
+ const MAX_RESULT_CHARS = 4e4;
9144
+ /** A provider-free LanguageModelV2 that answers `text`, optionally after a delay. */
9145
+ function fakeModel(text, delayMs = 0) {
9146
+ const usage = {
9147
+ inputTokens: 50,
9148
+ outputTokens: 20,
9149
+ totalTokens: 70
9150
+ };
9151
+ const wait = () => new Promise((resolve) => setTimeout(resolve, delayMs));
9152
+ return {
9153
+ specificationVersion: "v2",
9154
+ provider: "fake",
9155
+ modelId: "fake-model",
9156
+ supportedUrls: {},
9157
+ doGenerate: async () => {
9158
+ await wait();
9159
+ return {
9160
+ content: [{
9161
+ type: "text",
9162
+ text
9163
+ }],
9164
+ finishReason: "stop",
9165
+ usage,
9166
+ warnings: []
9167
+ };
9168
+ },
9169
+ doStream: async () => {
9170
+ await wait();
9171
+ const parts = [
9172
+ {
9173
+ type: "stream-start",
9174
+ warnings: []
9175
+ },
9176
+ {
9177
+ type: "text-start",
9178
+ id: "t"
9179
+ },
9180
+ {
9181
+ type: "text-delta",
9182
+ id: "t",
9183
+ delta: text
9184
+ },
9185
+ {
9186
+ type: "text-end",
9187
+ id: "t"
9188
+ },
9189
+ {
9190
+ type: "finish",
9191
+ finishReason: "stop",
9192
+ usage
9193
+ }
9194
+ ];
9195
+ return { stream: new ReadableStream({ start(controller) {
9196
+ for (const part of parts) controller.enqueue(part);
9197
+ controller.close();
9198
+ } }) };
9199
+ }
9200
+ };
9201
+ }
9202
+ const OPS = [
9203
+ "aggregate",
9204
+ "breakdown",
9205
+ "timeseries",
9206
+ "percentiles"
9207
+ ];
9208
+ /**
9209
+ * Memory and observability MCP tools must allow and deny exactly what their HTTP routes allow and deny for the
9210
+ * same user, and the multi-route analytics tools must dispatch each `op` to that op's own route.
9211
+ */
9212
+ function createBuiltinMCPToolsetsTestSuite(config) {
9213
+ const { suiteName = "Built-in MCP memory and observability toolsets", startServer } = config;
9214
+ describe(suiteName, () => {
9215
+ let server;
9216
+ let cleanup;
9217
+ const clients = [];
9218
+ beforeAll(async () => {
9219
+ const created = await config.createStorage();
9220
+ cleanup = created.cleanup;
9221
+ const { storage } = created;
9222
+ const agent = (id, scope) => new Agent({
9223
+ id,
9224
+ name: id,
9225
+ instructions: "Test",
9226
+ model: "openai/gpt-4o",
9227
+ memory: config.createMemory(storage, scope)
9228
+ });
9229
+ const mastra = new Mastra$1({
9230
+ logger: false,
9231
+ storage: new MastraCompositeStore({
9232
+ id: "toolsets-suite",
9233
+ default: storage,
9234
+ domains: { observability: await new InMemoryStore().getStore("observability") }
9235
+ }),
9236
+ agents: {
9237
+ "thread-agent": agent("thread-agent", "thread"),
9238
+ "resource-agent": agent("resource-agent", "resource"),
9239
+ "buffer-agent": new Agent({
9240
+ id: "buffer-agent",
9241
+ name: "buffer-agent",
9242
+ instructions: "Test",
9243
+ model: fakeModel("Noted."),
9244
+ memory: config.createMemory(storage, "thread", {
9245
+ model: fakeModel(`<observations>\n* ${OBSERVED}\n</observations>`, OBSERVER_DELAY_MS),
9246
+ observation: {
9247
+ messageTokens: 2e3,
9248
+ bufferTokens: .05
9249
+ }
9250
+ })
9251
+ })
9252
+ },
9253
+ server: {
9254
+ auth: new SimpleAuth({
9255
+ tokens: USERS,
9256
+ mapUserToResourceId: (user) => user.id
9257
+ }),
9258
+ rbac: new StaticRBACProvider({
9259
+ roles: ROLES,
9260
+ getUserRoles: (user) => [user.role]
9261
+ })
9262
+ }
9263
+ });
9264
+ await storage.init();
9265
+ const memoryStore = await storage.getStore("memory");
9266
+ for (const user of ["alice", "bob"]) {
9267
+ const now = /* @__PURE__ */ new Date();
9268
+ await memoryStore.saveThread({ thread: {
9269
+ id: `${user}-thread`,
9270
+ resourceId: user,
9271
+ title: "",
9272
+ metadata: {},
9273
+ createdAt: now,
9274
+ updatedAt: now
9275
+ } });
9276
+ await memoryStore.saveMessages({ messages: [{
9277
+ id: `${user}-message`,
9278
+ threadId: `${user}-thread`,
9279
+ resourceId: user,
9280
+ role: "user",
9281
+ createdAt: now,
9282
+ content: {
9283
+ format: 2,
9284
+ parts: [{
9285
+ type: "text",
9286
+ text: `${user} secret message`
9287
+ }]
9288
+ }
9289
+ }] });
9290
+ for (const [scope, threadId] of [["thread", `${user}-thread`], ["resource", null]]) {
9291
+ const record = await memoryStore.initializeObservationalMemory({
9292
+ threadId,
9293
+ resourceId: user,
9294
+ scope,
9295
+ config: {}
9296
+ });
9297
+ await memoryStore.updateActiveObservations({
9298
+ id: record.id,
9299
+ observations: `${user} ${scope} secret`,
9300
+ tokenCount: 10,
9301
+ lastObservedAt: now
9302
+ });
9303
+ }
9304
+ }
9305
+ const now = /* @__PURE__ */ new Date();
9306
+ await memoryStore.saveThread({ thread: {
9307
+ id: "alice-huge-thread",
9308
+ resourceId: "alice",
9309
+ title: "",
9310
+ metadata: {},
9311
+ createdAt: now,
9312
+ updatedAt: now
9313
+ } });
9314
+ const huge = await memoryStore.initializeObservationalMemory({
9315
+ threadId: "alice-huge-thread",
9316
+ resourceId: "alice",
9317
+ scope: "thread",
9318
+ config: {}
9319
+ });
9320
+ await memoryStore.updateActiveObservations({
9321
+ id: huge.id,
9322
+ observations: `${HUGE_OBSERVATIONS_START}${"o".repeat(6e4)}`,
9323
+ tokenCount: 15e3,
9324
+ lastObservedAt: now
9325
+ });
9326
+ server = await startServer(mastra);
9327
+ for (const [index, value] of [.2, .9].entries()) {
9328
+ const traceId = `signal-trace-${index}`;
9329
+ expect((await http("alice", "POST", "/observability/feedback", { feedback: {
9330
+ traceId,
9331
+ feedbackType: "rating",
9332
+ value
9333
+ } })).status).toBeLessThan(300);
9334
+ expect((await http("alice", "POST", "/observability/scores", { score: {
9335
+ traceId,
9336
+ scorerId: "quality",
9337
+ score: value,
9338
+ entityName: `agent-${index}`
9339
+ } })).status).toBeLessThan(300);
9340
+ }
9341
+ });
9342
+ afterAll(async () => {
9343
+ await Promise.all(clients.map((client) => client.disconnect()));
9344
+ await server?.close();
9345
+ await cleanup?.();
9346
+ });
9347
+ async function http(token, method, path, body) {
9348
+ const response = await fetch(`${server.url}/api${path}`, {
9349
+ method,
9350
+ headers: {
9351
+ authorization: `Bearer ${token}`,
9352
+ ...body !== void 0 ? { "content-type": "application/json" } : {}
9353
+ },
9354
+ ...body !== void 0 ? { body: JSON.stringify(body) } : {}
9355
+ });
9356
+ const text = await response.text();
9357
+ return {
9358
+ status: response.status,
9359
+ body: text ? JSON.parse(text) : void 0
9360
+ };
9361
+ }
9362
+ const connect = (token, headers = {}) => {
9363
+ const client = new MCPClient({
9364
+ id: `toolsets-${token}-${clients.length}`,
9365
+ servers: { mastra: {
9366
+ url: new URL(`${server.url}/api/mcp`),
9367
+ requestInit: { headers: {
9368
+ authorization: `Bearer ${token}`,
9369
+ ...headers
9370
+ } },
9371
+ onToolError: "return"
9372
+ } }
9373
+ });
9374
+ clients.push(client);
9375
+ return client;
9376
+ };
9377
+ const listTools = async (token, headers) => {
9378
+ const tools = await connect(token, headers).listTools();
9379
+ return Object.fromEntries(Object.entries(tools).map(([name, tool]) => [name.replace(/^mastra_/, ""), tool]));
9380
+ };
9381
+ const callTool = async (token, name, args) => {
9382
+ const client = connect(token);
9383
+ try {
9384
+ const tool = (await client.listTools())[`mastra_${name}`];
9385
+ if (!tool) return {
9386
+ isError: true,
9387
+ content: [{ text: `tool ${name} not offered` }]
9388
+ };
9389
+ return await tool.execute(args, {});
9390
+ } finally {
9391
+ await client.disconnect();
9392
+ }
9393
+ };
9394
+ /** The input schema a caller sees in a raw `tools/list`. */
9395
+ const inputSchemaOf = async (token, name, headers = {}) => {
9396
+ const raw = await (await fetch(`${server.url}/api/mcp`, {
9397
+ method: "POST",
9398
+ headers: {
9399
+ authorization: `Bearer ${token}`,
9400
+ "content-type": "application/json",
9401
+ accept: "application/json, text/event-stream",
9402
+ ...headers
9403
+ },
9404
+ body: JSON.stringify({
9405
+ jsonrpc: "2.0",
9406
+ id: 1,
9407
+ method: "tools/list"
9408
+ })
9409
+ })).text();
9410
+ return JSON.parse(raw.startsWith("{") ? raw : /^data: (.*)$/m.exec(raw)[1]).result.tools.find((tool) => tool.name === name)?.inputSchema;
9411
+ };
9412
+ const text = (result) => (result.content ?? []).map((part) => part.text ?? "").join("");
9413
+ const payload = (result) => {
9414
+ if (result.structuredContent !== void 0) return result.structuredContent;
9415
+ if (!Array.isArray(result.content)) return result;
9416
+ return JSON.parse(text(result));
9417
+ };
9418
+ /** `200` for success, else the HTTP status carried in the MCP error, or `not offered`. */
9419
+ const outcome = (result) => {
9420
+ if (result.error === true) return "invalid";
9421
+ if (!result.isError) return 200;
9422
+ if (text(result).includes("not offered")) return "not offered";
9423
+ return Number(/"?(\d{3}) /.exec(text(result))?.[1] ?? 500);
9424
+ };
9425
+ describe("memory ownership parity", () => {
9426
+ const thread = "alice-thread";
9427
+ const cases = [
9428
+ [
9429
+ "get_thread",
9430
+ { threadId: thread },
9431
+ "GET",
9432
+ `/memory/threads/${thread}`
9433
+ ],
9434
+ [
9435
+ "list_messages",
9436
+ { threadId: thread },
9437
+ "GET",
9438
+ `/memory/threads/${thread}/messages`
9439
+ ],
9440
+ [
9441
+ "get_observations",
9442
+ {
9443
+ agentId: "thread-agent",
9444
+ threadId: thread,
9445
+ resourceId: "alice"
9446
+ },
9447
+ "GET",
9448
+ `/memory/observational-memory?agentId=thread-agent&resourceId=alice&threadId=${thread}`
9449
+ ],
9450
+ [
9451
+ "get_observations",
9452
+ {
9453
+ agentId: "thread-agent",
9454
+ threadId: thread,
9455
+ resourceId: "alice",
9456
+ waitForPending: false
9457
+ },
9458
+ "GET",
9459
+ `/memory/observational-memory?agentId=thread-agent&resourceId=alice&threadId=${thread}`
9460
+ ],
9461
+ [
9462
+ "get_observations",
9463
+ {
9464
+ agentId: "thread-agent",
9465
+ threadId: thread,
9466
+ resourceId: "alice",
9467
+ waitForPending: true
9468
+ },
9469
+ "POST",
9470
+ "/memory/observational-memory/buffer-status",
9471
+ {
9472
+ agentId: "thread-agent",
9473
+ threadId: thread,
9474
+ resourceId: "alice"
9475
+ }
9476
+ ],
9477
+ [
9478
+ "get_memory_status",
9479
+ {
9480
+ agentId: "thread-agent",
9481
+ threadId: thread,
9482
+ resourceId: "alice"
9483
+ },
9484
+ "GET",
9485
+ `/memory/status?agentId=thread-agent&resourceId=alice&threadId=${thread}`
9486
+ ],
9487
+ [
9488
+ "update_thread",
9489
+ {
9490
+ agentId: "thread-agent",
9491
+ threadId: thread,
9492
+ title: "renamed"
9493
+ },
9494
+ "PATCH",
9495
+ `/memory/threads/${thread}?agentId=thread-agent`,
9496
+ { title: "renamed" }
9497
+ ],
9498
+ [
9499
+ "clone_thread",
9500
+ {
9501
+ agentId: "thread-agent",
9502
+ threadId: thread
9503
+ },
9504
+ "POST",
9505
+ `/memory/threads/${thread}/clone?agentId=thread-agent`,
9506
+ {}
9507
+ ]
9508
+ ];
9509
+ it.each(cases)("%s %j: the owner's call succeeds, another user's fails with the HTTP status", async (...row) => {
9510
+ const [tool, args, method, path, body] = row;
9511
+ for (const token of ["alice", "bob"]) {
9512
+ const mcp = outcome(await callTool(token, tool, args));
9513
+ const viaHttp = (await http(token, method, path, body)).status;
9514
+ expect({
9515
+ token,
9516
+ mcp
9517
+ }).toEqual({
9518
+ token,
9519
+ mcp: viaHttp
9520
+ });
9521
+ expect(viaHttp === 200).toBe(token === "alice");
9522
+ }
9523
+ });
9524
+ it("resource-scoped observations always resolve to the caller, whatever resourceId is passed", async () => {
9525
+ const result = await callTool("bob", "get_observations", {
9526
+ agentId: "resource-agent",
9527
+ resourceId: "alice"
9528
+ });
9529
+ const viaHttp = await http("bob", "GET", "/memory/observational-memory?agentId=resource-agent&resourceId=alice");
9530
+ expect(viaHttp.status).toBe(200);
9531
+ expect(payload(result).record.activeObservations).toBe("bob resource secret");
9532
+ expect(viaHttp.body.record.activeObservations).toBe("bob resource secret");
9533
+ });
9534
+ it("lists only the caller's threads, like GET /memory/threads", async () => {
9535
+ const result = await callTool("bob", "list_threads", {
9536
+ agentId: "thread-agent",
9537
+ resourceId: "alice"
9538
+ });
9539
+ const viaHttp = await http("bob", "GET", "/memory/threads?agentId=thread-agent&resourceId=alice");
9540
+ const ids = (threads) => threads.map((t) => t.id);
9541
+ expect(ids(payload(result).threads)).toEqual(["bob-thread"]);
9542
+ expect(ids(viaHttp.body.threads)).toEqual(["bob-thread"]);
9543
+ });
9544
+ it("save_messages cannot write into another user's thread", async () => {
9545
+ const message = {
9546
+ id: "intruder",
9547
+ threadId: thread,
9548
+ resourceId: "bob",
9549
+ role: "user",
9550
+ type: "text",
9551
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
9552
+ content: {
9553
+ format: 2,
9554
+ parts: [{
9555
+ type: "text",
9556
+ text: "hi"
9557
+ }]
9558
+ }
9559
+ };
9560
+ const mcp = outcome(await callTool("bob", "save_messages", {
9561
+ agentId: "thread-agent",
9562
+ messages: [message]
9563
+ }));
9564
+ const viaHttp = await http("bob", "POST", "/memory/save-messages?agentId=thread-agent", { messages: [message] });
9565
+ expect(viaHttp.status, JSON.stringify(viaHttp.body)).toBe(403);
9566
+ expect(mcp).toBe(viaHttp.status);
9567
+ });
9568
+ });
9569
+ describe("Observational Memory tools", () => {
9570
+ it("offers get_observations, not the Studio-only history and wait tools", async () => {
9571
+ const names = Object.keys(await listTools("alice"));
9572
+ expect(names).toContain("get_observations");
9573
+ expect(names).toContain("get_memory_status");
9574
+ expect(names).not.toContain("get_observation_history");
9575
+ expect(names).not.toContain("wait_for_observations");
9576
+ const schema = await inputSchemaOf("alice", "get_observations");
9577
+ expect(schema.properties.waitForPending.type).toBe("boolean");
9578
+ });
9579
+ it("get_observations returns the current record without waiting, like GET /memory/observational-memory", async () => {
9580
+ const viaHttp = await http("alice", "GET", "/memory/observational-memory?agentId=thread-agent&resourceId=alice&threadId=alice-thread");
9581
+ for (const args of [{}, { waitForPending: false }]) {
9582
+ const result = payload(await callTool("alice", "get_observations", {
9583
+ agentId: "thread-agent",
9584
+ threadId: "alice-thread",
9585
+ ...args
9586
+ }));
9587
+ expect(result).toEqual({ record: viaHttp.body.record });
9588
+ expect(result.record.activeObservations).toBe("alice thread secret");
9589
+ }
9590
+ });
9591
+ it("waitForPending: true waits for buffering started by call_agent, like POST buffer-status", async () => {
9592
+ const scope = {
9593
+ agentId: "buffer-agent",
9594
+ threadId: "alice-buffered"
9595
+ };
9596
+ const message = `Some facts about me. ${OBSERVED}. `.repeat(20);
9597
+ const called = await callTool("alice", "call_agent", {
9598
+ ...scope,
9599
+ message
9600
+ });
9601
+ expect(outcome(called), text(called)).toBe(200);
9602
+ const pending = payload(await callTool("alice", "get_observations", scope)).record;
9603
+ expect(pending?.isBufferingObservation).toBe(true);
9604
+ expect(JSON.stringify(pending ?? {})).not.toContain(OBSERVED);
9605
+ const done = payload(await callTool("alice", "get_observations", {
9606
+ ...scope,
9607
+ waitForPending: true
9608
+ })).record;
9609
+ expect(done.isBufferingObservation).toBe(false);
9610
+ expect(JSON.stringify(done.bufferedObservationChunks)).toContain(OBSERVED);
9611
+ const viaHttp = await http("alice", "POST", "/memory/observational-memory/buffer-status", scope);
9612
+ expect(viaHttp.status).toBe(200);
9613
+ expect(done).toEqual(viaHttp.body.record);
9614
+ const asBob = {
9615
+ ...scope,
9616
+ resourceId: "alice"
9617
+ };
9618
+ const bobHttp = {
9619
+ false: await http("bob", "GET", `/memory/observational-memory?${new URLSearchParams(asBob)}`),
9620
+ true: await http("bob", "POST", "/memory/observational-memory/buffer-status", asBob)
9621
+ };
9622
+ for (const waitForPending of [false, true]) {
9623
+ const bob = await callTool("bob", "get_observations", {
9624
+ ...asBob,
9625
+ waitForPending
9626
+ });
9627
+ expect(bobHttp[`${waitForPending}`].status).toBe(403);
9628
+ expect(outcome(bob)).toBe(bobHttp[`${waitForPending}`].status);
9629
+ expect(text(bob)).not.toContain(OBSERVED);
9630
+ }
9631
+ });
9632
+ it("get_observations clips an oversized record to fit one tool result; HTTP keeps it whole", async () => {
9633
+ const scope = {
9634
+ agentId: "thread-agent",
9635
+ threadId: "alice-huge-thread"
9636
+ };
9637
+ const viaHttp = await http("alice", "GET", `/memory/observational-memory?${new URLSearchParams(scope)}`);
9638
+ expect(viaHttp.status).toBe(200);
9639
+ expect(viaHttp.body.record.activeObservations).toHaveLength(60019);
9640
+ for (const waitForPending of [false, true]) {
9641
+ const result = await callTool("alice", "get_observations", {
9642
+ ...scope,
9643
+ waitForPending
9644
+ });
9645
+ expect(outcome(result), text(result)).toBe(200);
9646
+ expect(text(result).length).toBeLessThanOrEqual(MAX_RESULT_CHARS);
9647
+ const { record } = payload(result);
9648
+ expect(record.id).toBe(viaHttp.body.record.id);
9649
+ expect(record.activeObservations.startsWith(HUGE_OBSERVATIONS_START)).toBe(true);
9650
+ expect(record.activeObservations).toMatch(/\[truncated \d+ chars\]$/);
9651
+ }
9652
+ });
9653
+ it("a memory:read caller gets get_observations without waitForPending, and cannot wait (buffer-status is 403)", async () => {
9654
+ const path = "/memory/observational-memory?agentId=resource-agent";
9655
+ expect(Object.keys(await listTools("reader"))).toContain("get_observations");
9656
+ expect((await inputSchemaOf("reader", "get_observations")).properties).not.toHaveProperty("waitForPending");
9657
+ const viaHttp = await http("reader", "GET", path);
9658
+ expect(viaHttp.status).toBe(200);
9659
+ const result = await callTool("reader", "get_observations", { agentId: "resource-agent" });
9660
+ expect(payload(result)).toEqual({ record: viaHttp.body.record });
9661
+ const waited = await callTool("reader", "get_observations", {
9662
+ agentId: "resource-agent",
9663
+ waitForPending: true
9664
+ });
9665
+ expect(outcome(waited)).toBe("invalid");
9666
+ expect((await http("reader", "POST", "/memory/observational-memory/buffer-status", { agentId: "resource-agent" })).status).toBe(403);
9667
+ });
9668
+ });
9669
+ describe("read-only mode", () => {
9670
+ it("keeps get_observations without waitForPending", async () => {
9671
+ const readonly = { "x-mcp-readonly": "1" };
9672
+ expect((await inputSchemaOf("alice", "get_observations", readonly)).properties).not.toHaveProperty("waitForPending");
9673
+ const tool = (await connect("alice", readonly).listTools()).mastra_get_observations;
9674
+ const scope = {
9675
+ agentId: "thread-agent",
9676
+ threadId: "alice-thread"
9677
+ };
9678
+ const result = await tool.execute(scope, {});
9679
+ expect(payload(result).record.activeObservations).toBe("alice thread secret");
9680
+ const waited = await tool.execute({
9681
+ ...scope,
9682
+ waitForPending: true
9683
+ }, {});
9684
+ expect(outcome(waited)).toBe("invalid");
9685
+ });
9686
+ it("keeps POST-backed observability reads and drops memory writes", async () => {
9687
+ const tools = await listTools("alice", { "x-mcp-readonly": "1" });
9688
+ const names = Object.keys(tools);
9689
+ for (const name of [
9690
+ "analyze_metrics",
9691
+ "analyze_feedback",
9692
+ "list_threads",
9693
+ "get_observations"
9694
+ ]) {
9695
+ expect(names).toContain(name);
9696
+ expect(tools[name].mcp?.annotations?.readOnlyHint ?? true).toBe(true);
9697
+ }
9698
+ for (const name of [
9699
+ "create_thread",
9700
+ "update_thread",
9701
+ "clone_thread",
9702
+ "save_messages"
9703
+ ]) expect(names).not.toContain(name);
9704
+ });
9705
+ });
9706
+ describe("observability analytics dispatch", () => {
9707
+ const bodies = {
9708
+ feedback: {
9709
+ aggregate: {
9710
+ feedbackType: "rating",
9711
+ aggregation: "avg"
9712
+ },
9713
+ breakdown: {
9714
+ feedbackType: "rating",
9715
+ aggregation: "avg",
9716
+ groupBy: ["feedbackSource"]
9717
+ },
9718
+ timeseries: {
9719
+ feedbackType: "rating",
9720
+ aggregation: "avg",
9721
+ interval: "1h"
9722
+ },
9723
+ percentiles: {
9724
+ feedbackType: "rating",
9725
+ percentiles: [.5],
9726
+ interval: "1h"
9727
+ }
9728
+ },
9729
+ scores: {
9730
+ aggregate: {
9731
+ scorerId: "quality",
9732
+ aggregation: "avg"
9733
+ },
9734
+ breakdown: {
9735
+ scorerId: "quality",
9736
+ aggregation: "avg",
9737
+ groupBy: ["entityName"]
9738
+ },
9739
+ timeseries: {
9740
+ scorerId: "quality",
9741
+ aggregation: "avg",
9742
+ interval: "1h"
9743
+ },
9744
+ percentiles: {
9745
+ scorerId: "quality",
9746
+ percentiles: [.5],
9747
+ interval: "1h"
9748
+ }
9749
+ },
9750
+ metrics: {
9751
+ aggregate: {
9752
+ name: ["mastra_agent_duration_ms"],
9753
+ aggregation: "sum"
9754
+ },
9755
+ breakdown: {
9756
+ name: ["mastra_agent_duration_ms"],
9757
+ aggregation: "sum",
9758
+ groupBy: ["entityName"]
9759
+ },
9760
+ timeseries: {
9761
+ name: ["mastra_agent_duration_ms"],
9762
+ aggregation: "sum",
9763
+ interval: "1h"
9764
+ },
9765
+ percentiles: {
9766
+ name: "mastra_agent_duration_ms",
9767
+ percentiles: [.5],
9768
+ interval: "1h"
9769
+ }
9770
+ }
9771
+ };
9772
+ for (const source of Object.keys(bodies)) it.each(OPS)(`analyze_${source} op %s returns what its own route returns`, async (op) => {
9773
+ const body = bodies[source][op];
9774
+ const viaHttp = await http("alice", "POST", `/observability/${source}/${op}`, body);
9775
+ expect(viaHttp.status).toBe(200);
9776
+ const result = await callTool("alice", `analyze_${source}`, {
9777
+ op,
9778
+ ...body
9779
+ });
9780
+ expect(outcome(result)).toBe(200);
9781
+ expect(payload(result)).toEqual(viaHttp.body);
9782
+ if (op === "aggregate") {
9783
+ const breakdown = await http("alice", "POST", `/observability/${source}/breakdown`, bodies[source].breakdown);
9784
+ expect(breakdown.body).not.toEqual(viaHttp.body);
9785
+ }
9786
+ });
9787
+ it("list_metric_names answers each level from its discovery route", async () => {
9788
+ for (const [args, path] of [
9789
+ [{}, "/observability/discovery/metric-names"],
9790
+ [{ metricName: "mastra_agent_duration_ms" }, "/observability/discovery/metric-label-keys?metricName=mastra_agent_duration_ms"],
9791
+ [{
9792
+ metricName: "mastra_agent_duration_ms",
9793
+ labelKey: "status"
9794
+ }, "/observability/discovery/metric-label-values?metricName=mastra_agent_duration_ms&labelKey=status"]
9795
+ ]) {
9796
+ const viaHttp = await http("alice", "GET", path);
9797
+ expect(viaHttp.status).toBe(200);
9798
+ expect(payload(await callTool("alice", "list_metric_names", args))).toEqual(viaHttp.body);
9799
+ }
9800
+ expect(outcome(await callTool("alice", "list_metric_names", { labelKey: "status" }))).toBe(400);
9801
+ });
9802
+ it("offers no observability tools without observability:read, and every op route answers 403", async () => {
9803
+ const names = Object.keys(await listTools("no-obs"));
9804
+ expect(names).toContain("list_threads");
9805
+ expect(names.filter((name) => /trace|span|log|metric|score|feedback/.test(name))).toEqual([]);
9806
+ for (const source of Object.keys(bodies)) for (const op of OPS) expect((await http("no-obs", "POST", `/observability/${source}/${op}`, bodies[source][op])).status).toBe(403);
9807
+ });
9808
+ });
9809
+ });
9810
+ }
9811
+ // src/knowledge-routes-test-suite.ts
9812
+ /**
9813
+ * The opt-in Knowledge routes on every adapter: RBAC `knowledge:read` gates them, the Knowledge principals
9814
+ * `authorize` sets through `context.get('requestContext')` reach the handler (no mapping is refused), and a
9815
+ * repeated query param (`scopeId`) arrives as a list.
9816
+ */
9817
+ function createKnowledgeRoutesTestSuite(config) {
9818
+ const { suiteName = "Knowledge routes", startServer } = config;
9819
+ describe(suiteName, () => {
9820
+ let close;
9821
+ afterEach(async () => {
9822
+ await close?.();
9823
+ close = void 0;
9824
+ });
9825
+ const setup = async () => {
9826
+ const knowledge = new Knowledge({
9827
+ id: "kb",
9828
+ scopes: {},
9829
+ storage: new InMemoryStore({ id: "kb" })
9830
+ });
9831
+ const store = await knowledge.getStorage();
9832
+ const provenance = { author: "test" };
9833
+ const scopes = {};
9834
+ for (const [team, page] of [
9835
+ ["support", "Payments runbook"],
9836
+ ["eng", "Payments service"],
9837
+ ["sales", "Payments pricing"]
9838
+ ]) {
9839
+ const { scope } = await store.materializeScope({
9840
+ address: `team:${team}`,
9841
+ declaration: "team:$teamId",
9842
+ name: team,
9843
+ provenance
9844
+ });
9845
+ scopes[team] = scope.id;
9846
+ await store.createPage({
9847
+ parentId: scope.id,
9848
+ name: page,
9849
+ provenance
9850
+ });
9851
+ }
9852
+ const permissions = {
9853
+ "reader-token": ["knowledge:read"],
9854
+ "unmapped-token": ["knowledge:read"],
9855
+ "other-token": []
9856
+ };
9857
+ const mastra = new Mastra({
9858
+ logger: false,
9859
+ knowledge: { main: knowledge },
9860
+ server: { apiRoutes: [...KNOWLEDGE_ROUTES] }
9861
+ });
9862
+ const originalGetServer = mastra.getServer.bind(mastra);
9863
+ mastra.getServer = () => ({
9864
+ ...originalGetServer(),
9865
+ rbac: {
9866
+ getRoles: async () => ["member"],
9867
+ getPermissions: async (user) => permissions[user.id] ?? []
9868
+ },
9869
+ auth: {
9870
+ authenticateToken: async (token) => token in permissions ? { id: token } : null,
9871
+ authorize: async (_path, _method, user, context) => {
9872
+ if (user.id === "reader-token") context.get("requestContext").set(MASTRA_KNOWLEDGE_PRINCIPALS_KEY, "all");
9873
+ return true;
9874
+ }
9875
+ }
9876
+ });
9877
+ const server = await startServer(mastra);
9878
+ close = server.close;
9879
+ const get = (path, token) => server.request(`/api/knowledge/main${path}`, token ? { headers: { authorization: `Bearer ${token}` } } : {});
9880
+ return {
9881
+ get,
9882
+ scopes
9883
+ };
9884
+ };
9885
+ it("serves a reader authorize mapped to Knowledge principals and refuses everyone else", async () => {
9886
+ const { get } = await setup();
9887
+ const roots = await get("/tree", "reader-token");
9888
+ expect(roots.status).toBe(200);
9889
+ const body = await roots.json();
9890
+ expect(body.pages.map((page) => page.name).sort()).toEqual([
9891
+ "eng",
9892
+ "sales",
9893
+ "support"
9894
+ ]);
9895
+ expect((await get("/tree", "unmapped-token")).status).toBe(403);
9896
+ expect((await get("/tree", "other-token")).status).toBe(403);
9897
+ expect((await get("/tree")).status).toBe(401);
9898
+ });
9899
+ it("reads a repeated scopeId param as a list", async () => {
9900
+ const { get, scopes } = await setup();
9901
+ const res = await get(`/search?q=payments&scopeId=${scopes.support}&scopeId=${scopes.eng}`, "reader-token");
9902
+ expect(res.status).toBe(200);
9903
+ const body = await res.json();
9904
+ expect(body.results.map((hit) => hit.page.name).sort()).toEqual(["Payments runbook", "Payments service"]);
9905
+ });
9906
+ });
9907
+ }
9908
+ // src/observability-signal-write-test-suite.ts
9909
+ /** Shared HTTP contract for feedback/score writes, backed by real in-memory storage. */
9910
+ function createObservabilitySignalWriteTestSuite({ startServer }) {
9911
+ describe.each(["feedback", "scores"])("%s HTTP writes", (collection) => {
9912
+ let server;
9913
+ let store;
9914
+ let trustedScope;
9915
+ let allowAccess;
9916
+ let authorLookupFails;
9917
+ const isFeedback = collection === "feedback";
9918
+ const field = isFeedback ? "feedback" : "score";
9919
+ const idField = isFeedback ? "feedbackId" : "scoreId";
9920
+ const payload = isFeedback ? {
9921
+ feedbackType: "thumbs",
9922
+ value: 1
9923
+ } : {
9924
+ scorerId: "accuracy",
9925
+ score: .9
9926
+ };
9927
+ const path = `/api/observability/${collection}`;
9928
+ beforeEach(async () => {
9929
+ trustedScope = {};
9930
+ allowAccess = true;
9931
+ authorLookupFails = false;
9932
+ const storage = new InMemoryStore();
9933
+ store = await storage.getStore("observability");
9934
+ server = await startServer(new Mastra({
9935
+ storage,
9936
+ logger: false,
9937
+ server: { auth: {
9938
+ authenticateToken: async () => ({}),
9939
+ getCurrentUser: async () => null,
9940
+ getUser: async (id) => {
9941
+ if (authorLookupFails) throw new Error("Directory unavailable");
9942
+ return id === "author-1" ? {
9943
+ id,
9944
+ name: "Alice",
9945
+ email: "alice@example.com",
9946
+ secret: "private"
9947
+ } : null;
9948
+ },
9949
+ authorize: async (_path, _method, _user, c) => {
9950
+ for (const [key, value] of Object.entries(trustedScope)) c.get("requestContext").set(key, value);
9951
+ return allowAccess;
9952
+ }
9953
+ } }
9954
+ }));
9955
+ });
9956
+ afterEach(async () => {
9957
+ await server?.close();
6686
9958
  });
6687
9959
  const post = (record, contextMode) => server.request(path, {
6688
9960
  method: "POST",
@@ -6719,6 +9991,52 @@ function createObservabilitySignalWriteTestSuite({ startServer }) {
6719
9991
  contextMode
6720
9992
  })
6721
9993
  });
9994
+ const patchReview = (id, reviewStatus) => server.request(`${path}/${id}/review-status`, {
9995
+ method: "PATCH",
9996
+ headers: {
9997
+ "Content-Type": "application/json",
9998
+ authorization: "Bearer test-token"
9999
+ },
10000
+ body: JSON.stringify({ reviewStatus })
10001
+ });
10002
+ it("keeps local review updates working with older observability lacking export notification", async () => {
10003
+ await post(original);
10004
+ const response = await patchReview("edit", "reviewed");
10005
+ expect(response.status).toBe(200);
10006
+ expect(await response.json()).toMatchObject({
10007
+ ...original,
10008
+ reviewStatus: "reviewed"
10009
+ });
10010
+ });
10011
+ it("does not use organization metadata to scope review updates", async () => {
10012
+ await post({
10013
+ ...original,
10014
+ organizationId: "record-org"
10015
+ });
10016
+ trustedScope.organizationId = "request-org";
10017
+ const response = await patchReview("edit", "reviewed");
10018
+ expect(response.status).toBe(200);
10019
+ expect(await response.json()).toMatchObject({
10020
+ organizationId: "record-org",
10021
+ reviewStatus: "reviewed"
10022
+ });
10023
+ expect((await store.getFeedbackById("edit"))?.reviewStatus).toBe("reviewed");
10024
+ });
10025
+ it("does not update missing feedback or feedback outside the configured resource", async () => {
10026
+ expect((await patchReview("missing", "reviewed")).status).toBe(404);
10027
+ await post({
10028
+ ...original,
10029
+ resourceId: "foreign"
10030
+ });
10031
+ trustedScope.mastra__resourceId = "trusted";
10032
+ expect((await patchReview("edit", "reviewed")).status).toBe(404);
10033
+ expect((await store.getFeedbackById("edit"))?.reviewStatus).toBe("needs-review");
10034
+ });
10035
+ it.each([null, "invalid"])("rejects invalid review status %s without changing feedback", async (status) => {
10036
+ await post(original);
10037
+ expect((await patchReview("edit", status)).status).toBe(400);
10038
+ expect((await store.getFeedbackById("edit"))?.reviewStatus).toBe("needs-review");
10039
+ });
6722
10040
  it.each([
6723
10041
  { feedbackId: "other" },
6724
10042
  { timestamp: void 0 },
@@ -7270,6 +10588,93 @@ function createObservabilitySignalWriteTestSuite({ startServer }) {
7270
10588
  })]);
7271
10589
  });
7272
10590
  });
10591
+ describe("feedback review-status export delivery", () => {
10592
+ it.each(["flush", "shutdown"])("persists HTTP review changes before exporting and drains on %s", async (lifecycle) => {
10593
+ const writes = [];
10594
+ const responses = [];
10595
+ const receiver = createServer(async (req, res) => {
10596
+ const chunks = [];
10597
+ for await (const chunk of req) chunks.push(Buffer.from(chunk));
10598
+ writes.push({
10599
+ method: req.method,
10600
+ path: req.url,
10601
+ body: JSON.parse(Buffer.concat(chunks).toString())
10602
+ });
10603
+ responses.push(res);
10604
+ });
10605
+ receiver.listen(0, "127.0.0.1");
10606
+ await once(receiver, "listening");
10607
+ const address = receiver.address();
10608
+ if (!address || typeof address === "string") throw new Error("Expected TCP listener");
10609
+ const storage = new InMemoryStore();
10610
+ const store = await storage.getStore("observability");
10611
+ const original = {
10612
+ feedbackId: "review/id",
10613
+ timestamp: /* @__PURE__ */ new Date(),
10614
+ traceId: "trace",
10615
+ feedbackType: "comment",
10616
+ value: "actionable",
10617
+ feedbackUserId: "author",
10618
+ comment: "keep",
10619
+ tags: ["original"],
10620
+ metadata: { detail: true },
10621
+ reviewStatus: "needs-review"
10622
+ };
10623
+ await store.createFeedback({ feedback: original });
10624
+ const observability = new Observability({ configs: { default: {
10625
+ serviceName: "review",
10626
+ exporters: [new MastraStorageExporter(), new MastraPlatformExporter({
10627
+ accessToken: "test",
10628
+ endpoint: `http://127.0.0.1:${address.port}`,
10629
+ resolveFromEnv: false
10630
+ })]
10631
+ } } });
10632
+ const server = await startServer(new Mastra({
10633
+ storage,
10634
+ observability,
10635
+ logger: false
10636
+ }));
10637
+ try {
10638
+ const response = await server.request("/api/observability/feedback/review%2Fid/review-status", {
10639
+ method: "PATCH",
10640
+ headers: { "Content-Type": "application/json" },
10641
+ body: JSON.stringify({ reviewStatus: "reviewed" }),
10642
+ signal: AbortSignal.timeout(2e3)
10643
+ });
10644
+ expect(response.status, await response.clone().text()).toBe(200);
10645
+ expect(await response.json()).toMatchObject({
10646
+ ...original,
10647
+ timestamp: original.timestamp.toISOString(),
10648
+ reviewStatus: "reviewed"
10649
+ });
10650
+ expect(await store.getFeedbackById(original.feedbackId)).toMatchObject({
10651
+ ...original,
10652
+ reviewStatus: "reviewed"
10653
+ });
10654
+ await expect.poll(() => writes.length, { timeout: 1500 }).toBe(1);
10655
+ expect(writes).toEqual([{
10656
+ method: "PATCH",
10657
+ path: "/api/observability/feedback/review%2Fid/review-status",
10658
+ body: { reviewStatus: "reviewed" }
10659
+ }]);
10660
+ let drained = false;
10661
+ const pending = observability[lifecycle]().then(() => {
10662
+ drained = true;
10663
+ });
10664
+ await new Promise((resolve) => setTimeout(resolve, 25));
10665
+ expect(drained).toBe(false);
10666
+ for (const res of responses) res.writeHead(204).end();
10667
+ await pending;
10668
+ expect((await store.listFeedback({})).feedback).toHaveLength(1);
10669
+ } finally {
10670
+ for (const res of responses) if (!res.writableEnded) res.writeHead(204).end();
10671
+ await observability.shutdown();
10672
+ await server.close();
10673
+ receiver.closeAllConnections();
10674
+ await new Promise((resolve) => receiver.close(() => resolve()));
10675
+ }
10676
+ });
10677
+ });
7273
10678
  describe.each(["feedback", "scores"])("%s HTTP export delivery", (collection) => {
7274
10679
  it.each(["flush", "shutdown"])("returns HTTP success before a custom exporter completes and drains delivery on %s", async (lifecycle) => {
7275
10680
  const accepted = [];
@@ -7811,6 +11216,6 @@ function createCustomRouteDisconnectTestSuite(config) {
7811
11216
  }, 2e4);
7812
11217
  });
7813
11218
  }
7814
- export { consumeSSEStream, createBodyLimitTestSuite, createCustomRouteDisconnectTestSuite, createCustomRouteFGATestSuite, createDefaultTestContext, createDurableDisconnectTestSuite, createHttpLoggingTestSuite, createKnowledgeRoutesTestSuite, createMCPRouteTestSuite, createMCPTransportTestSuite, createMultipartTestSuite, createObservabilitySignalWriteTestSuite, createRouteAdapterTestSuite, createStreamDisconnectTestSuite, createStreamWithSensitiveData, createStreamWithUnserializableChunk, createStructuredWakeTestSuite, expectSerializedStreamChunks };
11219
+ export { consumeSSEStream, createBodyLimitTestSuite, createBuiltinMCPOAuthTestSuite, createBuiltinMCPParityTestSuite, createBuiltinMCPToolsetsTestSuite, createCustomRouteDisconnectTestSuite, createCustomRouteFGATestSuite, createDefaultTestContext, createDurableDisconnectTestSuite, createHttpLoggingTestSuite, createKnowledgeRoutesTestSuite, createMCPRouteTestSuite, createMCPTransportTestSuite, createMultipartTestSuite, createObservabilitySignalWriteTestSuite, createRouteAdapterTestSuite, createRouteDispatchParityTestSuite, createStreamDisconnectTestSuite, createStreamWithSensitiveData, createStreamWithUnserializableChunk, createStructuredWakeTestSuite, expectSerializedStreamChunks };
7815
11220
 
7816
11221
  //# sourceMappingURL=index.js.map