Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥
TypeScript aiai-agentsai-crawlerai-scrapingai-searchcrawlerdata-extractionhtml-to-markdownllmmarkdownscraperscrapingweb-crawlerweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
feat(api): accept optional session and thread ids on MCP action logs (#5436)
Rakshith Ramprakashc2b83bdd51cd
diff --git a/apps/api/src/services/mcp/action-logs-controller.test.ts b/apps/api/src/services/mcp/action-logs-controller.test.tsindex e96ec0488..f36f80506 100644--- a/apps/api/src/services/mcp/action-logs-controller.test.ts+++ b/apps/api/src/services/mcp/action-logs-controller.test.ts@@ -72,6 +72,28 @@ describe("MCP action log controllers", () => {);});+ it("persists no session or thread ids for teams with forced zero-data retention", async () => {+ mocks.policy.mockResolvedValue({ flags: { scrapeZDR: "forced" } });+ const res = response();+ await ingestMcpActionLogController(+ {+ body: {+ team_id: "team",+ session_id: "session-1",+ session_source: "token",+ thread_id: "thread-1",+ thread_source: "argument",+ },+ } as any,+ res,+ );+ expect(mocks.record).not.toHaveBeenCalled();+ expect(res.status).toHaveBeenCalledWith(202);+ expect(res.json).toHaveBeenCalledWith(+ expect.objectContaining({ disposition: "zero-data-retention", id: null }),+ );+ });+it("fails closed when team retention policy cannot be resolved", async () => {mocks.policy.mockResolvedValue(null);const res = response();diff --git a/apps/api/src/services/mcp/action-logs.test.ts b/apps/api/src/services/mcp/action-logs.test.tsindex 98749e354..e5fbda8aa 100644--- a/apps/api/src/services/mcp/action-logs.test.ts+++ b/apps/api/src/services/mcp/action-logs.test.ts@@ -309,6 +309,139 @@ describe("MCP action log contract", () => {);});+ it("stores optional session and thread ids with their sources", () => {+ expect(input()).toMatchObject({+ session_id: null,+ session_source: null,+ thread_id: null,+ thread_source: null,+ });+ expect(+ input({+ session_id: "AbC-123_xyz.789:abcdefg",+ session_source: "token",+ thread_id: "0b7c9a8e-1f2d-4e3c-9b8a-7f6e5d4c3b2a",+ thread_source: "argument",+ }),+ ).toMatchObject({+ session_id: "AbC-123_xyz.789:abcdefg",+ session_source: "token",+ thread_id: "0b7c9a8e-1f2d-4e3c-9b8a-7f6e5d4c3b2a",+ thread_source: "argument",+ });+ expect(+ input({+ session_id: "s".repeat(128),+ thread_id: "t",+ thread_source: "minted",+ }),+ ).toMatchObject({+ session_id: "s".repeat(128),+ session_source: null,+ thread_id: "t",+ thread_source: "minted",+ });+ expect(+ input({+ thread_id: "0f8fad5b-d9cb-869f-a165-70867728950e",+ thread_source: "client",+ }),+ ).toMatchObject({+ thread_id: "0f8fad5b-d9cb-869f-a165-70867728950e",+ thread_source: "client",+ });+ });++ it("stores a credential-like session or thread id as null instead of rejecting the event", async () => {+ ch.logMcpActionLog.mockReset().mockResolvedValue(undefined);+ await expect(+ recordMcpActionLog(+ input({+ session_id: "fc-FAKESECRET1234567890",+ session_source: "trace",+ }),+ ),+ ).resolves.toEqual({ disposition: "accepted", id: REQUEST_ID });+ expect(ch.logMcpActionLog.mock.calls[0][0]).toMatchObject({+ id: REQUEST_ID,+ session_id: null,+ session_source: null,+ });++ expect(+ input({+ session_id: "fc-FAKESECRET1234567890",+ session_source: "token",+ thread_id: "sk-FAKESECRET1234567890",+ thread_source: "argument",+ }),+ ).toMatchObject({+ session_id: null,+ session_source: null,+ thread_id: null,+ thread_source: null,+ });+ expect(+ input({+ session_id: "fc-FAKESECRET1234567890",+ thread_id: "thread-1",+ thread_source: "minted",+ }),+ ).toMatchObject({+ session_id: null,+ thread_id: "thread-1",+ thread_source: "minted",+ });+ for (const id of [+ "x_fc-FAKESECRET1234567890",+ "_sk-FAKESECRET1234567890",+ "s_fcmcp_FAKESECRET1234567890",+ ]) {+ expect(+ input({+ session_id: id,+ session_source: "token",+ thread_id: id,+ thread_source: "client",+ }),+ ).toMatchObject({+ session_id: null,+ session_source: null,+ thread_id: null,+ thread_source: null,+ });+ }+ expect(() =>+ input({+ session_id: "fc-FAKESECRET1234567890",+ session_source: "header",+ }),+ ).toThrow("session_source must be one of token, trace, sse");+ });++ it("rejects malformed session and thread fields", () => {+ for (const session_id of ["s".repeat(129), "has space", "a/b", 42]) {+ expect(() => input({ session_id })).toThrow(+ "session_id must be 1-128 letters, digits, dots, underscores, colons or hyphens",+ );+ }+ expect(() => input({ thread_id: "é" })).toThrow(+ "thread_id must be 1-128 letters, digits, dots, underscores, colons or hyphens",+ );+ expect(() =>+ input({ session_id: "abc", session_source: "header" }),+ ).toThrow("session_source must be one of token, trace, sse");+ expect(() => input({ thread_id: "abc", thread_source: "Session" })).toThrow(+ "thread_source must be one of argument, session, minted, client",+ );+ expect(() => input({ session_source: "token" })).toThrow(+ "session_source requires session_id",+ );+ expect(() => input({ thread_source: "session" })).toThrow(+ "thread_source requires thread_id",+ );+ });+it("validates API-key and OAuth actors against the claimed team", async () => {const apiKeyDb = {select: vi.fn(() => ({@@ -392,6 +525,10 @@ describe("MCP action log contract", () => {duration_ms: 55,invalid_arguments: ["limit:invalid_type"],rate_limit_retry: "recovered",+ session_id: "AbC-123_xyz.789:abcdefg",+ session_source: "trace",+ thread_id: "AbC-123_xyz.789:abcdefg",+ thread_source: "session",}),),).resolves.toEqual({ disposition: "accepted", id: REQUEST_ID });@@ -411,6 +548,10 @@ describe("MCP action log contract", () => {duration_ms: 55,invalid_arguments: ["limit:invalid_type"],rate_limit_retry: "recovered",+ session_id: "AbC-123_xyz.789:abcdefg",+ session_source: "trace",+ thread_id: "AbC-123_xyz.789:abcdefg",+ thread_source: "session",});expect(row).not.toHaveProperty("user_agent");diff --git a/apps/api/src/services/mcp/action-logs.ts b/apps/api/src/services/mcp/action-logs.tsindex 897885dfa..24cafd89c 100644--- a/apps/api/src/services/mcp/action-logs.ts+++ b/apps/api/src/services/mcp/action-logs.ts@@ -28,6 +28,11 @@ const RATE_LIMIT_RETRY_OUTCOMES = ["not_retryable",] as const;const DURATION_MS_MAX = 2_147_483_647;+const LINEAGE_ID_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/;+const SESSION_SOURCES = ["token", "trace", "sse"] as const;+const THREAD_SOURCES = ["argument", "session", "minted", "client"] as const;+const LINEAGE_ID_SECRET_PATTERN =+ /(?:^|[^A-Za-z0-9])(?:sk-|fc-|fco_|fcr_|fcmcp_)/i;const INVALID_ARGUMENTS_MAX = 10;const INVALID_ARGUMENT_PATTERN =/^(?:\(root\)|\*|[A-Za-z0-9_.-]{1,64}):[a-z_]{1,40}$/;@@ -56,6 +61,10 @@ const ALLOWED_FIELDS = new Set(["duration_ms","invalid_arguments","rate_limit_retry",+ "session_id",+ "session_source",+ "thread_id",+ "thread_source",]);export class McpActionLogValidationError extends Error {}@@ -161,6 +170,34 @@ function invalidArguments(value: unknown) {return value as string[];}+function lineage<T extends string>(+ payload: Record<string, unknown>,+ kind: "session" | "thread",+ values: readonly T[],+): { id: string | null; source: T | null } {+ const id = payload[`${kind}_id`];+ const source = payload[`${kind}_source`];+ const hasId = id != null && id !== "";+ const hasSource = source != null && source !== "";+ if (hasId && (typeof id !== "string" || !LINEAGE_ID_PATTERN.test(id))) {+ invalid(+ `${kind}_id must be 1-128 letters, digits, dots, underscores, colons or hyphens`,+ );+ }+ if (hasSource && !values.includes(source as T)) {+ invalid(`${kind}_source must be one of ${values.join(", ")}`);+ }+ if (hasSource && !hasId) invalid(`${kind}_source requires ${kind}_id`);+ const usable =+ hasId &&+ !SECRET_PATTERN.test(id as string) &&+ !LINEAGE_ID_SECRET_PATTERN.test(id as string);+ return {+ id: usable ? (id as string) : null,+ source: usable && hasSource ? (source as T) : null,+ };+}+type McpActionLogInput = {team_id: string;user_id: string | null;@@ -184,6 +221,10 @@ type McpActionLogInput = {duration_ms: number | null;invalid_arguments: string[];rate_limit_retry: (typeof RATE_LIMIT_RETRY_OUTCOMES)[number] | null;+ session_id: string | null;+ session_source: (typeof SESSION_SOURCES)[number] | null;+ thread_id: string | null;+ thread_source: (typeof THREAD_SOURCES)[number] | null;};type McpActionLogRow = {@@ -255,6 +296,8 @@ export function normalizeMcpActionLogInput(if (!RESOURCES.has(resource)) {invalid("resource must be a canonical hosted MCP URL");}+ const session = lineage(payload, "session", SESSION_SOURCES);+ const thread = lineage(payload, "thread", THREAD_SOURCES);return {team_id: uuid(payload.team_id, "team_id")!,user_id: userId,@@ -279,6 +322,10 @@ export function normalizeMcpActionLogInput(duration_ms: durationMs(payload.duration_ms),invalid_arguments: invalidArguments(payload.invalid_arguments),rate_limit_retry: rateLimitRetry as McpActionLogInput["rate_limit_retry"],+ session_id: session.id,+ session_source: session.source,+ thread_id: thread.id,+ thread_source: thread.source,};}