The best way to control Claude Code, Codex and more from any computer or phone
feat(server): count which T3 MCP tools agents use (#15913)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 18, 2026 at 19:23 UTC
ab6be13d438abeace7617e8d789d59cf2e880f42
8 files changed
+975
-3
apps/server/src/mcp/McpHttpServer.ts
+205
-3
@@ -13,7 +13,12 @@ import * as Stream from "effect/Stream";
13
import type * as Types from "effect/Types";
14
import { AiError, McpProtocol, McpSchema, McpServer, Tool, Toolkit } from "effect/ai";
15
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";
16
-import { OrchestratorMcpFailure, PreviewAutomationError } from "@t3tools/contracts";
16
+import {
17
+ OrchestratorMcpFailure,
18
+ PreviewAutomationError,
19
+ type RunId,
20
+ ThreadId,
21
+} from "@t3tools/contracts";
22
23
import packageJson from "../../package.json" with { type: "json" };
24
import * as ServerConfig from "../config.ts";
@@ -21,6 +26,15 @@ import * as DeviceService from "../device/DeviceService.ts";
26
import * as HtmlRender from "../htmlRender/HtmlRender.ts";
27
import * as ThreadCommandExecutor from "../orchestration-v2/ThreadCommandExecutor.ts";
28
import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
29
+import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
30
+import * as AnalyticsService from "../telemetry/AnalyticsService.ts";
31
+import {
32
+ type AgentThread,
33
+ agentToolProperties,
34
+ handoffSettings,
35
+ MAX_REPORTED_DEPTH,
36
+ toolOutcome,
37
+} from "../telemetry/ProviderDimensions.ts";
38
import * as McpInvocationContext from "./McpInvocationContext.ts";
39
import * as McpToolAccess from "./McpToolAccess.ts";
40
import * as OrchestratorMcpService from "./OrchestratorMcpService.ts";
@@ -746,6 +760,189 @@ const registerHtmlPreview = Effect.fn("McpHttpServer.registerHtmlPreview")(funct
760
);
761
});
762
763
+/**
764
+ * Tools that hand work to another thread's agent: they create it, message it,
765
+ * steer it, or move context into it. Their events name the receiving agent too.
766
+ */
767
+const HANDOFF_TOOLS: ReadonlySet<string> = new Set([
768
+ "delegate_task",
769
+ "create_threads",
770
+ "t3_thread_launch",
771
+ "t3_thread_send",
772
+ "t3_thread_send_attachments",
773
+ "t3_thread_fork",
774
+ "t3_thread_merge_back",
775
+ "t3_queue_edit",
776
+ "t3_queue_promote_to_steer",
777
+ "t3_pending_request_respond",
778
+ "schedule_task",
779
+ "run_scheduled_task_now",
780
+]);
781
+
782
+/** Handoff tools whose result is only `{ sequence }`; their input names the receiving thread. */
783
+const INPUT_TARGET_TOOLS: ReadonlySet<string> = new Set([
784
+ "t3_queue_edit",
785
+ "t3_queue_promote_to_steer",
786
+ "t3_pending_request_respond",
787
+]);
788
+
789
+const resultThreadKeys = ["childThreadId", "targetThreadId", "boundThreadId", "threadId"] as const;
790
+
791
+/** Thread ids a handoff tool result names: the thread that received the work. */
792
+const resultThreadIds = (content: unknown): ReadonlyArray<string> => {
793
+ if (typeof content !== "object" || content === null) return [];
794
+ const record = content as Readonly<Record<string, unknown>>;
795
+ if (Array.isArray(record.threads)) return record.threads.flatMap(resultThreadIds);
796
+ const key = resultThreadKeys.find((candidate) => typeof record[candidate] === "string");
797
+ return key === undefined ? [] : [record[key] as string];
798
+};
799
+
800
+/**
801
+ * Thread ids that received a handoff. The input's `threadId` is used only after
802
+ * the call succeeded, so it is one the handler already resolved and authorized.
803
+ */
804
+const handoffTargetIds = (
805
+ tool: string,
806
+ args: unknown,
807
+ result: McpSchema.CallToolResult | undefined,
808
+): ReadonlyArray<string> => {
809
+ if (!INPUT_TARGET_TOOLS.has(tool)) return resultThreadIds(result?.structuredContent);
810
+ if (result === undefined || toolOutcome(result).outcome !== "ok") return [];
811
+ const threadId = (args as { readonly threadId?: unknown } | null | undefined)?.threadId;
812
+ return typeof threadId === "string" ? [threadId] : [];
813
+};
814
+
815
+/**
816
+ * Runs a tool registration against a server that records one anonymous
817
+ * `mcp.tool.invoked` event per call: the tool, the calling agent's provider,
818
+ * the outcome with its failure code, and the duration. A handoff tool also
819
+ * reports the caller's model, origin, and delegation depth, the settings the
820
+ * agent chose, and the provider, model, and modes of each thread that received
821
+ * the work. Ids, prompts, and free text are never recorded.
822
+ */
823
+const withToolAnalytics = <A, E, R>(registration: Effect.Effect<A, E, R>) =>
824
+ Effect.gen(function* () {
825
+ const server = yield* McpServer.McpServer;
826
+ const analytics = yield* Effect.serviceOption(AnalyticsService.AnalyticsService);
827
+ if (Option.isNone(analytics)) return yield* registration;
828
+ const registry = yield* Effect.serviceOption(ProviderRegistry.ProviderRegistry);
829
+ const threads = yield* Effect.serviceOption(ThreadManagementService.ThreadManagementService);
830
+ const shellOf = (threadId: string) =>
831
+ Option.isNone(threads)
832
+ ? Effect.succeed(null)
833
+ : threads.value
834
+ .getThreadShell(ThreadId.make(threadId))
835
+ .pipe(Effect.orElseSucceed(() => null));
836
+ // Delegation depth: parents walked from the caller, capped.
837
+ const depthOf = (thread: AgentThread) =>
838
+ Effect.gen(function* () {
839
+ let depth = 0;
840
+ let parentId =
841
+ thread.lineage.relationshipToParent === "subagent" ? thread.lineage.parentThreadId : null;
842
+ while (parentId !== null && depth < MAX_REPORTED_DEPTH) {
843
+ depth += 1;
844
+ const parent = yield* shellOf(parentId);
845
+ parentId =
846
+ parent?.lineage.relationshipToParent === "subagent"
847
+ ? parent.lineage.parentThreadId
848
+ : null;
849
+ }
850
+ return depth;
851
+ });
852
+ // Whether the caller's active run was started by a scheduled task.
853
+ const scheduledRunOf = (threadId: string, runId: RunId | null) =>
854
+ Option.isNone(threads) || runId === null
855
+ ? Effect.succeed(false)
856
+ : threads.value
857
+ .getThreadRecords(ThreadId.make(threadId), ["runs", "messages"], {
858
+ runIds: [runId],
859
+ messageRoles: ["user"],
860
+ })
861
+ .pipe(
862
+ Effect.map((records) => {
863
+ const run = records.runs.find((candidate) => candidate.id === runId);
864
+ return records.messages.some(
865
+ (message) =>
866
+ message.id === run?.userMessageId && message.scheduledTaskId !== undefined,
867
+ );
868
+ }),
869
+ Effect.orElseSucceed(() => false),
870
+ );
871
+ const record = (
872
+ tool: string,
873
+ args: unknown,
874
+ result: McpSchema.CallToolResult | undefined,
875
+ durationMs: number,
876
+ ) =>
877
+ Effect.gen(function* () {
878
+ // Client credentials (no calling thread) report an unknown caller.
879
+ const invocation = Option.getOrUndefined(
880
+ yield* Effect.serviceOption(McpInvocationContext.McpInvocationContext),
881
+ )?.thread;
882
+ const providers = Option.isSome(registry) ? yield* registry.value.getProviders : [];
883
+ // Only handoff tools pay for thread lookups; the rest report the
884
+ // caller's provider from the credential.
885
+ const handoff = HANDOFF_TOOLS.has(tool);
886
+ const caller =
887
+ handoff && invocation !== undefined
888
+ ? ((yield* shellOf(invocation.threadId)) ?? undefined)
889
+ : undefined;
890
+ const targetIds = handoff
891
+ ? [...new Set(handoffTargetIds(tool, args, result))].filter(
892
+ (threadId) => threadId !== invocation?.threadId,
893
+ )
894
+ : [];
895
+ const targets = yield* Effect.forEach(targetIds, shellOf);
896
+ for (const properties of agentToolProperties({
897
+ tool,
898
+ providers,
899
+ caller,
900
+ ...(invocation === undefined
901
+ ? {}
902
+ : { callerProviderInstanceId: invocation.providerInstanceId }),
903
+ ...(caller === undefined || invocation === undefined
904
+ ? {}
905
+ : {
906
+ callerDepth: yield* depthOf(caller),
907
+ callerScheduledRun: yield* scheduledRunOf(invocation.threadId, caller.activeRunId),
908
+ }),
909
+ targets: targets.filter((thread) => thread !== null),
910
+ outcome: toolOutcome(result),
911
+ ...(handoff ? { settings: handoffSettings(tool, args, result?.structuredContent) } : {}),
912
+ durationMs,
913
+ })) {
914
+ yield* analytics.value.record("mcp.tool.invoked", properties);
915
+ }
916
+ }).pipe(Effect.ignoreCause);
917
+ const recordingServer = McpServer.McpServer.of({
918
+ ...server,
919
+ addTool: (options) =>
920
+ server.addTool({
921
+ ...options,
922
+ handle: (payload) =>
923
+ Effect.gen(function* () {
924
+ const startedAt = yield* Clock.currentTimeMillis;
925
+ return yield* options.handle(payload).pipe(
926
+ Effect.onExit((exit) => {
927
+ const result = exit._tag === "Success" ? exit.value : undefined;
928
+ // A call that asks for input is retried with it, and that call is the one counted.
929
+ if (result instanceof McpSchema.InputRequired) return Effect.void;
930
+ // Handoff tools look up threads to record; the response must not wait on them.
931
+ return Clock.currentTimeMillis.pipe(
932
+ Effect.flatMap((endedAt) =>
933
+ record(options.tool.name, payload, result, endedAt - startedAt),
934
+ ),
935
+ Effect.forkDetach,
936
+ Effect.asVoid,
937
+ );
938
+ }),
939
+ );
940
+ }),
941
+ }),
942
+ });
943
+ return yield* registration.pipe(Effect.provideService(McpServer.McpServer, recordingServer));
944
+ });
945
+
946
/**
947
* `McpServer.toolkit` asks for every service its tools declare when it
948
* registers them, but the auth middleware provides `McpInvocationContext` to
@@ -756,7 +953,9 @@ export const toolkitRegistration = <Tools extends Record<string, Tool.Any>, EX,
953
toolkit: Toolkit.Toolkit<Tools>,
954
handlers: McpToolAccess.HandlersLayer<Tools, EX, RX>,
955
) => {
759
- const registration = McpServer.toolkit(decodeAsAdvertised(toolkit));
956
+ const registration = Layer.effectDiscard(
957
+ withToolAnalytics(McpServer.registerToolkit(decodeAsAdvertised(toolkit))),
958
+ ).pipe(Layer.provide(McpServer.McpServer.layer));
959
// @effect-diagnostics-next-line unsafeEffectTypeAssertion:off - the auth middleware provides it per request.
960
const registered = registration as Layer.Layer<
961
never,
@@ -769,7 +968,10 @@ export const toolkitRegistration = <Tools extends Record<string, Tool.Any>, EX,
968
const imageToolRegistration = <Tools extends Record<string, Tool.Any>, A, E, R, EX, RX>(
969
register: Effect.Effect<A, E, R>,
970
handlers: McpToolAccess.HandlersLayer<Tools, EX, RX>,
772
-) => Layer.effectDiscard(register).pipe(Layer.provide(McpToolAccess.HandlersLayer.layer(handlers)));
971
+) =>
972
+ Layer.effectDiscard(withToolAnalytics(register)).pipe(
973
+ Layer.provide(McpToolAccess.HandlersLayer.layer(handlers)),
974
+ );
975
976
export const layerHtmlToolkit = Layer.mergeAll(
977
toolkitRegistration(HtmlRenderToolkit, HtmlHandlers.layerRender),
apps/server/src/mcp/toolkits/core.test.ts
+127
@@ -18,6 +18,7 @@ import {
18
type OrchestrationV2ProjectedTurnItem,
19
type OrchestrationV2ThreadShell,
20
} from "@t3tools/contracts";
21
+import * as Deferred from "effect/Deferred";
22
import * as Effect from "effect/Effect";
23
import * as TestClock from "effect/testing/TestClock";
24
import * as Layer from "effect/Layer";
@@ -49,6 +50,7 @@ import * as McpHttpServer from "../McpHttpServer.ts";
50
import * as McpInvocationContext from "../McpInvocationContext.ts";
51
import * as McpToolAccessTestkit from "../McpToolAccess.testkit.ts";
52
import { dispatchFailure } from "../threadAccess.ts";
53
+import * as AnalyticsService from "../../telemetry/AnalyticsService.ts";
54
import { OrchestratorToolkit } from "./orchestrator/tools.ts";
55
import { PreviewToolkit } from "./preview/tools.ts";
56
import { PreviewControlsToolkit } from "./previewControls/tools.ts";
@@ -362,6 +364,131 @@ it.effect("keeps unexpected handler defects private through the production regis
364
),
365
);
366
367
+it.effect("records the calling agent and the agent a tool acted on", () => {
368
+ // Recording runs detached from the tool response, so each expected event is awaited.
369
+ const recorded = [
370
+ Deferred.makeUnsafe<{ event: string; properties: object }>(),
371
+ Deferred.makeUnsafe<{ event: string; properties: object }>(),
372
+ ];
373
+ let recordedCount = 0;
374
+ const shell = (id: ThreadId, instanceId: string, model: string) =>
375
+ ({
376
+ id,
377
+ projectId: "mcp-core-project",
378
+ providerInstanceId: ProviderInstanceId.make(instanceId),
379
+ modelSelection: { instanceId: ProviderInstanceId.make(instanceId), model },
380
+ runtimeMode: "full-access",
381
+ interactionMode: "default",
382
+ archivedAt: null,
383
+ deletedAt: null,
384
+ activeRunId: "mcp-core-run",
385
+ createdBy: "agent",
386
+ creationSource: "mcp",
387
+ lineage: {
388
+ parentThreadId: id === threadId ? ThreadId.make("mcp-core-parent") : null,
389
+ relationshipToParent: id === threadId ? "subagent" : null,
390
+ rootThreadId: ThreadId.make("mcp-core-parent"),
391
+ },
392
+ }) as never;
393
+ return Effect.gen(function* () {
394
+ const server = yield* McpServer.McpServer;
395
+ yield* server
396
+ .callTool({ name: "t3_thread_fork", arguments: { sourcePoint: { type: "latest_stable" } } })
397
+ .pipe(
398
+ Effect.provideService(McpInvocationContext.McpInvocationContext, scope),
399
+ Effect.provideService(McpSchema.McpServerClient, client),
400
+ );
401
+ const { event, properties } = yield* Deferred.await(recorded[0]!);
402
+ expect(event).toBe("mcp.tool.invoked");
403
+ expect(properties).toMatchObject({
404
+ tool: "t3_thread_fork",
405
+ outcome: "ok",
406
+ callerProvider: "codex",
407
+ callerModel: "gpt-5.5",
408
+ callerOrigin: "agent",
409
+ callerDepth: 1,
410
+ targetProvider: "claudeAgent",
411
+ targetModel: "claude-opus-5-5",
412
+ targetRuntimeMode: "full-access",
413
+ targetInteractionMode: "default",
414
+ crossProvider: true,
415
+ });
416
+ expect(properties).toHaveProperty("durationMs");
417
+ expect(Object.values(properties).some((value) => String(value).includes("mcp-core"))).toBe(
418
+ false,
419
+ );
420
+
421
+ // Queue tools return only a sequence, so the receiving thread comes from the input.
422
+ yield* server
423
+ .callTool({
424
+ name: "t3_queue_edit",
425
+ arguments: { threadId: "mcp-core-other", queuedRunId: "mcp-core-queued", text: "secret" },
426
+ })
427
+ .pipe(
428
+ Effect.provideService(McpInvocationContext.McpInvocationContext, scope),
429
+ Effect.provideService(McpSchema.McpServerClient, client),
430
+ );
431
+ // The fork recorded a single event, so the next one is the queue edit.
432
+ expect((yield* Deferred.await(recorded[1]!)).properties).toMatchObject({
433
+ tool: "t3_queue_edit",
434
+ outcome: "ok",
435
+ callerProvider: "codex",
436
+ targetProvider: "claudeAgent",
437
+ crossProvider: true,
438
+ });
439
+ }).pipe(
440
+ Effect.provide(
441
+ layerThreadToolkit.pipe(
442
+ Layer.provideMerge(McpServer.McpServer.layer),
443
+ Layer.provide(NodeCrypto.layer),
444
+ Layer.provide(
445
+ Layer.mock(ThreadManagement.ThreadManagementService)({
446
+ getThreadShell: (id) =>
447
+ Effect.succeed(
448
+ id === threadId
449
+ ? shell(threadId, "codex", "gpt-5.5")
450
+ : shell(id, "claudeAgent", "claude-opus-5-5"),
451
+ ),
452
+ getThreadRecords: () => Effect.succeed({ runs: [], messages: [] } as never),
453
+ getProjectThreadRecords: () =>
454
+ Effect.succeed({ thread: shell(threadId, "codex", "gpt-5.5") } as never),
455
+ dispatch: () => Effect.succeed({ sequence: 1 } as never),
456
+ }),
457
+ ),
458
+ Layer.provide(
459
+ Layer.mock(ProviderRegistry.ProviderRegistry)({
460
+ getProviders: Effect.succeed([
461
+ {
462
+ instanceId: ProviderInstanceId.make("codex"),
463
+ driver: "codex",
464
+ models: [{ slug: "gpt-5.5", isCustom: false }],
465
+ } as never,
466
+ {
467
+ instanceId: ProviderInstanceId.make("claudeAgent"),
468
+ driver: "claudeAgent",
469
+ models: [{ slug: "claude-opus-5-5", isCustom: false }],
470
+ } as never,
471
+ ]),
472
+ }),
473
+ ),
474
+ Layer.provide(
475
+ Layer.succeed(
476
+ AnalyticsService.AnalyticsService,
477
+ AnalyticsService.AnalyticsService.of({
478
+ record: (event, properties) =>
479
+ Deferred.succeed(recorded[recordedCount++]!, {
480
+ event,
481
+ properties: properties ?? {},
482
+ }).pipe(Effect.asVoid),
483
+ flush: Effect.void,
484
+ }),
485
+ ),
486
+ ),
487
+ ),
488
+ ),
489
+ );
490
+});
491
+
492
it("keeps MCP preference output allowlisted and Unicode-bounded", () => {
493
const settings = {
494
...DEFAULT_SERVER_SETTINGS,
apps/server/src/server.ts
+2
@@ -45,6 +45,7 @@ import * as PullRequestReviewGuides from "./persistence/PullRequestReviewGuides.
45
import * as PullRequestReviewGuideService from "./pullRequest/PullRequestReviewGuideService.ts";
46
import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
47
import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
48
+import * as DelegatedTaskAnalytics from "./telemetry/DelegatedTaskAnalytics.ts";
49
import * as ProviderEventIngestor from "./orchestration-v2/ProviderEventIngestor.ts";
50
import * as ModelManifest from "./provider/ModelManifest.ts";
51
import * as ResetCreditCoordinator from "./provider/resetCreditCoordinator.ts";
@@ -554,6 +555,7 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll(
555
),
556
),
557
layerThreadPullRequestWorker,
558
+ DelegatedTaskAnalytics.layer,
559
Layer.effectDiscard(
560
Effect.gen(function* () {
561
const service = yield* PullRequestSyncReactor.PullRequestSyncReactor;
apps/server/src/telemetry/DelegatedTaskAnalytics.test.ts
new
+102
@@ -0,0 +1,102 @@
1
+import { ProviderInstanceId, ThreadId } from "@t3tools/contracts";
2
+import { expect, it } from "@effect/vitest";
3
+import * as DateTime from "effect/DateTime";
4
+import * as Effect from "effect/Effect";
5
+import * as Layer from "effect/Layer";
6
+import * as Stream from "effect/Stream";
7
+
8
+import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
9
+import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
10
+import * as AnalyticsService from "./AnalyticsService.ts";
11
+import * as DelegatedTaskAnalytics from "./DelegatedTaskAnalytics.ts";
12
+
13
+const parentThreadId = ThreadId.make("parent-private");
14
+
15
+const subagentEvent = (status: string, origin = "app_owned") =>
16
+ ({
17
+ type: "subagent.updated",
18
+ payload: {
19
+ id: "task-private",
20
+ threadId: parentThreadId,
21
+ origin,
22
+ status,
23
+ providerInstanceId: ProviderInstanceId.make("claudeAgent"),
24
+ model: "claude-opus-5-5",
25
+ prompt: "secret task",
26
+ completionWake: "always",
27
+ startedAt: DateTime.makeUnsafe(0),
28
+ completedAt: DateTime.makeUnsafe(90_000),
29
+ },
30
+ }) as never;
31
+
32
+it.effect("records each delegated task's final outcome once, without ids or prompts", () => {
33
+ const recorded: Array<{ event: string; properties: unknown }> = [];
34
+ let shellLookups = 0;
35
+ return Effect.gen(function* () {
36
+ const analytics = yield* DelegatedTaskAnalytics.DelegatedTaskAnalytics;
37
+ yield* analytics.onSubagent(subagentEvent("running"));
38
+ yield* analytics.onSubagent(subagentEvent("completed", "provider_native"));
39
+ // The first parent lookup fails; the next final update still reports the task.
40
+ yield* analytics.onSubagent(subagentEvent("completed"));
41
+ yield* analytics.onSubagent(subagentEvent("completed"));
42
+ yield* analytics.onSubagent(subagentEvent("completed"));
43
+ expect(recorded).toEqual([
44
+ {
45
+ event: "mcp.delegated_task.finished",
46
+ properties: {
47
+ status: "completed",
48
+ callerProvider: "codex",
49
+ callerModel: "gpt-5.5",
50
+ targetProvider: "claudeAgent",
51
+ targetModel: "claude-opus-5-5",
52
+ crossProvider: true,
53
+ completionWake: "always",
54
+ durationSeconds: 90,
55
+ },
56
+ },
57
+ ]);
58
+ }).pipe(
59
+ Effect.provide(
60
+ DelegatedTaskAnalytics.layer.pipe(
61
+ Layer.provide(
62
+ Layer.mergeAll(
63
+ Layer.mock(Orchestrator.OrchestratorV2)({
64
+ streamDomainEvents: Stream.empty,
65
+ getThreadShell: () =>
66
+ ++shellLookups === 1
67
+ ? Effect.die("thread store unavailable")
68
+ : Effect.succeed({
69
+ modelSelection: {
70
+ instanceId: ProviderInstanceId.make("codex"),
71
+ model: "gpt-5.5",
72
+ },
73
+ } as never),
74
+ }),
75
+ Layer.mock(ProviderRegistry.ProviderRegistry)({
76
+ getProviders: Effect.succeed([
77
+ {
78
+ instanceId: ProviderInstanceId.make("codex"),
79
+ driver: "codex",
80
+ models: [{ slug: "gpt-5.5", isCustom: false }],
81
+ } as never,
82
+ {
83
+ instanceId: ProviderInstanceId.make("claudeAgent"),
84
+ driver: "claudeAgent",
85
+ models: [{ slug: "claude-opus-5-5", isCustom: false }],
86
+ } as never,
87
+ ]),
88
+ }),
89
+ Layer.succeed(
90
+ AnalyticsService.AnalyticsService,
91
+ AnalyticsService.AnalyticsService.of({
92
+ record: (event, properties) =>
93
+ Effect.sync(() => void recorded.push({ event, properties })),
94
+ flush: Effect.void,
95
+ }),
96
+ ),
97
+ ),
98
+ ),
99
+ ),
100
+ ),
101
+ );
102
+});
apps/server/src/telemetry/DelegatedTaskAnalytics.ts
new
+93
@@ -0,0 +1,93 @@
1
+/**
2
+ * Records one anonymous `mcp.delegated_task.finished` event when an app-owned
3
+ * delegated task reaches a final status, so we can see whether delegation
4
+ * between providers actually completes. The event carries the parent and child
5
+ * provider and model, the final status, and the child's runtime in seconds.
6
+ *
7
+ * @module DelegatedTaskAnalytics
8
+ */
9
+import type { OrchestrationV2DomainEvent } from "@t3tools/contracts";
10
+import * as DateTime from "effect/DateTime";
11
+import * as Context from "effect/Context";
12
+import * as Effect from "effect/Effect";
13
+import * as Layer from "effect/Layer";
14
+import * as Stream from "effect/Stream";
15
+
16
+import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
17
+import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
18
+import { forkParked } from "../serverActivation.ts";
19
+import * as AnalyticsService from "./AnalyticsService.ts";
20
+import { crossProvider, providerDimensions } from "./ProviderDimensions.ts";
21
+
22
+type SubagentEvent = Extract<OrchestrationV2DomainEvent, { readonly type: "subagent.updated" }>;
23
+
24
+const FINAL_STATUSES: ReadonlySet<string> = new Set([
25
+ "completed",
26
+ "failed",
27
+ "cancelled",
28
+ "interrupted",
29
+]);
30
+
31
+export class DelegatedTaskAnalytics extends Context.Service<
32
+ DelegatedTaskAnalytics,
33
+ { readonly onSubagent: (event: SubagentEvent) => Effect.Effect<void> }
34
+>()("t3/telemetry/DelegatedTaskAnalytics") {}
35
+
36
+const make = Effect.gen(function* () {
37
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
38
+ const analytics = yield* AnalyticsService.AnalyticsService;
39
+ const registry = yield* ProviderRegistry.ProviderRegistry;
40
+ // A task can be re-reported with the same final status; count it once per process.
41
+ const reported = new Set<string>();
42
+
43
+ const onSubagent = (event: SubagentEvent) =>
44
+ Effect.gen(function* () {
45
+ const task = event.payload;
46
+ if (task.origin !== "app_owned" || !FINAL_STATUSES.has(task.status)) return;
47
+ if (reported.has(task.id)) return;
48
+ const parent = yield* orchestrator.getThreadShell(task.threadId);
49
+ const providers = yield* registry.getProviders;
50
+ const parentDimensions =
51
+ parent === null
52
+ ? { provider: "unknown" }
53
+ : providerDimensions(providers, parent.modelSelection);
54
+ const child = providerDimensions(providers, {
55
+ instanceId: task.providerInstanceId,
56
+ model: task.model ?? "",
57
+ });
58
+ const cross = crossProvider(parentDimensions.provider, child.provider);
59
+ const durationSeconds =
60
+ task.startedAt !== null && task.completedAt !== null
61
+ ? Math.max(
62
+ 0,
63
+ Math.round(
64
+ (DateTime.toEpochMillis(task.completedAt) -
65
+ DateTime.toEpochMillis(task.startedAt)) /
66
+ 1000,
67
+ ),
68
+ )
69
+ : undefined;
70
+ yield* analytics.record("mcp.delegated_task.finished", {
71
+ status: task.status,
72
+ callerProvider: parentDimensions.provider,
73
+ ...(parentDimensions.model === undefined ? {} : { callerModel: parentDimensions.model }),
74
+ targetProvider: child.provider,
75
+ ...(child.model === undefined ? {} : { targetModel: child.model }),
76
+ ...(cross === undefined ? {} : { crossProvider: cross }),
77
+ ...(task.completionWake === undefined ? {} : { completionWake: task.completionWake }),
78
+ ...(durationSeconds === undefined ? {} : { durationSeconds }),
79
+ });
80
+ // Only after recording: a failed lookup leaves the next final update to report it.
81
+ reported.add(task.id);
82
+ }).pipe(Effect.ignoreCause);
83
+
84
+ yield* forkParked(
85
+ Stream.runForEach(orchestrator.streamDomainEvents, (event) =>
86
+ event.type === "subagent.updated" ? onSubagent(event) : Effect.void,
87
+ ),
88
+ );
89
+
90
+ return DelegatedTaskAnalytics.of({ onSubagent });
91
+});
92
+
93
+export const layer = Layer.effect(DelegatedTaskAnalytics, make);
apps/server/src/telemetry/ProviderDimensions.test.ts
new
+226
@@ -0,0 +1,226 @@
1
+import { ProviderInstanceId, ThreadId, type ServerProvider } from "@t3tools/contracts";
2
+import { expect, it } from "@effect/vitest";
3
+
4
+import {
5
+ type AgentThread,
6
+ agentToolProperties,
7
+ handoffSettings,
8
+ callerOrigin,
9
+ toolOutcome,
10
+} from "./ProviderDimensions.ts";
11
+
12
+const provider = (
13
+ instanceId: string,
14
+ driver: string,
15
+ models: ReadonlyArray<{ slug: string; isCustom: boolean }>,
16
+) =>
17
+ ({
18
+ instanceId: ProviderInstanceId.make(instanceId),
19
+ driver,
20
+ models,
21
+ }) as unknown as ServerProvider;
22
+
23
+const providers = [
24
+ provider("work-codex", "codex", [{ slug: "gpt-5.5", isCustom: false }]),
25
+ provider("claudeAgent", "claudeAgent", [
26
+ { slug: "claude-opus-5-5", isCustom: false },
27
+ { slug: "my-private-finetune", isCustom: true },
28
+ ]),
29
+ provider("opencode", "opencode", [{ slug: "ollama/acme-internal", isCustom: false }]),
30
+];
31
+
32
+const thread = (
33
+ instanceId: string,
34
+ model: string,
35
+ overrides: Partial<AgentThread> = {},
36
+): AgentThread => ({
37
+ modelSelection: { instanceId: ProviderInstanceId.make(instanceId), model },
38
+ runtimeMode: "full-access",
39
+ interactionMode: "default",
40
+ createdBy: "user",
41
+ creationSource: "web",
42
+ lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: ThreadId.make("t") },
43
+ ...overrides,
44
+});
45
+
46
+it("relates the calling agent to each agent that received work", () => {
47
+ expect(
48
+ agentToolProperties({
49
+ tool: "create_threads",
50
+ providers,
51
+ caller: thread("work-codex", "gpt-5.5", { createdBy: "agent", creationSource: "mcp" }),
52
+ callerDepth: 1,
53
+ targets: [
54
+ thread("claudeAgent", "claude-opus-5-5", { interactionMode: "plan" }),
55
+ thread("work-codex", "gpt-5.5"),
56
+ ],
57
+ outcome: { outcome: "ok" },
58
+ settings: { batchSize: 2, targetChosen: true },
59
+ durationMs: 42,
60
+ }),
61
+ ).toEqual([
62
+ {
63
+ tool: "create_threads",
64
+ callerProvider: "codex",
65
+ callerModel: "gpt-5.5",
66
+ callerOrigin: "agent",
67
+ callerDepth: 1,
68
+ durationMs: 42,
69
+ outcome: "ok",
70
+ batchSize: 2,
71
+ targetChosen: true,
72
+ targetProvider: "claudeAgent",
73
+ targetModel: "claude-opus-5-5",
74
+ targetRuntimeMode: "full-access",
75
+ targetInteractionMode: "plan",
76
+ crossProvider: true,
77
+ },
78
+ {
79
+ tool: "create_threads",
80
+ callerProvider: "codex",
81
+ callerModel: "gpt-5.5",
82
+ callerOrigin: "agent",
83
+ callerDepth: 1,
84
+ durationMs: 42,
85
+ outcome: "ok",
86
+ batchSize: 2,
87
+ targetChosen: true,
88
+ targetProvider: "codex",
89
+ targetModel: "gpt-5.5",
90
+ targetRuntimeMode: "full-access",
91
+ targetInteractionMode: "default",
92
+ crossProvider: false,
93
+ },
94
+ ]);
95
+});
96
+
97
+it("reports a non-handoff tool from the credential's provider alone", () => {
98
+ expect(
99
+ agentToolProperties({
100
+ tool: "preview_click",
101
+ providers,
102
+ caller: undefined,
103
+ callerProviderInstanceId: ProviderInstanceId.make("claudeAgent"),
104
+ targets: [],
105
+ outcome: { outcome: "error", errorCode: "capability_denied" },
106
+ durationMs: 3,
107
+ }),
108
+ ).toEqual([
109
+ {
110
+ tool: "preview_click",
111
+ callerProvider: "claudeAgent",
112
+ durationMs: 3,
113
+ outcome: "error",
114
+ errorCode: "capability_denied",
115
+ },
116
+ ]);
117
+});
118
+
119
+it("omits custom, user-configured, and unknown models and instance names", () => {
120
+ expect(
121
+ agentToolProperties({
122
+ tool: "t3_thread_send",
123
+ providers,
124
+ caller: thread("claudeAgent", "my-private-finetune"),
125
+ targets: [thread("opencode", "ollama/acme-internal"), thread("removed-instance", "gpt-5.5")],
126
+ outcome: { outcome: "ok" },
127
+ }).map(({ callerProvider, callerModel, targetProvider, targetModel }) => ({
128
+ callerProvider,
129
+ callerModel,
130
+ targetProvider,
131
+ targetModel,
132
+ })),
133
+ ).toEqual([
134
+ {
135
+ callerProvider: "claudeAgent",
136
+ callerModel: undefined,
137
+ targetProvider: "opencode",
138
+ targetModel: undefined,
139
+ },
140
+ {
141
+ callerProvider: "claudeAgent",
142
+ callerModel: undefined,
143
+ targetProvider: "unknown",
144
+ targetModel: undefined,
145
+ },
146
+ ]);
147
+});
148
+
149
+it("reads handoff settings from enums and flags, never from prompts or ids", () => {
150
+ expect(
151
+ handoffSettings(
152
+ "delegate_task",
153
+ { task: "secret", mode: "wait", target: { driverKind: "claudeAgent" } },
154
+ { taskId: "t", waitTimedOut: true },
155
+ ),
156
+ ).toEqual({ targetChosen: true, mode: "wait", waitTimedOut: true });
157
+ expect(handoffSettings("delegate_task", { task: "secret" }, { waitTimedOut: false })).toEqual({
158
+ targetChosen: false,
159
+ mode: "async",
160
+ });
161
+ expect(
162
+ handoffSettings(
163
+ "t3_thread_launch",
164
+ { message: "secret", workspaceStrategy: { type: "worktree", branch: "private" } },
165
+ {},
166
+ ),
167
+ ).toEqual({ targetChosen: false, workspace: "worktree" });
168
+ expect(handoffSettings("t3_thread_launch", { scratch: true }, {})).toMatchObject({
169
+ workspace: "scratch",
170
+ });
171
+ expect(
172
+ handoffSettings(
173
+ "create_threads",
174
+ { threads: [{ prompt: "a" }, { prompt: "b", target: {} }] },
175
+ {},
176
+ ),
177
+ ).toEqual({ batchSize: 2, targetChosen: true });
178
+ expect(handoffSettings("t3_thread_send", { message: "secret" }, { delivery: "steered" })).toEqual(
179
+ { delivery: "steered" },
180
+ );
181
+});
182
+
183
+it("drops input strings outside the schema's literals, since rejected calls are recorded too", () => {
184
+ expect(handoffSettings("delegate_task", { mode: "/home/me/secret" }, undefined)).toEqual({
185
+ targetChosen: false,
186
+ mode: "async",
187
+ });
188
+ expect(
189
+ handoffSettings("t3_thread_launch", { workspaceStrategy: { type: "/home/me/secret" } }, {}),
190
+ ).toEqual({ targetChosen: false, workspace: "root" });
191
+});
192
+
193
+it("reports crossProvider only when both providers resolve", () => {
194
+ const [event] = agentToolProperties({
195
+ tool: "t3_thread_send",
196
+ providers,
197
+ caller: thread("work-codex", "gpt-5.5"),
198
+ targets: [thread("removed-instance", "gpt-5.5")],
199
+ outcome: { outcome: "ok" },
200
+ });
201
+ expect(event).toMatchObject({ callerProvider: "codex", targetProvider: "unknown" });
202
+ expect(event).not.toHaveProperty("crossProvider");
203
+});
204
+
205
+it("reads failure codes from declared tool errors even without isError", () => {
206
+ expect(
207
+ toolOutcome({
208
+ structuredContent: {
209
+ _tag: "OrchestratorMcpFailure",
210
+ code: "capability_denied",
211
+ message: "private detail",
212
+ },
213
+ }),
214
+ ).toEqual({ outcome: "error", errorCode: "capability_denied" });
215
+ expect(toolOutcome({ isError: false, structuredContent: { threadId: "t" } })).toEqual({
216
+ outcome: "ok",
217
+ });
218
+ expect(toolOutcome(undefined)).toEqual({ outcome: "error", errorCode: "exception" });
219
+});
220
+
221
+it("tells user, agent, system, and scheduled work apart", () => {
222
+ expect(callerOrigin({ thread: { createdBy: "user" }, scheduledRun: false })).toBe("user");
223
+ expect(callerOrigin({ thread: { createdBy: "agent" }, scheduledRun: false })).toBe("agent");
224
+ expect(callerOrigin({ thread: { createdBy: "system" }, scheduledRun: false })).toBe("system");
225
+ expect(callerOrigin({ thread: { createdBy: "user" }, scheduledRun: true })).toBe("scheduler");
226
+});
apps/server/src/telemetry/ProviderDimensions.ts
new
+210
@@ -0,0 +1,210 @@
1
+import type {
2
+ ModelSelection,
3
+ OrchestrationV2ThreadShell,
4
+ ServerProvider,
5
+} from "@t3tools/contracts";
6
+
7
+/**
8
+ * Drivers whose model catalogs are published by the vendor. Other drivers
9
+ * (OpenCode, Pi, ACP agents) list models from the user's own configuration,
10
+ * such as local Ollama tags, so their model names stay out of analytics.
11
+ */
12
+const VENDOR_CATALOG_DRIVERS: ReadonlySet<string> = new Set([
13
+ "codex",
14
+ "claudeAgent",
15
+ "cursor",
16
+ "grok",
17
+ "antigravity",
18
+]);
19
+
20
+export interface ProviderDimensions {
21
+ readonly provider: string;
22
+ readonly model?: string;
23
+}
24
+
25
+/**
26
+ * Anonymous provider and model for a model selection. Instance ids are
27
+ * user-defined, so only the driver kind is reported. The model is reported
28
+ * only when it comes from a vendor catalog and is not a user-added custom model.
29
+ */
30
+export function providerDimensions(
31
+ providers: ReadonlyArray<ServerProvider>,
32
+ selection: Pick<ModelSelection, "instanceId" | "model">,
33
+): ProviderDimensions {
34
+ const provider = providers.find((candidate) => candidate.instanceId === selection.instanceId);
35
+ if (provider === undefined) return { provider: "unknown" };
36
+ const model = provider.models.find((candidate) => candidate.slug === selection.model);
37
+ return VENDOR_CATALOG_DRIVERS.has(provider.driver) && model !== undefined && !model.isCustom
38
+ ? { provider: provider.driver, model: model.slug }
39
+ : { provider: provider.driver };
40
+}
41
+
42
+/** The thread fields agent analytics reads. Ids are used for lookups, never reported. */
43
+export type AgentThread = Pick<
44
+ OrchestrationV2ThreadShell,
45
+ "modelSelection" | "runtimeMode" | "interactionMode" | "createdBy" | "creationSource" | "lineage"
46
+>;
47
+
48
+type Fields = Readonly<Record<string, unknown>>;
49
+
50
+const asFields = (value: unknown): Fields =>
51
+ typeof value === "object" && value !== null ? (value as Fields) : {};
52
+
53
+const stringField = (fields: Fields, key: string) =>
54
+ typeof fields[key] === "string" ? (fields[key] as string) : undefined;
55
+
56
+/** A string from the tool input only when it is one of the schema's literals. */
57
+const oneOf = (value: string | undefined, allowed: ReadonlyArray<string>) =>
58
+ value !== undefined && allowed.includes(value) ? value : undefined;
59
+
60
+/**
61
+ * Whether two resolved providers differ. Unresolved selections compare as
62
+ * unknown rather than as a cross-provider handoff.
63
+ */
64
+export const crossProvider = (caller: string, target: string) =>
65
+ caller === "unknown" || target === "unknown" ? undefined : caller !== target;
66
+
67
+const defined = (entries: Readonly<Record<string, unknown>>) =>
68
+ Object.fromEntries(Object.entries(entries).filter(([, value]) => value !== undefined));
69
+
70
+/**
71
+ * How deep a thread sits in a delegation tree: 0 for a top-level thread, 1 for
72
+ * its subagent, and so on. Forks are top-level threads of their own. Depth is
73
+ * counted by walking parents, capped so a corrupt lineage cannot loop.
74
+ */
75
+export const MAX_REPORTED_DEPTH = 5;
76
+
77
+/**
78
+ * Who started the work that made this call. Scheduled runs keep the task
79
+ * creator's provenance, so the run's message marks them instead.
80
+ */
81
+export function callerOrigin(input: {
82
+ readonly thread: Pick<AgentThread, "createdBy">;
83
+ readonly scheduledRun: boolean;
84
+}) {
85
+ if (input.scheduledRun) return "scheduler";
86
+ if (input.thread.createdBy === "agent") return "agent";
87
+ return input.thread.createdBy === "system" ? "system" : "user";
88
+}
89
+
90
+/**
91
+ * Settings the agent chose for a handoff, read only from closed enums and
92
+ * booleans in the tool's arguments and result. Prompts, titles, and ids are
93
+ * never read.
94
+ */
95
+export function handoffSettings(tool: string, args: unknown, result: unknown): Fields {
96
+ const input = asFields(args);
97
+ const output = asFields(result);
98
+ switch (tool) {
99
+ case "delegate_task":
100
+ return defined({
101
+ targetChosen: input.target !== undefined,
102
+ // Rejected calls are recorded too, so input strings must match a literal.
103
+ mode: oneOf(stringField(input, "mode"), ["async", "wait"]) ?? "async",
104
+ ...(output.waitTimedOut === true ? { waitTimedOut: true } : {}),
105
+ });
106
+ case "create_threads": {
107
+ const threads = Array.isArray(input.threads) ? input.threads : [];
108
+ return {
109
+ batchSize: threads.length,
110
+ targetChosen: threads.some((thread) => asFields(thread).target !== undefined),
111
+ };
112
+ }
113
+ case "t3_thread_launch":
114
+ return defined({
115
+ targetChosen: input.modelSelection !== undefined,
116
+ workspace:
117
+ input.scratch === true
118
+ ? "scratch"
119
+ : (oneOf(stringField(asFields(input.workspaceStrategy), "type"), [
120
+ "root",
121
+ "worktree",
122
+ "existing_worktree",
123
+ ]) ?? "root"),
124
+ });
125
+ case "t3_thread_send":
126
+ return defined({ delivery: stringField(output, "delivery") });
127
+ case "t3_thread_send_attachments":
128
+ return { delivery: "auto" };
129
+ case "schedule_task":
130
+ return { bindToCurrentThread: input.bindToCurrentThread !== false };
131
+ default:
132
+ return {};
133
+ }
134
+}
135
+
136
+/** Outcome of a tool call, with the stable failure code when the call failed. */
137
+export function toolOutcome(
138
+ result:
139
+ | { readonly isError?: boolean | undefined; readonly structuredContent?: unknown }
140
+ | undefined,
141
+) {
142
+ if (result === undefined) return { outcome: "error", errorCode: "exception" };
143
+ const content = asFields(result.structuredContent);
144
+ // T3 tool failures are declared errors whose structured content carries a
145
+ // closed `code`; the MCP layer does not always set isError for them.
146
+ const code = stringField(content, "code") ?? stringField(asFields(content.error), "_tag");
147
+ if (result.isError === true || (content._tag !== undefined && code !== undefined)) {
148
+ return { outcome: "error", errorCode: code ?? "unknown" };
149
+ }
150
+ return { outcome: "ok" };
151
+}
152
+
153
+/**
154
+ * Event properties for an agent tool call: the calling agent, and when the call
155
+ * handed work to other threads, the agents running them. Each target counts
156
+ * once, so a create_threads batch on two providers reports both.
157
+ */
158
+export function agentToolProperties(input: {
159
+ readonly tool: string;
160
+ readonly providers: ReadonlyArray<ServerProvider>;
161
+ readonly caller: AgentThread | undefined;
162
+ readonly callerProviderInstanceId?: ModelSelection["instanceId"];
163
+ readonly callerDepth?: number;
164
+ readonly callerScheduledRun?: boolean;
165
+ readonly targets: ReadonlyArray<AgentThread>;
166
+ readonly outcome: Fields;
167
+ readonly settings?: Fields;
168
+ readonly durationMs?: number;
169
+}): ReadonlyArray<Readonly<Record<string, unknown>>> {
170
+ const caller =
171
+ input.caller !== undefined
172
+ ? providerDimensions(input.providers, input.caller.modelSelection)
173
+ : input.callerProviderInstanceId !== undefined
174
+ ? {
175
+ provider: providerDimensions(input.providers, {
176
+ instanceId: input.callerProviderInstanceId,
177
+ model: "",
178
+ }).provider,
179
+ }
180
+ : { provider: "unknown" };
181
+ const base = defined({
182
+ tool: input.tool,
183
+ callerProvider: caller.provider,
184
+ callerModel: caller.model,
185
+ callerOrigin:
186
+ input.caller === undefined
187
+ ? undefined
188
+ : callerOrigin({
189
+ thread: input.caller,
190
+ scheduledRun: input.callerScheduledRun === true,
191
+ }),
192
+ callerDepth:
193
+ input.callerDepth === undefined ? undefined : Math.min(input.callerDepth, MAX_REPORTED_DEPTH),
194
+ durationMs: input.durationMs,
195
+ ...input.outcome,
196
+ ...input.settings,
197
+ });
198
+ if (input.targets.length === 0) return [base];
199
+ return input.targets.map((thread) => {
200
+ const target = providerDimensions(input.providers, thread.modelSelection);
201
+ return defined({
202
+ ...base,
203
+ targetProvider: target.provider,
204
+ targetModel: target.model,
205
+ targetRuntimeMode: thread.runtimeMode,
206
+ targetInteractionMode: thread.interactionMode,
207
+ crossProvider: crossProvider(caller.provider, target.provider),
208
+ });
209
+ });
210
+}
docs/internals/product-analytics.md
+10
@@ -47,6 +47,16 @@ RPC authorization middleware after the request succeeds.
47
the methods and commands, and takes variants only from closed contract enums,
48
so paths, ids, and text never reach analytics.
49
50
+Agent tool events report driver kinds, never instance ids: users name
51
+instances, so an instance id can identify an account or employer.
52
+[Provider dimensions](../../apps/server/src/telemetry/ProviderDimensions.ts)
53
+report a model only when it is a non-custom entry in a vendor catalog. OpenCode,
54
+Pi, and ACP agents list models from user configuration, such as local Ollama
55
+tags, so their models stay out. Handoff settings come from closed enums and
56
+booleans in tool arguments; prompts, titles, and ids are never read. Thread ids
57
+are used only to look up the threads on each side and never leave the server,
58
+which is also why tool events carry no per-thread sequence.
59
+
60
## Delivery
61
62
The server sends batches to the ingest endpoint at `ingest.t3.codes`, which archives