@mastra/server-adapters-test-suite 0.2.1 → 0.3.0-alpha.1
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/CHANGELOG.md +38 -0
- package/dist/durable-disconnect-test-suite.d.ts +5 -0
- package/dist/durable-disconnect-test-suite.d.ts.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1217 -11
- package/dist/index.js.map +1 -1
- package/dist/legacy-sse-fixture.d.ts +52 -0
- package/dist/legacy-sse-fixture.d.ts.map +1 -0
- package/dist/mcp-transport-test-suite.d.ts.map +1 -1
- package/dist/observability-signal-write-test-suite.d.ts +10 -0
- package/dist/observability-signal-write-test-suite.d.ts.map +1 -0
- package/dist/stream-disconnect-test-suite.d.ts +24 -0
- package/dist/stream-disconnect-test-suite.d.ts.map +1 -0
- package/dist/test-helpers.d.ts +1 -1
- package/dist/test-helpers.d.ts.map +1 -1
- package/package.json +6 -6
package/dist/index.js
CHANGED
|
@@ -7,7 +7,7 @@ import * as zod from "zod";
|
|
|
7
7
|
import { z } from "zod";
|
|
8
8
|
import { z as z$1 } from "zod/v3";
|
|
9
9
|
import { getZodDef, getZodTypeName, makeCoreTool } from "@mastra/core/utils";
|
|
10
|
-
import { randomUUID } from "crypto";
|
|
10
|
+
import { randomBytes, randomUUID } from "crypto";
|
|
11
11
|
import * as fs from "fs";
|
|
12
12
|
import * as os from "os";
|
|
13
13
|
import * as path from "path";
|
|
@@ -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 { InMemoryStore } from "@mastra/core/storage";
|
|
20
|
+
import { EntityType, InMemoryStore } 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";
|
|
@@ -25,7 +25,7 @@ import { CompositeVoice } from "@mastra/core/voice";
|
|
|
25
25
|
import { createStep, createWorkflow } from "@mastra/core/workflows";
|
|
26
26
|
import { LocalFilesystem, Workspace } from "@mastra/core/workspace";
|
|
27
27
|
import { MCPClient, MCPServer, defineEvent } from "@mastra/mcp";
|
|
28
|
-
import { AGENT_STREAM_TOPIC, createDurableAgent, createDurableAgentStream, createEventedAgent } from "@mastra/core/agent/durable";
|
|
28
|
+
import { AGENT_STREAM_TOPIC, DurableStepIds, createDurableAgent, createDurableAgentStream, createEventedAgent } from "@mastra/core/agent/durable";
|
|
29
29
|
import { Mastra as Mastra$1 } from "@mastra/core/mastra";
|
|
30
30
|
import http from "http";
|
|
31
31
|
import { MCPServerBase } from "@mastra/core/mcp";
|
|
@@ -3152,6 +3152,34 @@ function deferred() {
|
|
|
3152
3152
|
resolve
|
|
3153
3153
|
};
|
|
3154
3154
|
}
|
|
3155
|
+
async function persistReplayOwner(mastra, runId, agentId) {
|
|
3156
|
+
const workflows = await mastra.getStorage().getStore("workflows");
|
|
3157
|
+
const input = {
|
|
3158
|
+
agentId,
|
|
3159
|
+
status: "success",
|
|
3160
|
+
output: {},
|
|
3161
|
+
payload: {},
|
|
3162
|
+
startedAt: Date.now(),
|
|
3163
|
+
endedAt: Date.now()
|
|
3164
|
+
};
|
|
3165
|
+
await workflows.persistWorkflowSnapshot({
|
|
3166
|
+
workflowName: DurableStepIds.AGENTIC_LOOP,
|
|
3167
|
+
runId,
|
|
3168
|
+
snapshot: {
|
|
3169
|
+
runId,
|
|
3170
|
+
status: "success",
|
|
3171
|
+
value: {},
|
|
3172
|
+
context: { input },
|
|
3173
|
+
activePaths: [],
|
|
3174
|
+
activeStepsPath: {},
|
|
3175
|
+
serializedStepGraph: [],
|
|
3176
|
+
suspendedPaths: {},
|
|
3177
|
+
resumeLabels: {},
|
|
3178
|
+
waitingPaths: {},
|
|
3179
|
+
timestamp: Date.now()
|
|
3180
|
+
}
|
|
3181
|
+
});
|
|
3182
|
+
}
|
|
3155
3183
|
async function collectPublicFrames(response, onFrame) {
|
|
3156
3184
|
const frames = [];
|
|
3157
3185
|
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
|
|
@@ -3357,6 +3385,15 @@ function createDurableDisconnectTestSuite(config) {
|
|
|
3357
3385
|
} finally {
|
|
3358
3386
|
await reference.cleanup();
|
|
3359
3387
|
}
|
|
3388
|
+
const observe = () => fetch(`${server.baseUrl}/api/agents/agent/observe`, {
|
|
3389
|
+
method: "POST",
|
|
3390
|
+
headers: { "content-type": "application/json" },
|
|
3391
|
+
body: JSON.stringify({ runId })
|
|
3392
|
+
});
|
|
3393
|
+
expect((await observe()).status).toBe(404);
|
|
3394
|
+
await persistReplayOwner(mastra, runId, "another-agent");
|
|
3395
|
+
expect((await observe()).status).toBe(403);
|
|
3396
|
+
await persistReplayOwner(mastra, runId, agent.id);
|
|
3360
3397
|
for (const offset of [
|
|
3361
3398
|
0,
|
|
3362
3399
|
1,
|
|
@@ -3374,6 +3411,16 @@ function createDurableDisconnectTestSuite(config) {
|
|
|
3374
3411
|
expect(await collectPublicFrames(response)).toEqual(expected);
|
|
3375
3412
|
}
|
|
3376
3413
|
expect(expected).toHaveLength(terminal === "error" ? 1 : 2);
|
|
3414
|
+
expect(expected.map((frame) => frame.index)).toEqual(terminal === "error" ? [2] : [void 0, 2]);
|
|
3415
|
+
const pastEnd = await fetch(`${server.baseUrl}/api/agents/agent/observe`, {
|
|
3416
|
+
method: "POST",
|
|
3417
|
+
headers: { "content-type": "application/json" },
|
|
3418
|
+
body: JSON.stringify({
|
|
3419
|
+
runId,
|
|
3420
|
+
offset: 3
|
|
3421
|
+
})
|
|
3422
|
+
});
|
|
3423
|
+
expect(await collectPublicFrames(pastEnd)).toEqual([]);
|
|
3377
3424
|
if (config.observeWithClient) expect(await config.observeWithClient(server.baseUrl, runId)).toEqual(expected);
|
|
3378
3425
|
});
|
|
3379
3426
|
it("preserves finish metadata after a model error chunk (COR-1498)", async () => {
|
|
@@ -3391,6 +3438,7 @@ function createDurableDisconnectTestSuite(config) {
|
|
|
3391
3438
|
});
|
|
3392
3439
|
server = await config.startServer(mastra, () => {});
|
|
3393
3440
|
const runId = `observe-model-error-${kind}`;
|
|
3441
|
+
await persistReplayOwner(mastra, runId, agent.id);
|
|
3394
3442
|
const usage = {
|
|
3395
3443
|
inputTokens: 1,
|
|
3396
3444
|
outputTokens: 2,
|
|
@@ -3490,6 +3538,7 @@ function createDurableDisconnectTestSuite(config) {
|
|
|
3490
3538
|
});
|
|
3491
3539
|
server = await config.startServer(mastra, () => {});
|
|
3492
3540
|
const runId = `observe-usage-${kind}-${explicit}`;
|
|
3541
|
+
await persistReplayOwner(mastra, runId, agent.id);
|
|
3493
3542
|
const usage = {
|
|
3494
3543
|
inputTokens: 1,
|
|
3495
3544
|
outputTokens: 2,
|
|
@@ -3579,6 +3628,7 @@ function createDurableDisconnectTestSuite(config) {
|
|
|
3579
3628
|
});
|
|
3580
3629
|
server = await config.startServer(mastra, () => {});
|
|
3581
3630
|
const runId = `observe-reject-${kind}`;
|
|
3631
|
+
await persistReplayOwner(mastra, runId, agent.id);
|
|
3582
3632
|
const prefix = {
|
|
3583
3633
|
type: "text-delta",
|
|
3584
3634
|
runId,
|
|
@@ -3608,7 +3658,10 @@ function createDurableDisconnectTestSuite(config) {
|
|
|
3608
3658
|
});
|
|
3609
3659
|
expect(response.status).toBe(200);
|
|
3610
3660
|
const wire = await response.text();
|
|
3611
|
-
expect(wire).toContain(JSON.stringify(
|
|
3661
|
+
expect(wire).toContain(JSON.stringify({
|
|
3662
|
+
...prefix,
|
|
3663
|
+
index: 0
|
|
3664
|
+
}));
|
|
3612
3665
|
expect(wire).not.toContain("[DONE]");
|
|
3613
3666
|
expect(wire).not.toContain("\"type\":\"error\"");
|
|
3614
3667
|
});
|
|
@@ -3725,7 +3778,311 @@ function createDurableDisconnectTestSuite(config) {
|
|
|
3725
3778
|
await original;
|
|
3726
3779
|
}
|
|
3727
3780
|
});
|
|
3781
|
+
it("resumes a multi-step tool loop after the last frame index received from /stream (COR-1506)", async () => {
|
|
3782
|
+
fixture = await config.setupModel();
|
|
3783
|
+
const tool = createTool({
|
|
3784
|
+
id: "lookup",
|
|
3785
|
+
description: "Look up a value",
|
|
3786
|
+
inputSchema: z.object({ n: z.number() }),
|
|
3787
|
+
execute: async ({ n }) => ({ value: n * 10 })
|
|
3788
|
+
});
|
|
3789
|
+
const agent = (kind === "durable" ? createDurableAgent : createEventedAgent)({
|
|
3790
|
+
agent: new Agent({
|
|
3791
|
+
id: "resume-agent",
|
|
3792
|
+
name: "Resume agent",
|
|
3793
|
+
instructions: "Look up values.",
|
|
3794
|
+
model: fixture.model,
|
|
3795
|
+
tools: { lookup: tool }
|
|
3796
|
+
}),
|
|
3797
|
+
cleanupTimeoutMs: 6e4
|
|
3798
|
+
});
|
|
3799
|
+
mastra = new Mastra$1({
|
|
3800
|
+
agents: { agent },
|
|
3801
|
+
storage: new InMemoryStore(),
|
|
3802
|
+
logger: false
|
|
3803
|
+
});
|
|
3804
|
+
server = await config.startServer(mastra, () => {});
|
|
3805
|
+
fixture.addResponse(0, {
|
|
3806
|
+
content: "First",
|
|
3807
|
+
toolCalls: [{
|
|
3808
|
+
id: "call-1",
|
|
3809
|
+
name: "lookup",
|
|
3810
|
+
arguments: { n: 1 }
|
|
3811
|
+
}]
|
|
3812
|
+
});
|
|
3813
|
+
fixture.addResponse(1, {
|
|
3814
|
+
content: "Second",
|
|
3815
|
+
toolCalls: [{
|
|
3816
|
+
id: "call-2",
|
|
3817
|
+
name: "lookup",
|
|
3818
|
+
arguments: { n: 2 }
|
|
3819
|
+
}]
|
|
3820
|
+
});
|
|
3821
|
+
fixture.addResponse(2, { content: "Done: 10 and 20." });
|
|
3822
|
+
fixture.addResponse(3, { content: "Again: 30." });
|
|
3823
|
+
const runId = `observe-resume-${kind}`;
|
|
3824
|
+
const post = async (route, body) => {
|
|
3825
|
+
const response = await fetch(`${server.baseUrl}/api/agents/agent/${route}`, {
|
|
3826
|
+
method: "POST",
|
|
3827
|
+
headers: { "content-type": "application/json" },
|
|
3828
|
+
body: JSON.stringify(body)
|
|
3829
|
+
});
|
|
3830
|
+
expect(response.status).toBe(200);
|
|
3831
|
+
return response;
|
|
3832
|
+
};
|
|
3833
|
+
const frames = await collectPublicFrames(await post("stream", {
|
|
3834
|
+
messages: "Look up 1 then 2",
|
|
3835
|
+
runId,
|
|
3836
|
+
maxSteps: 5
|
|
3837
|
+
}));
|
|
3838
|
+
expect(frames.filter((frame) => frame.type === "step-start")).toHaveLength(3);
|
|
3839
|
+
expect(frames.at(-1)).toMatchObject({ type: "finish" });
|
|
3840
|
+
expect(frames.every((frame) => typeof frame.index === "number")).toBe(true);
|
|
3841
|
+
expect(frames.at(-1).index).toBeGreaterThan(frames.length - 1);
|
|
3842
|
+
expect(await collectPublicFrames(await post("observe", {
|
|
3843
|
+
runId,
|
|
3844
|
+
offset: 0
|
|
3845
|
+
}))).toEqual(frames);
|
|
3846
|
+
const resumeAt = (cut) => cut === 0 ? 0 : frames[cut - 1].index + 1;
|
|
3847
|
+
const mismatches = [];
|
|
3848
|
+
for (let cut = 0; cut <= frames.length; cut++) {
|
|
3849
|
+
const resumed = await collectPublicFrames(await post("observe", {
|
|
3850
|
+
runId,
|
|
3851
|
+
offset: resumeAt(cut)
|
|
3852
|
+
}));
|
|
3853
|
+
const combined = [...frames.slice(0, cut), ...resumed];
|
|
3854
|
+
if (JSON.stringify(combined) !== JSON.stringify(frames)) mismatches.push(`cut ${cut}/${frames.length}: ${combined.length - frames.length} extra`);
|
|
3855
|
+
}
|
|
3856
|
+
expect(mismatches).toEqual([]);
|
|
3857
|
+
const cuts = [
|
|
3858
|
+
0,
|
|
3859
|
+
Math.floor(frames.length / 2),
|
|
3860
|
+
frames.length - 1,
|
|
3861
|
+
frames.length
|
|
3862
|
+
];
|
|
3863
|
+
if (config.observeWithClient) for (const cut of cuts) expect([...frames.slice(0, cut), ...await config.observeWithClient(server.baseUrl, runId, resumeAt(cut))]).toEqual(frames);
|
|
3864
|
+
if (config.streamWithClient) {
|
|
3865
|
+
const clientRunId = `${runId}-client`;
|
|
3866
|
+
const clientFrames = await config.streamWithClient(server.baseUrl, {
|
|
3867
|
+
messages: "Say it again",
|
|
3868
|
+
runId: clientRunId
|
|
3869
|
+
});
|
|
3870
|
+
expect(clientFrames.at(-1)).toMatchObject({ type: "finish" });
|
|
3871
|
+
expect(clientFrames.some((frame) => frame.type === "error")).toBe(false);
|
|
3872
|
+
expect(clientFrames.every((frame) => typeof frame.index === "number")).toBe(true);
|
|
3873
|
+
const mid = Math.floor(clientFrames.length / 2);
|
|
3874
|
+
expect([...clientFrames.slice(0, mid), ...await config.observeWithClient(server.baseUrl, clientRunId, clientFrames[mid - 1].index + 1)]).toEqual(clientFrames);
|
|
3875
|
+
}
|
|
3876
|
+
});
|
|
3877
|
+
it("keeps numbering and resuming by index across a tool-approval suspend (COR-1506)", async () => {
|
|
3878
|
+
fixture = await config.setupModel();
|
|
3879
|
+
const storage = new InMemoryStore();
|
|
3880
|
+
const authorize = createTool({
|
|
3881
|
+
id: "authorize",
|
|
3882
|
+
description: "Authorize the lookup",
|
|
3883
|
+
inputSchema: z.object({}),
|
|
3884
|
+
requireApproval: true,
|
|
3885
|
+
execute: async () => ({ approved: true })
|
|
3886
|
+
});
|
|
3887
|
+
const lookup = createTool({
|
|
3888
|
+
id: "lookup",
|
|
3889
|
+
description: "Look up a value",
|
|
3890
|
+
inputSchema: z.object({ n: z.number() }),
|
|
3891
|
+
execute: async ({ n }) => ({ value: n * 10 })
|
|
3892
|
+
});
|
|
3893
|
+
const agent = (kind === "durable" ? createDurableAgent : createEventedAgent)({
|
|
3894
|
+
agent: new Agent({
|
|
3895
|
+
id: "suspend-agent",
|
|
3896
|
+
name: "Suspend agent",
|
|
3897
|
+
instructions: "Authorize, then look up.",
|
|
3898
|
+
model: fixture.model,
|
|
3899
|
+
memory: new MockMemory({ storage }),
|
|
3900
|
+
tools: {
|
|
3901
|
+
authorize,
|
|
3902
|
+
lookup
|
|
3903
|
+
}
|
|
3904
|
+
}),
|
|
3905
|
+
cleanupTimeoutMs: 6e4
|
|
3906
|
+
});
|
|
3907
|
+
mastra = new Mastra$1({
|
|
3908
|
+
agents: { agent },
|
|
3909
|
+
storage,
|
|
3910
|
+
logger: false
|
|
3911
|
+
});
|
|
3912
|
+
server = await config.startServer(mastra, () => {});
|
|
3913
|
+
fixture.addResponse(0, {
|
|
3914
|
+
content: "Asking",
|
|
3915
|
+
toolCalls: [{
|
|
3916
|
+
id: "authorize-1",
|
|
3917
|
+
name: "authorize",
|
|
3918
|
+
arguments: {}
|
|
3919
|
+
}]
|
|
3920
|
+
});
|
|
3921
|
+
fixture.addResponse(1, {
|
|
3922
|
+
content: "Looking",
|
|
3923
|
+
toolCalls: [{
|
|
3924
|
+
id: "call-1",
|
|
3925
|
+
name: "lookup",
|
|
3926
|
+
arguments: { n: 1 }
|
|
3927
|
+
}]
|
|
3928
|
+
});
|
|
3929
|
+
fixture.addResponse(2, { content: "Done: 10." });
|
|
3930
|
+
const runId = `observe-suspend-${kind}`;
|
|
3931
|
+
const memory = {
|
|
3932
|
+
thread: runId,
|
|
3933
|
+
resource: "suspend-user"
|
|
3934
|
+
};
|
|
3935
|
+
const post = async (route, body) => {
|
|
3936
|
+
const response = await fetch(`${server.baseUrl}/api/agents/agent/${route}`, {
|
|
3937
|
+
method: "POST",
|
|
3938
|
+
headers: { "content-type": "application/json" },
|
|
3939
|
+
body: JSON.stringify(body)
|
|
3940
|
+
});
|
|
3941
|
+
expect(response.status).toBe(200);
|
|
3942
|
+
return response;
|
|
3943
|
+
};
|
|
3944
|
+
const suspended = [];
|
|
3945
|
+
const dropped = new AbortController();
|
|
3946
|
+
const streaming = await fetch(`${server.baseUrl}/api/agents/agent/stream`, {
|
|
3947
|
+
method: "POST",
|
|
3948
|
+
headers: { "content-type": "application/json" },
|
|
3949
|
+
signal: dropped.signal,
|
|
3950
|
+
body: JSON.stringify({
|
|
3951
|
+
messages: "Authorize then look up 1",
|
|
3952
|
+
runId,
|
|
3953
|
+
memory,
|
|
3954
|
+
maxSteps: 5
|
|
3955
|
+
})
|
|
3956
|
+
});
|
|
3957
|
+
expect(streaming.status).toBe(200);
|
|
3958
|
+
await collectPublicFrames(streaming, (frame) => {
|
|
3959
|
+
suspended.push(frame);
|
|
3960
|
+
if (frame.type === "tool-call-approval") dropped.abort();
|
|
3961
|
+
}).catch((error) => {
|
|
3962
|
+
if (error.name !== "AbortError") throw error;
|
|
3963
|
+
});
|
|
3964
|
+
expect(suspended.at(-1)).toMatchObject({ type: "tool-call-approval" });
|
|
3965
|
+
expect(suspended.every((frame) => typeof frame.index === "number")).toBe(true);
|
|
3966
|
+
const mid = Math.floor(suspended.length / 2);
|
|
3967
|
+
const parkedObservers = [suspended.length, mid].map(async (cut) => ({
|
|
3968
|
+
cut,
|
|
3969
|
+
frames: await collectPublicFrames(await post("observe", {
|
|
3970
|
+
runId,
|
|
3971
|
+
offset: suspended[cut - 1].index + 1
|
|
3972
|
+
}))
|
|
3973
|
+
}));
|
|
3974
|
+
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
3975
|
+
const approved = await collectPublicFrames(await post("approve-tool-call", {
|
|
3976
|
+
runId,
|
|
3977
|
+
toolCallId: "authorize-1",
|
|
3978
|
+
memory,
|
|
3979
|
+
maxSteps: 5
|
|
3980
|
+
}));
|
|
3981
|
+
expect(approved.at(-1)).toMatchObject({ type: "finish" });
|
|
3982
|
+
expect(approved.every((frame) => typeof frame.index === "number")).toBe(true);
|
|
3983
|
+
expect(approved[0].index).toBeGreaterThan(suspended.at(-1).index);
|
|
3984
|
+
const frames = [...suspended, ...approved];
|
|
3985
|
+
expect(frames.map((frame) => frame.index)).toEqual([...frames.map((frame) => frame.index)].sort((a, b) => a - b));
|
|
3986
|
+
for (const { cut, frames: resumed } of await Promise.all(parkedObservers)) expect([...suspended.slice(0, cut), ...resumed]).toEqual(frames);
|
|
3987
|
+
expect(await collectPublicFrames(await post("observe", {
|
|
3988
|
+
runId,
|
|
3989
|
+
offset: 0
|
|
3990
|
+
}))).toEqual(frames);
|
|
3991
|
+
const mismatches = [];
|
|
3992
|
+
for (let cut = 0; cut <= frames.length; cut++) {
|
|
3993
|
+
const offset = cut === 0 ? 0 : frames[cut - 1].index + 1;
|
|
3994
|
+
const combined = [...frames.slice(0, cut), ...await collectPublicFrames(await post("observe", {
|
|
3995
|
+
runId,
|
|
3996
|
+
offset
|
|
3997
|
+
}))];
|
|
3998
|
+
if (JSON.stringify(combined) !== JSON.stringify(frames)) mismatches.push(`cut ${cut}/${frames.length}: ${combined.length - frames.length} extra`);
|
|
3999
|
+
}
|
|
4000
|
+
expect(mismatches).toEqual([]);
|
|
4001
|
+
}, 3e4);
|
|
3728
4002
|
}
|
|
4003
|
+
if (kind === "plain") it("numbers every /observe frame with the index its log entry holds (COR-1506)", async () => {
|
|
4004
|
+
fixture = await config.setupModel();
|
|
4005
|
+
const tool = createTool({
|
|
4006
|
+
id: "lookup",
|
|
4007
|
+
description: "Look up a value",
|
|
4008
|
+
inputSchema: z.object({ n: z.number() }),
|
|
4009
|
+
execute: async ({ n }) => ({ value: n * 10 })
|
|
4010
|
+
});
|
|
4011
|
+
const agent = new Agent({
|
|
4012
|
+
id: "plain-resume-agent",
|
|
4013
|
+
name: "Plain resume agent",
|
|
4014
|
+
instructions: "Look up values.",
|
|
4015
|
+
model: fixture.model,
|
|
4016
|
+
tools: { lookup: tool }
|
|
4017
|
+
});
|
|
4018
|
+
mastra = new Mastra$1({
|
|
4019
|
+
agents: { agent },
|
|
4020
|
+
storage: new InMemoryStore(),
|
|
4021
|
+
logger: false
|
|
4022
|
+
});
|
|
4023
|
+
server = await config.startServer(mastra, () => {});
|
|
4024
|
+
fixture.addResponse(0, {
|
|
4025
|
+
content: "First",
|
|
4026
|
+
toolCalls: [{
|
|
4027
|
+
id: "call-1",
|
|
4028
|
+
name: "lookup",
|
|
4029
|
+
arguments: { n: 1 }
|
|
4030
|
+
}]
|
|
4031
|
+
});
|
|
4032
|
+
fixture.addResponse(1, {
|
|
4033
|
+
content: "Second",
|
|
4034
|
+
toolCalls: [{
|
|
4035
|
+
id: "call-2",
|
|
4036
|
+
name: "lookup",
|
|
4037
|
+
arguments: { n: 2 }
|
|
4038
|
+
}]
|
|
4039
|
+
});
|
|
4040
|
+
fixture.addResponse(2, { content: "Done: 10 and 20." });
|
|
4041
|
+
const runId = "observe-resume-plain";
|
|
4042
|
+
const post = async (route, body) => {
|
|
4043
|
+
const response = await fetch(`${server.baseUrl}/api/agents/agent/${route}`, {
|
|
4044
|
+
method: "POST",
|
|
4045
|
+
headers: { "content-type": "application/json" },
|
|
4046
|
+
body: JSON.stringify(body)
|
|
4047
|
+
});
|
|
4048
|
+
expect(response.status).toBe(200);
|
|
4049
|
+
return response;
|
|
4050
|
+
};
|
|
4051
|
+
const streamed = await collectPublicFrames(await post("stream", {
|
|
4052
|
+
messages: "Look up 1 then 2",
|
|
4053
|
+
runId,
|
|
4054
|
+
maxSteps: 5
|
|
4055
|
+
}));
|
|
4056
|
+
expect(streamed.filter((frame) => frame.type === "step-start")).toHaveLength(3);
|
|
4057
|
+
const pubsub = agent.__getStreamBus().pubsub;
|
|
4058
|
+
const topic = AGENT_STREAM_TOPIC(runId);
|
|
4059
|
+
await expect.poll(async () => (await pubsub.getHistory(topic)).some((event) => event.type === "finish"), { timeout: 5e3 }).toBe(true);
|
|
4060
|
+
const history = await pubsub.getHistory(topic);
|
|
4061
|
+
const frames = await collectPublicFrames(await post("observe", { runId }));
|
|
4062
|
+
expect(frames.map((frame) => frame.type)).toEqual(streamed.map((frame) => frame.type));
|
|
4063
|
+
expect(frames.every((frame) => typeof frame.index === "number")).toBe(true);
|
|
4064
|
+
for (const frame of frames) {
|
|
4065
|
+
const entry = history.find((event) => event.index === frame.index);
|
|
4066
|
+
expect(entry, `log entry ${frame.index}`).toBeDefined();
|
|
4067
|
+
if (entry.type === "chunk") expect(entry.data.type).toBe(frame.type);
|
|
4068
|
+
else expect(entry.type).toBe(frame.type);
|
|
4069
|
+
}
|
|
4070
|
+
expect(frames.every((frame, i) => i === 0 || frame.index > frames[i - 1].index)).toBe(true);
|
|
4071
|
+
const resumeAt = (cut) => cut === 0 ? 0 : frames[cut - 1].index + 1;
|
|
4072
|
+
const mismatches = [];
|
|
4073
|
+
for (let cut = 0; cut <= frames.length; cut++) {
|
|
4074
|
+
const resumed = await collectPublicFrames(await post("observe", {
|
|
4075
|
+
runId,
|
|
4076
|
+
offset: resumeAt(cut)
|
|
4077
|
+
}));
|
|
4078
|
+
if (JSON.stringify([...frames.slice(0, cut), ...resumed]) !== JSON.stringify(frames)) mismatches.push(`cut ${cut}/${frames.length}`);
|
|
4079
|
+
}
|
|
4080
|
+
expect(mismatches).toEqual([]);
|
|
4081
|
+
if (config.observeWithClient) {
|
|
4082
|
+
const mid = Math.floor(frames.length / 2);
|
|
4083
|
+
expect([...frames.slice(0, mid), ...await config.observeWithClient(server.baseUrl, runId, resumeAt(mid))]).toEqual(frames);
|
|
4084
|
+
}
|
|
4085
|
+
}, 3e4);
|
|
3729
4086
|
for (const route of [
|
|
3730
4087
|
"stream",
|
|
3731
4088
|
"stream-alias",
|
|
@@ -3735,15 +4092,18 @@ function createDurableDisconnectTestSuite(config) {
|
|
|
3735
4092
|
"resume-stream-until-idle",
|
|
3736
4093
|
"approve-tool-call",
|
|
3737
4094
|
"decline-tool-call"
|
|
3738
|
-
]) for (const explicitAbort of [
|
|
4095
|
+
]) for (const { durable, explicitAbort } of (kind === "plain" ? [void 0, false] : [void 0]).flatMap((durable) => [
|
|
3739
4096
|
false,
|
|
3740
4097
|
true,
|
|
3741
4098
|
"run",
|
|
3742
4099
|
"threadless"
|
|
3743
|
-
]) {
|
|
4100
|
+
].map((explicitAbort) => ({
|
|
4101
|
+
durable,
|
|
4102
|
+
explicitAbort
|
|
4103
|
+
})))) {
|
|
3744
4104
|
if (typeof explicitAbort === "string" && (kind === "plain" || !["stream", "stream-alias"].includes(route))) continue;
|
|
3745
4105
|
const threadless = explicitAbort === "threadless";
|
|
3746
|
-
it(`${route}: disconnect ${explicitAbort ? `then explicit ${explicitAbort === true ? "thread" : explicitAbort} abort stops execution` : "preserves durable execution and replay"}`, async () => {
|
|
4106
|
+
it(`${route}${durable === false ? " (durable:false)" : ""}: disconnect ${explicitAbort ? `then explicit ${explicitAbort === true ? "thread" : explicitAbort} abort stops execution` : "preserves durable execution and replay"}`, async () => {
|
|
3747
4107
|
fixture = await config.setupModel();
|
|
3748
4108
|
const entered = deferred();
|
|
3749
4109
|
const gate = deferred();
|
|
@@ -3792,6 +4152,7 @@ function createDurableDisconnectTestSuite(config) {
|
|
|
3792
4152
|
const inner = new Agent({
|
|
3793
4153
|
id: "disconnect-agent",
|
|
3794
4154
|
name: "Disconnect agent",
|
|
4155
|
+
durable,
|
|
3795
4156
|
instructions: "Execute three steps.",
|
|
3796
4157
|
model: fixture.model,
|
|
3797
4158
|
...threadless ? {} : { memory },
|
|
@@ -3889,7 +4250,7 @@ function createDurableDisconnectTestSuite(config) {
|
|
|
3889
4250
|
client.abort();
|
|
3890
4251
|
await disconnected.promise;
|
|
3891
4252
|
await request;
|
|
3892
|
-
if (
|
|
4253
|
+
if (durable !== false && explicitAbort) {
|
|
3893
4254
|
const runScoped = typeof explicitAbort === "string";
|
|
3894
4255
|
if (runScoped) {
|
|
3895
4256
|
const denied = await fetch(`${server.baseUrl}/api/agents/otherAgent/runs/${runId}/abort`, { method: "POST" });
|
|
@@ -3909,10 +4270,10 @@ function createDurableDisconnectTestSuite(config) {
|
|
|
3909
4270
|
expect(response.status).toBe(200);
|
|
3910
4271
|
expect(result).toEqual({ aborted: true });
|
|
3911
4272
|
}
|
|
3912
|
-
const completes =
|
|
4273
|
+
const completes = durable !== false && !explicitAbort;
|
|
3913
4274
|
if (!completes) await vi.waitFor(() => expect(toolSignal?.aborted).toBe(true));
|
|
3914
4275
|
else expect(toolSignal?.aborted).toBe(false);
|
|
3915
|
-
const observing =
|
|
4276
|
+
const observing = durable === false ? void 0 : fetch(`${base}/observe`, {
|
|
3916
4277
|
method: "POST",
|
|
3917
4278
|
headers: { "content-type": "application/json" },
|
|
3918
4279
|
body: JSON.stringify({ runId })
|
|
@@ -3970,6 +4331,199 @@ function createDurableDisconnectTestSuite(config) {
|
|
|
3970
4331
|
}
|
|
3971
4332
|
});
|
|
3972
4333
|
}
|
|
4334
|
+
// src/stream-disconnect-test-suite.ts
|
|
4335
|
+
const incompressible = (bytes) => randomBytes(Math.ceil(bytes * 3 / 4)).toString("base64").slice(0, bytes);
|
|
4336
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
4337
|
+
/**
|
|
4338
|
+
* Covers what happens to the stream a route returns when the client goes away (#29634, #29640). The adapter has
|
|
4339
|
+
* to cancel the upstream stream once the client is gone; for agents with resumable streams that cancel is the only
|
|
4340
|
+
* signal that the HTTP observer left, and without it the upstream keeps being read into a dead socket.
|
|
4341
|
+
*/
|
|
4342
|
+
function createStreamDisconnectTestSuite(config) {
|
|
4343
|
+
describe("streaming client disconnect", () => {
|
|
4344
|
+
let close;
|
|
4345
|
+
afterEach(async () => {
|
|
4346
|
+
await close?.();
|
|
4347
|
+
close = void 0;
|
|
4348
|
+
});
|
|
4349
|
+
async function setup({ responseType, chunks = 60, chunkBytes = 16, paceMs = 10, holdUntilDisconnect = false, compress = false }) {
|
|
4350
|
+
const state = {
|
|
4351
|
+
pulls: 0,
|
|
4352
|
+
canceled: false
|
|
4353
|
+
};
|
|
4354
|
+
let handlerEntered;
|
|
4355
|
+
const handlerStarted = new Promise((resolve) => handlerEntered = resolve);
|
|
4356
|
+
let handlerReturned;
|
|
4357
|
+
const handlerDone = new Promise((resolve) => handlerReturned = resolve);
|
|
4358
|
+
const padding = compress ? incompressible(chunkBytes) : "x".repeat(chunkBytes);
|
|
4359
|
+
const route = {
|
|
4360
|
+
method: "POST",
|
|
4361
|
+
path: "/test/disconnect",
|
|
4362
|
+
responseType,
|
|
4363
|
+
handler: async ({ abortSignal }) => {
|
|
4364
|
+
handlerEntered();
|
|
4365
|
+
if (holdUntilDisconnect) await Promise.race([new Promise((resolve) => {
|
|
4366
|
+
if (abortSignal?.aborted) resolve();
|
|
4367
|
+
abortSignal?.addEventListener("abort", () => resolve(), { once: true });
|
|
4368
|
+
}), sleep(2e3)]);
|
|
4369
|
+
handlerReturned();
|
|
4370
|
+
const body = new ReadableStream({
|
|
4371
|
+
async pull(controller) {
|
|
4372
|
+
if (state.pulls >= chunks) return controller.close();
|
|
4373
|
+
state.pulls++;
|
|
4374
|
+
if (paceMs) await sleep(paceMs);
|
|
4375
|
+
controller.enqueue(responseType === "stream" ? {
|
|
4376
|
+
type: "chunk",
|
|
4377
|
+
n: state.pulls,
|
|
4378
|
+
padding
|
|
4379
|
+
} : new TextEncoder().encode(`chunk-${state.pulls} ${padding}\n`));
|
|
4380
|
+
},
|
|
4381
|
+
cancel() {
|
|
4382
|
+
state.canceled = true;
|
|
4383
|
+
}
|
|
4384
|
+
});
|
|
4385
|
+
return responseType === "stream" ? body : new Response(body, {
|
|
4386
|
+
status: 200,
|
|
4387
|
+
headers: { "Content-Type": "text/plain" }
|
|
4388
|
+
});
|
|
4389
|
+
}
|
|
4390
|
+
};
|
|
4391
|
+
const server = await config.startServer(route, { compress });
|
|
4392
|
+
close = server.close;
|
|
4393
|
+
return {
|
|
4394
|
+
url: server.url,
|
|
4395
|
+
state,
|
|
4396
|
+
handlerStarted,
|
|
4397
|
+
handlerDone
|
|
4398
|
+
};
|
|
4399
|
+
}
|
|
4400
|
+
const post = (url, signal) => fetch(url, {
|
|
4401
|
+
method: "POST",
|
|
4402
|
+
headers: { "content-type": "application/json" },
|
|
4403
|
+
body: "{}",
|
|
4404
|
+
signal
|
|
4405
|
+
});
|
|
4406
|
+
it("aborts the route abort signal when the client left while earlier middleware was running", async () => {
|
|
4407
|
+
let hookEntered;
|
|
4408
|
+
const inHook = new Promise((resolve) => hookEntered = resolve);
|
|
4409
|
+
let releaseHook;
|
|
4410
|
+
const hookReleased = new Promise((resolve) => releaseHook = resolve);
|
|
4411
|
+
let routeRan;
|
|
4412
|
+
const routeResult = new Promise((resolve) => routeRan = resolve);
|
|
4413
|
+
const server = await config.startServer({
|
|
4414
|
+
method: "GET",
|
|
4415
|
+
path: "/test/early-close",
|
|
4416
|
+
responseType: "json",
|
|
4417
|
+
handler: async ({ abortSignal }) => {
|
|
4418
|
+
routeRan(abortSignal?.aborted);
|
|
4419
|
+
return {};
|
|
4420
|
+
}
|
|
4421
|
+
}, { beforeContext: async () => {
|
|
4422
|
+
hookEntered();
|
|
4423
|
+
await hookReleased;
|
|
4424
|
+
} });
|
|
4425
|
+
close = server.close;
|
|
4426
|
+
const client = new AbortController();
|
|
4427
|
+
const request = fetch(server.url, { signal: client.signal }).catch(() => void 0);
|
|
4428
|
+
await inHook;
|
|
4429
|
+
client.abort();
|
|
4430
|
+
await request;
|
|
4431
|
+
await sleep(100);
|
|
4432
|
+
releaseHook();
|
|
4433
|
+
const aborted = await Promise.race([routeResult, sleep(2e3).then(() => "route never ran")]);
|
|
4434
|
+
expect(aborted, "route abortSignal.aborted").toBe(true);
|
|
4435
|
+
});
|
|
4436
|
+
describe.each(["stream", "datastream-response"])("%s route", (responseType) => {
|
|
4437
|
+
it("stops reading the upstream when the client aborts mid-body", async () => {
|
|
4438
|
+
const { url, state } = await setup({ responseType });
|
|
4439
|
+
const client = new AbortController();
|
|
4440
|
+
await (await post(url, client.signal)).body.getReader().read();
|
|
4441
|
+
const pullsAtAbort = state.pulls;
|
|
4442
|
+
client.abort();
|
|
4443
|
+
await sleep(300);
|
|
4444
|
+
expect(state.pulls - pullsAtAbort, "upstream pulls after client abort").toBeLessThanOrEqual(2);
|
|
4445
|
+
expect(state.canceled, "upstream cancel()").toBe(true);
|
|
4446
|
+
});
|
|
4447
|
+
it("stops reading the upstream when the client aborts before the handler returns", async () => {
|
|
4448
|
+
const { url, state, handlerStarted, handlerDone } = await setup({
|
|
4449
|
+
responseType,
|
|
4450
|
+
holdUntilDisconnect: true
|
|
4451
|
+
});
|
|
4452
|
+
const client = new AbortController();
|
|
4453
|
+
const request = post(url, client.signal).catch(() => void 0);
|
|
4454
|
+
await handlerStarted;
|
|
4455
|
+
client.abort();
|
|
4456
|
+
await request;
|
|
4457
|
+
await handlerDone;
|
|
4458
|
+
await sleep(300);
|
|
4459
|
+
expect(state.pulls, "upstream pulls after client abort").toBeLessThanOrEqual(2);
|
|
4460
|
+
expect(state.canceled, "upstream cancel()").toBe(true);
|
|
4461
|
+
});
|
|
4462
|
+
it("delivers the whole body without cancelling the upstream when the client reads to the end", async () => {
|
|
4463
|
+
const { url, state } = await setup({
|
|
4464
|
+
responseType,
|
|
4465
|
+
chunks: 20
|
|
4466
|
+
});
|
|
4467
|
+
const text = await (await post(url)).text();
|
|
4468
|
+
expect(text.match(/"n":\d+|chunk-\d+/g)).toHaveLength(20);
|
|
4469
|
+
expect(state.canceled, "upstream cancel()").toBe(false);
|
|
4470
|
+
});
|
|
4471
|
+
it("pauses reading the upstream while a connected client is not reading, and cancels it once the client leaves", async () => {
|
|
4472
|
+
const { url, state } = await setup({
|
|
4473
|
+
responseType,
|
|
4474
|
+
chunks: 400,
|
|
4475
|
+
chunkBytes: 65536,
|
|
4476
|
+
paceMs: 0
|
|
4477
|
+
});
|
|
4478
|
+
const client = new AbortController();
|
|
4479
|
+
const response = await post(url, client.signal);
|
|
4480
|
+
await sleep(500);
|
|
4481
|
+
const pullsWhilePaused = state.pulls;
|
|
4482
|
+
client.abort();
|
|
4483
|
+
await response.body?.cancel().catch(() => {});
|
|
4484
|
+
expect(pullsWhilePaused, "upstream pulls while the client was not reading").toBeLessThan(400);
|
|
4485
|
+
await sleep(300);
|
|
4486
|
+
expect(state.canceled, "upstream cancel()").toBe(true);
|
|
4487
|
+
});
|
|
4488
|
+
it.runIf(config.supportsCompression)("streams a compressed response to a slow client without piling up drain listeners", async () => {
|
|
4489
|
+
const warnings = [];
|
|
4490
|
+
const onWarning = (warning) => {
|
|
4491
|
+
if (warning.name === "MaxListenersExceededWarning") warnings.push(warning.message);
|
|
4492
|
+
};
|
|
4493
|
+
process.on("warning", onWarning);
|
|
4494
|
+
try {
|
|
4495
|
+
const { url } = await setup({
|
|
4496
|
+
responseType,
|
|
4497
|
+
chunks: 100,
|
|
4498
|
+
chunkBytes: 65536,
|
|
4499
|
+
paceMs: 0,
|
|
4500
|
+
compress: true
|
|
4501
|
+
});
|
|
4502
|
+
const response = await fetch(url, {
|
|
4503
|
+
method: "POST",
|
|
4504
|
+
headers: {
|
|
4505
|
+
"content-type": "application/json",
|
|
4506
|
+
"accept-encoding": "gzip"
|
|
4507
|
+
},
|
|
4508
|
+
body: "{}"
|
|
4509
|
+
});
|
|
4510
|
+
expect(response.headers.get("content-encoding")).toBe("gzip");
|
|
4511
|
+
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
|
|
4512
|
+
let text = "";
|
|
4513
|
+
for (let next = await reader.read(); !next.done; next = await reader.read()) {
|
|
4514
|
+
text += next.value;
|
|
4515
|
+
await sleep(1);
|
|
4516
|
+
}
|
|
4517
|
+
await sleep(50);
|
|
4518
|
+
expect(text.match(/"n":\d+|chunk-\d+/g)).toHaveLength(100);
|
|
4519
|
+
expect(warnings, "MaxListenersExceededWarning").toEqual([]);
|
|
4520
|
+
} finally {
|
|
4521
|
+
process.off("warning", onWarning);
|
|
4522
|
+
}
|
|
4523
|
+
});
|
|
4524
|
+
});
|
|
4525
|
+
});
|
|
4526
|
+
}
|
|
3973
4527
|
// src/mcp-route-test-suite.ts
|
|
3974
4528
|
/**
|
|
3975
4529
|
* Creates a standardized integration test suite for MCP registry routes
|
|
@@ -4222,6 +4776,73 @@ function createMCPRouteTestSuite(config) {
|
|
|
4222
4776
|
});
|
|
4223
4777
|
});
|
|
4224
4778
|
}
|
|
4779
|
+
// src/legacy-sse-fixture.ts
|
|
4780
|
+
const TRUSTED_REQUEST_CONTEXT = Symbol.for("mastra.mcp.trustedRequestContext");
|
|
4781
|
+
function identityOf(auth) {
|
|
4782
|
+
const authInfo = auth;
|
|
4783
|
+
const trusted = authInfo?.[TRUSTED_REQUEST_CONTEXT];
|
|
4784
|
+
const user = trusted?.["mastra__user"];
|
|
4785
|
+
return {
|
|
4786
|
+
clientId: authInfo?.clientId ?? null,
|
|
4787
|
+
userId: user?.id ?? null,
|
|
4788
|
+
permissions: trusted?.["mastra__userPermissions"] ?? null
|
|
4789
|
+
};
|
|
4790
|
+
}
|
|
4791
|
+
/**
|
|
4792
|
+
* Stands in for an `@mastra/mcp` 1.x server, the only kind that serves the
|
|
4793
|
+
* standalone SSE transport. Instead of streaming, it answers the SSE request
|
|
4794
|
+
* with the caller identity the adapter handed it.
|
|
4795
|
+
*/
|
|
4796
|
+
var LegacySSEFixture = class extends MCPServerBase {
|
|
4797
|
+
constructor() {
|
|
4798
|
+
super({
|
|
4799
|
+
id: "legacy-sse-fixture",
|
|
4800
|
+
name: "Legacy SSE fixture",
|
|
4801
|
+
version: "1.0.0",
|
|
4802
|
+
tools: {}
|
|
4803
|
+
});
|
|
4804
|
+
}
|
|
4805
|
+
async startSSE({ req, res }) {
|
|
4806
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
4807
|
+
res.end(JSON.stringify(identityOf(req.auth)));
|
|
4808
|
+
}
|
|
4809
|
+
async startHonoSSE({ authInfo }) {
|
|
4810
|
+
return Response.json(identityOf(authInfo));
|
|
4811
|
+
}
|
|
4812
|
+
convertTools() {
|
|
4813
|
+
return {};
|
|
4814
|
+
}
|
|
4815
|
+
async startStdio() {}
|
|
4816
|
+
async startHTTP() {}
|
|
4817
|
+
async close() {}
|
|
4818
|
+
getServerInfo() {
|
|
4819
|
+
return {
|
|
4820
|
+
id: this.id,
|
|
4821
|
+
name: this.name,
|
|
4822
|
+
version_detail: {
|
|
4823
|
+
version: this.version,
|
|
4824
|
+
release_date: this.releaseDate,
|
|
4825
|
+
is_latest: this.isLatest
|
|
4826
|
+
}
|
|
4827
|
+
};
|
|
4828
|
+
}
|
|
4829
|
+
getServerDetail() {
|
|
4830
|
+
return this.getServerInfo();
|
|
4831
|
+
}
|
|
4832
|
+
getToolListInfo() {
|
|
4833
|
+
return { tools: [] };
|
|
4834
|
+
}
|
|
4835
|
+
getToolInfo() {}
|
|
4836
|
+
async executeTool() {
|
|
4837
|
+
return {};
|
|
4838
|
+
}
|
|
4839
|
+
async readResource() {
|
|
4840
|
+
return { contents: [] };
|
|
4841
|
+
}
|
|
4842
|
+
async listResources() {
|
|
4843
|
+
return { resources: [] };
|
|
4844
|
+
}
|
|
4845
|
+
};
|
|
4225
4846
|
// src/native-mcp-fixture.ts
|
|
4226
4847
|
const unavailable = (feature) => async () => {
|
|
4227
4848
|
throw new Error(`${feature} is not available on a 2026-07-28 server`);
|
|
@@ -4712,6 +5333,119 @@ function createMCPTransportTestSuite(config) {
|
|
|
4712
5333
|
});
|
|
4713
5334
|
});
|
|
4714
5335
|
});
|
|
5336
|
+
describe("HTTP Transport with server auth", () => {
|
|
5337
|
+
const whoamiTool = createTool({
|
|
5338
|
+
id: "whoami",
|
|
5339
|
+
description: "Reports the caller identity the tool sees",
|
|
5340
|
+
inputSchema: z.object({}),
|
|
5341
|
+
execute: async (_input, context) => {
|
|
5342
|
+
const requestContext = context?.requestContext;
|
|
5343
|
+
return {
|
|
5344
|
+
userId: (requestContext?.get("user"))?.id ?? null,
|
|
5345
|
+
permissions: requestContext?.get("mastra__userPermissions") ?? null
|
|
5346
|
+
};
|
|
5347
|
+
}
|
|
5348
|
+
});
|
|
5349
|
+
let authedHttpServer;
|
|
5350
|
+
let authedPort;
|
|
5351
|
+
let authedMcpServer;
|
|
5352
|
+
let authedClient;
|
|
5353
|
+
const legacySseServer = new LegacySSEFixture();
|
|
5354
|
+
const users = {
|
|
5355
|
+
"reader-token": { id: "user-reader" },
|
|
5356
|
+
"blocked-token": { id: "user-blocked" }
|
|
5357
|
+
};
|
|
5358
|
+
beforeAll(async () => {
|
|
5359
|
+
authedMcpServer = new MCPServer({
|
|
5360
|
+
name: "authed",
|
|
5361
|
+
version: "1.0.0",
|
|
5362
|
+
tools: { whoami: whoamiTool }
|
|
5363
|
+
});
|
|
5364
|
+
const authedMastra = new Mastra$1({
|
|
5365
|
+
mcpServers: {
|
|
5366
|
+
authed: authedMcpServer,
|
|
5367
|
+
legacySse: legacySseServer
|
|
5368
|
+
},
|
|
5369
|
+
server: {
|
|
5370
|
+
auth: {
|
|
5371
|
+
authenticateToken: async (token) => users[token] ?? null,
|
|
5372
|
+
authorize: async (_path, _method, user) => user.id !== "user-blocked"
|
|
5373
|
+
},
|
|
5374
|
+
rbac: {
|
|
5375
|
+
getPermissions: async () => ["observability:read"],
|
|
5376
|
+
getRoles: async () => ["reader"]
|
|
5377
|
+
}
|
|
5378
|
+
}
|
|
5379
|
+
});
|
|
5380
|
+
const setup = await createServer(authedMastra);
|
|
5381
|
+
authedHttpServer = setup.server;
|
|
5382
|
+
authedPort = setup.port;
|
|
5383
|
+
authedClient = new MCPClient({ servers: { authed: {
|
|
5384
|
+
url: new URL(`http://localhost:${authedPort}/api/mcp/${authedMcpServer.id}/mcp`),
|
|
5385
|
+
requestInit: { headers: { Authorization: "Bearer reader-token" } }
|
|
5386
|
+
} } });
|
|
5387
|
+
}, 3e4);
|
|
5388
|
+
afterAll(async () => {
|
|
5389
|
+
await authedClient?.disconnect();
|
|
5390
|
+
authedHttpServer?.close();
|
|
5391
|
+
await authedMcpServer?.close();
|
|
5392
|
+
}, 3e4);
|
|
5393
|
+
it("gives MCP tools the user and permissions server auth resolved", async () => {
|
|
5394
|
+
const whoami = (await authedClient.listTools())["authed_whoami"];
|
|
5395
|
+
if (!whoami?.execute) throw new Error("Expected authed_whoami tool");
|
|
5396
|
+
const result = await whoami.execute({}, {});
|
|
5397
|
+
expectTextToolResult(result, {
|
|
5398
|
+
userId: "user-reader",
|
|
5399
|
+
permissions: ["observability:read"]
|
|
5400
|
+
});
|
|
5401
|
+
});
|
|
5402
|
+
it("rejects MCP requests without credentials", async () => {
|
|
5403
|
+
const response = await fetch(`http://localhost:${authedPort}/api/mcp/${authedMcpServer.id}/mcp`, {
|
|
5404
|
+
method: "POST",
|
|
5405
|
+
headers: {
|
|
5406
|
+
"Content-Type": "application/json",
|
|
5407
|
+
Accept: "application/json, text/event-stream"
|
|
5408
|
+
},
|
|
5409
|
+
body: JSON.stringify({
|
|
5410
|
+
jsonrpc: "2.0",
|
|
5411
|
+
id: 1,
|
|
5412
|
+
method: "tools/list",
|
|
5413
|
+
params: {}
|
|
5414
|
+
})
|
|
5415
|
+
});
|
|
5416
|
+
expect(response.status).toBe(401);
|
|
5417
|
+
});
|
|
5418
|
+
it("refuses MCP requests server auth does not authorize", async () => {
|
|
5419
|
+
const response = await fetch(`http://localhost:${authedPort}/api/mcp/${authedMcpServer.id}/mcp`, {
|
|
5420
|
+
method: "POST",
|
|
5421
|
+
headers: {
|
|
5422
|
+
"Content-Type": "application/json",
|
|
5423
|
+
Accept: "application/json, text/event-stream",
|
|
5424
|
+
Authorization: "Bearer blocked-token"
|
|
5425
|
+
},
|
|
5426
|
+
body: JSON.stringify({
|
|
5427
|
+
jsonrpc: "2.0",
|
|
5428
|
+
id: 1,
|
|
5429
|
+
method: "tools/list",
|
|
5430
|
+
params: {}
|
|
5431
|
+
})
|
|
5432
|
+
});
|
|
5433
|
+
expect(response.status).toBe(403);
|
|
5434
|
+
});
|
|
5435
|
+
it("hands the SSE transport the user and permissions server auth resolved", async () => {
|
|
5436
|
+
const response = await fetch(`http://localhost:${authedPort}/api/mcp/${legacySseServer.id}/sse`, { headers: { Authorization: "Bearer reader-token" } });
|
|
5437
|
+
expect(response.status).toBe(200);
|
|
5438
|
+
expect(await response.json()).toEqual({
|
|
5439
|
+
clientId: "user-reader",
|
|
5440
|
+
userId: "user-reader",
|
|
5441
|
+
permissions: ["observability:read"]
|
|
5442
|
+
});
|
|
5443
|
+
});
|
|
5444
|
+
it("refuses SSE requests server auth does not authorize", async () => {
|
|
5445
|
+
const response = await fetch(`http://localhost:${authedPort}/api/mcp/${legacySseServer.id}/sse`, { headers: { Authorization: "Bearer blocked-token" } });
|
|
5446
|
+
expect(response.status).toBe(403);
|
|
5447
|
+
});
|
|
5448
|
+
});
|
|
4715
5449
|
describe("HTTP Transport client disconnect", () => {
|
|
4716
5450
|
it.each([{
|
|
4717
5451
|
name: "before any response bytes are sent",
|
|
@@ -5722,6 +6456,478 @@ function createKnowledgeRoutesTestSuite(config) {
|
|
|
5722
6456
|
});
|
|
5723
6457
|
});
|
|
5724
6458
|
}
|
|
5725
|
-
|
|
6459
|
+
// src/observability-signal-write-test-suite.ts
|
|
6460
|
+
/** Shared HTTP contract for feedback/score writes, backed by real in-memory storage. */
|
|
6461
|
+
function createObservabilitySignalWriteTestSuite({ startServer }) {
|
|
6462
|
+
describe.each(["feedback", "scores"])("%s HTTP writes", (collection) => {
|
|
6463
|
+
let server;
|
|
6464
|
+
let store;
|
|
6465
|
+
let trustedScope;
|
|
6466
|
+
let allowAccess;
|
|
6467
|
+
let authorLookupFails;
|
|
6468
|
+
const isFeedback = collection === "feedback";
|
|
6469
|
+
const field = isFeedback ? "feedback" : "score";
|
|
6470
|
+
const idField = isFeedback ? "feedbackId" : "scoreId";
|
|
6471
|
+
const payload = isFeedback ? {
|
|
6472
|
+
feedbackType: "thumbs",
|
|
6473
|
+
value: 1
|
|
6474
|
+
} : {
|
|
6475
|
+
scorerId: "accuracy",
|
|
6476
|
+
score: .9
|
|
6477
|
+
};
|
|
6478
|
+
const path = `/api/observability/${collection}`;
|
|
6479
|
+
beforeEach(async () => {
|
|
6480
|
+
trustedScope = {};
|
|
6481
|
+
allowAccess = true;
|
|
6482
|
+
authorLookupFails = false;
|
|
6483
|
+
const storage = new InMemoryStore();
|
|
6484
|
+
store = await storage.getStore("observability");
|
|
6485
|
+
server = await startServer(new Mastra({
|
|
6486
|
+
storage,
|
|
6487
|
+
logger: false,
|
|
6488
|
+
server: { auth: {
|
|
6489
|
+
authenticateToken: async () => ({}),
|
|
6490
|
+
getCurrentUser: async () => null,
|
|
6491
|
+
getUser: async (id) => {
|
|
6492
|
+
if (authorLookupFails) throw new Error("Directory unavailable");
|
|
6493
|
+
return id === "author-1" ? {
|
|
6494
|
+
id,
|
|
6495
|
+
name: "Alice",
|
|
6496
|
+
email: "alice@example.com",
|
|
6497
|
+
secret: "private"
|
|
6498
|
+
} : null;
|
|
6499
|
+
},
|
|
6500
|
+
authorize: async (_path, _method, _user, c) => {
|
|
6501
|
+
for (const [key, value] of Object.entries(trustedScope)) c.get("requestContext").set(key, value);
|
|
6502
|
+
return allowAccess;
|
|
6503
|
+
}
|
|
6504
|
+
} }
|
|
6505
|
+
}));
|
|
6506
|
+
});
|
|
6507
|
+
afterEach(async () => {
|
|
6508
|
+
await server?.close();
|
|
6509
|
+
});
|
|
6510
|
+
const post = (record, contextMode) => server.request(path, {
|
|
6511
|
+
method: "POST",
|
|
6512
|
+
headers: {
|
|
6513
|
+
"Content-Type": "application/json",
|
|
6514
|
+
authorization: "Bearer test-token"
|
|
6515
|
+
},
|
|
6516
|
+
body: JSON.stringify({
|
|
6517
|
+
[field]: record,
|
|
6518
|
+
contextMode
|
|
6519
|
+
})
|
|
6520
|
+
});
|
|
6521
|
+
const list = async () => {
|
|
6522
|
+
const response = await server.request(path, { headers: { authorization: "Bearer test-token" } });
|
|
6523
|
+
expect(response.status).toBe(200);
|
|
6524
|
+
return (await response.json())[collection];
|
|
6525
|
+
};
|
|
6526
|
+
describe("single-record reads", () => {
|
|
6527
|
+
it("returns the persisted record with its identity and timestamp", async () => {
|
|
6528
|
+
const id = "single-record";
|
|
6529
|
+
const timestamp = "2026-11-05T12:00:00.000Z";
|
|
6530
|
+
const identity = {
|
|
6531
|
+
traceId: "trace-123",
|
|
6532
|
+
timestamp: /* @__PURE__ */ new Date(timestamp)
|
|
6533
|
+
};
|
|
6534
|
+
if (isFeedback) await store.createFeedback({ feedback: {
|
|
6535
|
+
...identity,
|
|
6536
|
+
feedbackId: id,
|
|
6537
|
+
feedbackType: "thumbs",
|
|
6538
|
+
value: 1
|
|
6539
|
+
} });
|
|
6540
|
+
else await store.createScore({ score: {
|
|
6541
|
+
...identity,
|
|
6542
|
+
scoreId: id,
|
|
6543
|
+
scorerId: "accuracy",
|
|
6544
|
+
score: .9
|
|
6545
|
+
} });
|
|
6546
|
+
const response = await server.request(`${path}/${id}`, { headers: { authorization: "Bearer test-token" } });
|
|
6547
|
+
expect(response.status).toBe(200);
|
|
6548
|
+
expect(await response.json()).toMatchObject({ [field]: {
|
|
6549
|
+
...payload,
|
|
6550
|
+
[idField]: id,
|
|
6551
|
+
traceId: "trace-123",
|
|
6552
|
+
timestamp
|
|
6553
|
+
} });
|
|
6554
|
+
});
|
|
6555
|
+
it("returns null for a missing record", async () => {
|
|
6556
|
+
const response = await server.request(`${path}/missing`, { headers: { authorization: "Bearer test-token" } });
|
|
6557
|
+
expect(response.status).toBe(200);
|
|
6558
|
+
expect(await response.json()).toEqual({ [field]: null });
|
|
6559
|
+
});
|
|
6560
|
+
it("denies reads when authorization rejects access", async () => {
|
|
6561
|
+
allowAccess = false;
|
|
6562
|
+
const response = await server.request(`${path}/private-record`, { headers: { authorization: "Bearer test-token" } });
|
|
6563
|
+
expect(response.status).toBe(403);
|
|
6564
|
+
});
|
|
6565
|
+
});
|
|
6566
|
+
if (isFeedback) describe("single-record feedback enrichment and compatibility", () => {
|
|
6567
|
+
it.each([
|
|
6568
|
+
"resolved",
|
|
6569
|
+
"missing",
|
|
6570
|
+
"failed",
|
|
6571
|
+
"anonymous"
|
|
6572
|
+
])("returns feedback with %s author lookup consistently with the list", async (scenario) => {
|
|
6573
|
+
authorLookupFails = scenario === "failed";
|
|
6574
|
+
await store.createFeedback({ feedback: {
|
|
6575
|
+
feedbackId: "with-author",
|
|
6576
|
+
traceId: "trace-123",
|
|
6577
|
+
timestamp: /* @__PURE__ */ new Date("2026-11-05T12:00:00.000Z"),
|
|
6578
|
+
feedbackType: "thumbs",
|
|
6579
|
+
value: 1,
|
|
6580
|
+
feedbackUserId: scenario === "anonymous" ? null : scenario === "missing" ? "deleted-user" : "author-1"
|
|
6581
|
+
} });
|
|
6582
|
+
const response = await server.request(`${path}/with-author`, { headers: { authorization: "Bearer test-token" } });
|
|
6583
|
+
expect(response.status).toBe(200);
|
|
6584
|
+
const { feedback } = await response.json();
|
|
6585
|
+
expect(feedback).toEqual((await list())[0]);
|
|
6586
|
+
expect(feedback.feedbackId).toBe("with-author");
|
|
6587
|
+
if (scenario === "resolved") expect(feedback.author).toEqual({
|
|
6588
|
+
id: "author-1",
|
|
6589
|
+
name: "Alice",
|
|
6590
|
+
email: "alice@example.com"
|
|
6591
|
+
});
|
|
6592
|
+
else expect(feedback).not.toHaveProperty("author");
|
|
6593
|
+
});
|
|
6594
|
+
it("returns 501 when an older Core store lacks single-feedback reads", async () => {
|
|
6595
|
+
Object.defineProperty(store, "getFeedbackById", {
|
|
6596
|
+
value: void 0,
|
|
6597
|
+
configurable: true
|
|
6598
|
+
});
|
|
6599
|
+
const response = await server.request(`${path}/existing-id`, { headers: { authorization: "Bearer test-token" } });
|
|
6600
|
+
expect(response.status).toBe(501);
|
|
6601
|
+
expect(await response.json()).toMatchObject({ error: expect.stringContaining("single-feedback reads") });
|
|
6602
|
+
});
|
|
6603
|
+
});
|
|
6604
|
+
it.each([
|
|
6605
|
+
void 0,
|
|
6606
|
+
null,
|
|
6607
|
+
"",
|
|
6608
|
+
" ",
|
|
6609
|
+
" \n"
|
|
6610
|
+
])("rejects traceId %j without persisting a record (OBS-788)", async (traceId) => {
|
|
6611
|
+
const create = vi.spyOn(store, isFeedback ? "createFeedback" : "createScore");
|
|
6612
|
+
for (const spanId of [void 0, "span-without-trace"]) {
|
|
6613
|
+
const response = await post({
|
|
6614
|
+
...payload,
|
|
6615
|
+
traceId,
|
|
6616
|
+
spanId
|
|
6617
|
+
});
|
|
6618
|
+
expect(response.status, await response.clone().text()).toBe(400);
|
|
6619
|
+
}
|
|
6620
|
+
expect(create).not.toHaveBeenCalled();
|
|
6621
|
+
expect(await list()).toEqual([]);
|
|
6622
|
+
});
|
|
6623
|
+
it.each([void 0, "span-123"])("persists a trace with spanId %j and preserves the write contract", async (spanId) => {
|
|
6624
|
+
const before = Date.now();
|
|
6625
|
+
for (const id of [void 0, "caller-id"]) {
|
|
6626
|
+
const response = await post({
|
|
6627
|
+
...payload,
|
|
6628
|
+
traceId: "trace-123",
|
|
6629
|
+
spanId,
|
|
6630
|
+
[idField]: id
|
|
6631
|
+
});
|
|
6632
|
+
expect(response.status, await response.clone().text()).toBe(200);
|
|
6633
|
+
expect(await response.json()).toMatchObject({
|
|
6634
|
+
success: true,
|
|
6635
|
+
data: {
|
|
6636
|
+
traceId: "trace-123",
|
|
6637
|
+
spanId: spanId ?? null,
|
|
6638
|
+
timestamp: expect.any(String)
|
|
6639
|
+
}
|
|
6640
|
+
});
|
|
6641
|
+
}
|
|
6642
|
+
const rows = await list();
|
|
6643
|
+
expect(rows).toHaveLength(2);
|
|
6644
|
+
expect(new Set(rows.map((row) => row[idField])).size).toBe(2);
|
|
6645
|
+
expect(rows.some((row) => row[idField] === "caller-id")).toBe(true);
|
|
6646
|
+
for (const row of rows) {
|
|
6647
|
+
expect(row).toMatchObject({
|
|
6648
|
+
...payload,
|
|
6649
|
+
traceId: "trace-123"
|
|
6650
|
+
});
|
|
6651
|
+
expect(row.spanId ?? null).toBe(spanId ?? null);
|
|
6652
|
+
expect(row[idField]).toEqual(expect.any(String));
|
|
6653
|
+
expect(String(row[idField]).length).toBeGreaterThan(0);
|
|
6654
|
+
expect(new Date(String(row.timestamp)).getTime()).toBeGreaterThanOrEqual(before);
|
|
6655
|
+
expect(new Date(String(row.timestamp)).getTime()).toBeLessThanOrEqual(Date.now());
|
|
6656
|
+
}
|
|
6657
|
+
});
|
|
6658
|
+
const writeSpan = async (spanId, parentSpanId = null, overrides = {}) => {
|
|
6659
|
+
await store.createSpan({ span: {
|
|
6660
|
+
traceId: "trace-123",
|
|
6661
|
+
spanId,
|
|
6662
|
+
parentSpanId,
|
|
6663
|
+
name: spanId,
|
|
6664
|
+
spanType: SpanType.GENERIC,
|
|
6665
|
+
isEvent: false,
|
|
6666
|
+
startedAt: /* @__PURE__ */ new Date("2026-01-01T00:00:00Z"),
|
|
6667
|
+
endedAt: /* @__PURE__ */ new Date("2026-01-01T00:00:01Z"),
|
|
6668
|
+
entityType: EntityType.AGENT,
|
|
6669
|
+
entityId: spanId,
|
|
6670
|
+
userId: "span-user",
|
|
6671
|
+
tags: parentSpanId ? ["child-tag"] : ["root-tag"],
|
|
6672
|
+
metadata: {
|
|
6673
|
+
inherited: true,
|
|
6674
|
+
override: "stored",
|
|
6675
|
+
userId: "metadata-user"
|
|
6676
|
+
},
|
|
6677
|
+
...overrides
|
|
6678
|
+
} });
|
|
6679
|
+
};
|
|
6680
|
+
it.each([void 0, "provided"])("uses supplied context without lookup in mode %j", async (contextMode) => {
|
|
6681
|
+
const lookup = vi.spyOn(store, "getTrace");
|
|
6682
|
+
const spanLookup = vi.spyOn(store, "getSpan");
|
|
6683
|
+
const timestamp = "2026-01-01T01:00:00.123456+01:00";
|
|
6684
|
+
const response = await post({
|
|
6685
|
+
...payload,
|
|
6686
|
+
traceId: "absent",
|
|
6687
|
+
spanId: "absent",
|
|
6688
|
+
timestamp,
|
|
6689
|
+
[idField]: "stable-id",
|
|
6690
|
+
userId: "span-user",
|
|
6691
|
+
tags: ["provided"]
|
|
6692
|
+
}, contextMode);
|
|
6693
|
+
expect(response.status, await response.clone().text()).toBe(200);
|
|
6694
|
+
expect(await response.json()).toEqual({
|
|
6695
|
+
success: true,
|
|
6696
|
+
data: {
|
|
6697
|
+
[idField]: "stable-id",
|
|
6698
|
+
traceId: "absent",
|
|
6699
|
+
spanId: "absent",
|
|
6700
|
+
timestamp: "2026-01-01T00:00:00.123Z"
|
|
6701
|
+
}
|
|
6702
|
+
});
|
|
6703
|
+
expect(lookup).not.toHaveBeenCalled();
|
|
6704
|
+
expect(spanLookup).not.toHaveBeenCalled();
|
|
6705
|
+
const [row] = await list();
|
|
6706
|
+
expect(row).toMatchObject({
|
|
6707
|
+
userId: "span-user",
|
|
6708
|
+
tags: ["provided"],
|
|
6709
|
+
timestamp: "2026-01-01T00:00:00.123Z"
|
|
6710
|
+
});
|
|
6711
|
+
expect(row).not.toHaveProperty("contextMode");
|
|
6712
|
+
expect(row).not.toHaveProperty("rootEntityId");
|
|
6713
|
+
if (isFeedback) expect(row.feedbackUserId).toBeNull();
|
|
6714
|
+
});
|
|
6715
|
+
it("rejects unsupported modes and invalid timestamps before writing", async () => {
|
|
6716
|
+
for (const contextMode of [
|
|
6717
|
+
"automatic",
|
|
6718
|
+
null,
|
|
6719
|
+
false
|
|
6720
|
+
]) expect((await post({
|
|
6721
|
+
...payload,
|
|
6722
|
+
traceId: "trace-123"
|
|
6723
|
+
}, contextMode)).status).toBe(400);
|
|
6724
|
+
for (const timestamp of [
|
|
6725
|
+
"invalid",
|
|
6726
|
+
null,
|
|
6727
|
+
123
|
|
6728
|
+
]) expect((await post({
|
|
6729
|
+
...payload,
|
|
6730
|
+
traceId: "trace-123",
|
|
6731
|
+
timestamp
|
|
6732
|
+
})).status).toBe(400);
|
|
6733
|
+
expect(await list()).toEqual([]);
|
|
6734
|
+
});
|
|
6735
|
+
it("requires the root before accepting a resolved annotation, even if the target exists", async () => {
|
|
6736
|
+
await writeSpan("child", "missing-root");
|
|
6737
|
+
for (const spanId of [
|
|
6738
|
+
void 0,
|
|
6739
|
+
"child",
|
|
6740
|
+
"missing-target"
|
|
6741
|
+
]) {
|
|
6742
|
+
const response = await post({
|
|
6743
|
+
...payload,
|
|
6744
|
+
traceId: "trace-123",
|
|
6745
|
+
spanId,
|
|
6746
|
+
tags: ["supplied"]
|
|
6747
|
+
}, "resolve");
|
|
6748
|
+
expect(response.status).toBe(404);
|
|
6749
|
+
expect(await response.json()).toMatchObject({ code: "TRACE_NOT_FOUND" });
|
|
6750
|
+
}
|
|
6751
|
+
await writeSpan("root");
|
|
6752
|
+
const response = await post({
|
|
6753
|
+
...payload,
|
|
6754
|
+
traceId: "trace-123",
|
|
6755
|
+
spanId: "missing-target"
|
|
6756
|
+
}, "resolve");
|
|
6757
|
+
expect(response.status).toBe(404);
|
|
6758
|
+
expect(await response.json()).toMatchObject({ code: "SPAN_NOT_FOUND" });
|
|
6759
|
+
expect(await list()).toEqual([]);
|
|
6760
|
+
});
|
|
6761
|
+
it.each([void 0, "child"])("resolves root tags and target context for span %j", async (spanId) => {
|
|
6762
|
+
await writeSpan("root");
|
|
6763
|
+
await writeSpan("child", "root");
|
|
6764
|
+
const response = await post({
|
|
6765
|
+
...payload,
|
|
6766
|
+
traceId: "trace-123",
|
|
6767
|
+
spanId,
|
|
6768
|
+
userId: "spoofed",
|
|
6769
|
+
tags: ["spoofed"],
|
|
6770
|
+
entityId: "spoofed",
|
|
6771
|
+
feedbackUserId: "reviewer",
|
|
6772
|
+
metadata: { override: "request" }
|
|
6773
|
+
}, "resolve");
|
|
6774
|
+
expect(response.status, await response.clone().text()).toBe(200);
|
|
6775
|
+
const [row] = await list();
|
|
6776
|
+
expect(row).toMatchObject({
|
|
6777
|
+
userId: "span-user",
|
|
6778
|
+
tags: ["root-tag"],
|
|
6779
|
+
entityId: spanId ?? "root",
|
|
6780
|
+
rootEntityId: "root",
|
|
6781
|
+
metadata: {
|
|
6782
|
+
inherited: true,
|
|
6783
|
+
override: "request",
|
|
6784
|
+
userId: "metadata-user"
|
|
6785
|
+
}
|
|
6786
|
+
});
|
|
6787
|
+
if (spanId) expect(row.parentEntityId).toBe("root");
|
|
6788
|
+
if (isFeedback) expect(row.feedbackUserId).toBe("reviewer");
|
|
6789
|
+
expect(row).not.toHaveProperty("contextMode");
|
|
6790
|
+
});
|
|
6791
|
+
it.each([
|
|
6792
|
+
void 0,
|
|
6793
|
+
"older-root",
|
|
6794
|
+
"child"
|
|
6795
|
+
])("uses the target ancestor root, or latest root without a target, for span %j", async (spanId) => {
|
|
6796
|
+
await writeSpan("older-root", null, { tags: ["older"] });
|
|
6797
|
+
await writeSpan("parent", "older-root");
|
|
6798
|
+
await writeSpan("child", "parent");
|
|
6799
|
+
await writeSpan("newer-root", null, {
|
|
6800
|
+
endedAt: /* @__PURE__ */ new Date("2026-01-01T00:00:02Z"),
|
|
6801
|
+
tags: ["newer"]
|
|
6802
|
+
});
|
|
6803
|
+
const response = await post({
|
|
6804
|
+
...payload,
|
|
6805
|
+
traceId: "trace-123",
|
|
6806
|
+
spanId
|
|
6807
|
+
}, "resolve");
|
|
6808
|
+
expect(response.status, await response.clone().text()).toBe(200);
|
|
6809
|
+
const [row] = await list();
|
|
6810
|
+
expect(row).toMatchObject({
|
|
6811
|
+
rootEntityId: spanId ? "older-root" : "newer-root",
|
|
6812
|
+
tags: spanId ? ["older"] : ["newer"],
|
|
6813
|
+
entityId: spanId ?? "newer-root"
|
|
6814
|
+
});
|
|
6815
|
+
if (spanId === "child") expect(row.parentEntityId).toBe("parent");
|
|
6816
|
+
});
|
|
6817
|
+
it.each(["missing", "cycle"])("rejects a target with a %s ancestor chain", async (chain) => {
|
|
6818
|
+
await writeSpan("unrelated-root");
|
|
6819
|
+
await writeSpan("child", "parent");
|
|
6820
|
+
await writeSpan("parent", chain === "cycle" ? "child" : "missing-root");
|
|
6821
|
+
const response = await post({
|
|
6822
|
+
...payload,
|
|
6823
|
+
traceId: "trace-123",
|
|
6824
|
+
spanId: "child"
|
|
6825
|
+
}, "resolve");
|
|
6826
|
+
expect(response.status).toBe(404);
|
|
6827
|
+
expect(await response.json()).toMatchObject({ code: "TRACE_NOT_FOUND" });
|
|
6828
|
+
expect(await list()).toEqual([]);
|
|
6829
|
+
});
|
|
6830
|
+
it("enforces trusted organization scope and authenticated feedback attribution", async () => {
|
|
6831
|
+
trustedScope = {
|
|
6832
|
+
organizationId: "trusted-org",
|
|
6833
|
+
mastra__user: { id: "authenticated-reviewer" }
|
|
6834
|
+
};
|
|
6835
|
+
const response = await post({
|
|
6836
|
+
...payload,
|
|
6837
|
+
traceId: "absent",
|
|
6838
|
+
organizationId: "spoofed-org",
|
|
6839
|
+
feedbackUserId: "spoofed-author",
|
|
6840
|
+
userId: "span-user"
|
|
6841
|
+
}, "provided");
|
|
6842
|
+
expect(response.status, await response.clone().text()).toBe(200);
|
|
6843
|
+
const [row] = await list();
|
|
6844
|
+
expect(row).toMatchObject({
|
|
6845
|
+
organizationId: "trusted-org",
|
|
6846
|
+
userId: "span-user"
|
|
6847
|
+
});
|
|
6848
|
+
if (isFeedback) expect(row.feedbackUserId).toBe("authenticated-reviewer");
|
|
6849
|
+
await writeSpan("root");
|
|
6850
|
+
const resolved = await post({
|
|
6851
|
+
...payload,
|
|
6852
|
+
traceId: "trace-123",
|
|
6853
|
+
organizationId: "trusted-org"
|
|
6854
|
+
}, "resolve");
|
|
6855
|
+
expect(resolved.status).toBe(404);
|
|
6856
|
+
expect(await resolved.json()).toMatchObject({ code: "TRACE_NOT_FOUND" });
|
|
6857
|
+
});
|
|
6858
|
+
it.each([{
|
|
6859
|
+
field: "organizationId",
|
|
6860
|
+
contextKey: "organizationId"
|
|
6861
|
+
}, {
|
|
6862
|
+
field: "resourceId",
|
|
6863
|
+
contextKey: "mastra__resourceId"
|
|
6864
|
+
}])("does not let a caller override trusted $field during resolution", async ({ field, contextKey }) => {
|
|
6865
|
+
trustedScope = { [contextKey]: "trusted" };
|
|
6866
|
+
await writeSpan("trusted-root", null, { [field]: "trusted" });
|
|
6867
|
+
await writeSpan("foreign-root", null, { [field]: "foreign" });
|
|
6868
|
+
const rejected = await post({
|
|
6869
|
+
...payload,
|
|
6870
|
+
traceId: "trace-123",
|
|
6871
|
+
spanId: "foreign-root",
|
|
6872
|
+
[field]: "foreign"
|
|
6873
|
+
}, "resolve");
|
|
6874
|
+
expect(rejected.status).toBe(404);
|
|
6875
|
+
expect(await rejected.json()).toMatchObject({ code: "SPAN_NOT_FOUND" });
|
|
6876
|
+
expect(await list()).toEqual([]);
|
|
6877
|
+
const accepted = await post({
|
|
6878
|
+
...payload,
|
|
6879
|
+
traceId: "trace-123",
|
|
6880
|
+
spanId: "trusted-root",
|
|
6881
|
+
[field]: "foreign"
|
|
6882
|
+
}, "resolve");
|
|
6883
|
+
expect(accepted.status, await accepted.clone().text()).toBe(200);
|
|
6884
|
+
expect(await list()).toEqual([expect.objectContaining({
|
|
6885
|
+
[field]: "trusted",
|
|
6886
|
+
entityId: "trusted-root",
|
|
6887
|
+
rootEntityId: "trusted-root"
|
|
6888
|
+
})]);
|
|
6889
|
+
});
|
|
6890
|
+
it("allows self-hosted resolution without configured tenant scope", async () => {
|
|
6891
|
+
await writeSpan("root", null, {
|
|
6892
|
+
organizationId: "stored-org",
|
|
6893
|
+
resourceId: "stored-resource"
|
|
6894
|
+
});
|
|
6895
|
+
const response = await post({
|
|
6896
|
+
...payload,
|
|
6897
|
+
traceId: "trace-123",
|
|
6898
|
+
organizationId: "caller-org",
|
|
6899
|
+
resourceId: "caller-resource"
|
|
6900
|
+
}, "resolve");
|
|
6901
|
+
expect(response.status, await response.clone().text()).toBe(200);
|
|
6902
|
+
expect(await list()).toEqual([expect.objectContaining({
|
|
6903
|
+
organizationId: "stored-org",
|
|
6904
|
+
resourceId: "stored-resource",
|
|
6905
|
+
rootEntityId: "root"
|
|
6906
|
+
})]);
|
|
6907
|
+
});
|
|
6908
|
+
it("still reads historical feedback and scores with no trace", async () => {
|
|
6909
|
+
const timestamp = /* @__PURE__ */ new Date();
|
|
6910
|
+
if (isFeedback) await store.createFeedback({ feedback: {
|
|
6911
|
+
feedbackId: "historical",
|
|
6912
|
+
timestamp,
|
|
6913
|
+
traceId: null,
|
|
6914
|
+
feedbackType: "thumbs",
|
|
6915
|
+
value: 1
|
|
6916
|
+
} });
|
|
6917
|
+
else await store.createScore({ score: {
|
|
6918
|
+
scoreId: "historical",
|
|
6919
|
+
timestamp,
|
|
6920
|
+
traceId: null,
|
|
6921
|
+
scorerId: "accuracy",
|
|
6922
|
+
score: .9
|
|
6923
|
+
} });
|
|
6924
|
+
expect(await list()).toEqual([expect.objectContaining({
|
|
6925
|
+
[idField]: "historical",
|
|
6926
|
+
traceId: null
|
|
6927
|
+
})]);
|
|
6928
|
+
});
|
|
6929
|
+
});
|
|
6930
|
+
}
|
|
6931
|
+
export { consumeSSEStream, createBodyLimitTestSuite, createCustomRouteFGATestSuite, createDefaultTestContext, createDurableDisconnectTestSuite, createHttpLoggingTestSuite, createKnowledgeRoutesTestSuite, createMCPRouteTestSuite, createMCPTransportTestSuite, createMultipartTestSuite, createObservabilitySignalWriteTestSuite, createRouteAdapterTestSuite, createStreamDisconnectTestSuite, createStreamWithSensitiveData, createStreamWithUnserializableChunk, createStructuredWakeTestSuite, expectSerializedStreamChunks };
|
|
5726
6932
|
|
|
5727
6933
|
//# sourceMappingURL=index.js.map
|