@devries-cameron20 / t3code Mirror · read-only / commits / b387e3a179
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 08:30 UTC

fix(server): Claude turns receive MCP app model context (#38307)

Julius Marminge committed Nov 17, 2026 at 12:37 UTC b387e3a179d7495321019363c5ba11e847834cd0
2 files changed +143 -5
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+72
@@ -6840,6 +6840,78 @@ describe("ClaudeAdapterV2 background wake turns", () => {
6840 ),
6841 );
6842
6843 + // regression: #38284 an MCP app's update-model-context note must reach Claude's next turn
6844 + it.effect("sends MCP app model context with the next Claude turn", () =>
6845 + Effect.gen(function* () {
6846 + const harness = yield* makeWakeHarnessWithOptions({
6847 + close: (sdkMessages) => Queue.shutdown(sdkMessages),
6848 + freshQueueOnReopen: true,
6849 + });
6850 + const runTurn = Effect.fnUntraced(function* (ordinal: number, note: string) {
6851 + yield* harness.runtime.startTurn({
6852 + ...makeClaudeTestTurnInput({
6853 + threadId: harness.threadId,
6854 + providerThread: harness.providerThread,
6855 + now: yield* DateTime.now,
6856 + attemptId: RunAttemptId.make(`mcp-app-context-${ordinal}`),
6857 + providerTurnOrdinal: ordinal,
6858 + text: "What did the app report?",
6859 + attachments: [],
6860 + }),
6861 + appContext: [{ key: "mcp_app_item-1", text: note }],
6862 + });
6863 + const content = harness.offeredMessages.at(-1)?.message.content;
6864 + return typeof content === "string"
6865 + ? content
6866 + : (content ?? []).map((block) => (block.type === "text" ? block.text : "")).join("\n");
6867 + });
6868 + const finishTurn = Effect.fnUntraced(function* (ordinal: number) {
6869 + yield* harness.offerAndWait(
6870 + makeResultFrame({ uuid: `mcp-app-context-result-${ordinal}`, result: "Done." }),
6871 + );
6872 + yield* Queue.take(harness.terminalReceipts);
6873 + });
6874 +
6875 + assert.include(yield* runTurn(0, "Created Jira issue PROJ-42"), "PROJ-42");
6876 + // A turn that does not complete may not have put the note in Claude's history.
6877 + yield* harness.runtime.interruptTurn({
6878 + providerThread: harness.providerThread,
6879 + providerTurnId: (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({
6880 + driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
6881 + nativeTurnId: "turn:mcp-app-context-0",
6882 + }),
6883 + });
6884 + assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "interrupted");
6885 + assert.include(yield* runTurn(1, "Created Jira issue PROJ-42"), "PROJ-42");
6886 + yield* finishTurn(1);
6887 + // Already in Claude's history: resending it every turn would only grow the context.
6888 + assert.notInclude(yield* runTurn(2, "Created Jira issue PROJ-42"), "PROJ-42");
6889 + yield* finishTurn(2);
6890 + assert.include(yield* runTurn(3, "Created Jira issue PROJ-43"), "PROJ-43");
6891 + yield* harness.offerAndWait(
6892 + claudeSdkFrame({
6893 + type: "system",
6894 + subtype: "compact_boundary",
6895 + compact_metadata: { trigger: "auto", pre_tokens: 1500, post_tokens: 400 },
6896 + uuid: "00000000-0000-4000-8000-000000038284",
6897 + session_id: WAKE_NATIVE_SESSION,
6898 + }),
6899 + );
6900 + yield* finishTurn(3);
6901 + // Compaction summarizes the note away, so the next turn carries it again.
6902 + assert.include(yield* runTurn(4, "Created Jira issue PROJ-43"), "PROJ-43");
6903 + }).pipe(
6904 + Effect.provide(
6905 + Layer.mergeAll(
6906 + IdAllocator.layer,
6907 + McpProviderSessions.layer,
6908 + NodeServices.layer,
6909 + NodeCrypto.layer,
6910 + ),
6911 + ),
6912 + ),
6913 + );
6914 +
6915 it.effect("sends the model id Claude Code reported for the selected catalog model", () =>
6916 Effect.scoped(
6917 Effect.gen(function* () {
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+71 -5
@@ -3022,6 +3022,37 @@ const reserveClaudePdfBudget = (
3022 }).pipe(Effect.andThen(persist)),
3023 );
3024
3025 +// MCP app notes are app-written, so they go as quoted user input like Codex's untrusted context.
3026 +// A slash command runs only when it opens a plain-text prompt; its note waits for the next turn.
3027 +// Returns `message` itself when it adds nothing.
3028 +const withClaudeAppContext = (
3029 + message: SDKUserMessage,
3030 + appContext: NonNullable<ProviderAdapter.ProviderAdapterV2TurnInput["appContext"]>,
3031 + reservation: Effect.Success<ReturnType<typeof reserveClaudePdfBudget>>,
3032 +): SDKUserMessage => {
3033 + const content = message.message.content;
3034 + if (appContext.length === 0 || (typeof content === "string" && content.startsWith("/"))) {
3035 + return message;
3036 + }
3037 + const contextBlocks = appContext.map((entry) => ({
3038 + type: "text" as const,
3039 + text: `<external_${entry.key}>${entry.text}</external_${entry.key}>`,
3040 + }));
3041 + const bytes = Buffer.byteLength(encodeClaudeJson(contextBlocks));
3042 + reservation.budget.pending.bytes += bytes;
3043 + reservation.bytes += bytes;
3044 + return {
3045 + ...message,
3046 + message: {
3047 + ...message.message,
3048 + content: [
3049 + ...contextBlocks,
3050 + ...(typeof content === "string" ? [{ type: "text" as const, text: content }] : content),
3051 + ],
3052 + },
3053 + };
3054 +};
3055 +
3056 const makeClaudeUserMessageWithAttachments = Effect.fnUntraced(function* (input: {
3057 readonly text: string;
3058 readonly attachments: ReadonlyArray<ChatAttachment>;
@@ -5045,6 +5076,8 @@ interface ActiveClaudeTurnContext {
5076 readonly subagentsByToolUseId: Map<string, ActiveClaudeSubagent>;
5077 readonly promptUuid: string | null;
5078 promptEcho: "pending" | "confirmed";
5079 + // MCP app notes this turn's prompt carries, recorded as delivered only if the turn completes.
5080 + appContextOffered?: ReadonlyMap<string, string> | undefined;
5081 promptStarted: boolean;
5082 nativeWakeStarted: boolean;
5083 gatedFramesBeforeEcho: number;
@@ -5889,6 +5922,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
5922 // Sessions Claude Code reported gone on resume; resumeThread fails them into a fresh session.
5923 const missingNativeThreads = new Set<string>();
5924 const pdfBudgets = new Map<string, ReturnType<typeof makeClaudeAttachmentBudget>>();
5925 + // MCP app notes already in each native session's history, by key. Cleared when it compacts.
5926 + const deliveredAppContext = new Map<string, ReadonlyMap<string, string>>();
5927 const latestPlanByKind = yield* Ref.make(new Map<string, OrchestrationV2PlanArtifact>());
5928 // Claude 5 task tools edit one list per native session, across turns.
5929 const taskListsByNativeThread = yield* Ref.make(
@@ -9216,6 +9251,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
9251 } else {
9252 yield* cutOffStreamedText(input.context);
9253 }
9254 + if (input.status === "completed" && input.context.appContextOffered !== undefined) {
9255 + deliveredAppContext.set(input.context.nativeThreadId, input.context.appContextOffered);
9256 + }
9257 // A turn that completes has taken in every steer; one that stops drops them unread.
9258 const droppedSteers = [...input.context.pendingSteers];
9259 input.context.pendingSteers.clear();
@@ -10924,6 +10962,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
10962
10963 // Every trigger discards the conversation, so reset whatever the trigger is.
10964 if (message.type === "conversation_reset") {
10965 + deliveredAppContext.delete(context.nativeThreadId);
10966 + context.appContextOffered = undefined;
10967 if (context.streamUsage !== null) context.streamUsage.usage = null;
10968 context.compactionTokens = 0;
10969 yield* emitContextUsage(context, 0);
@@ -10993,6 +11033,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
11033 budget.compacting = null;
11034 yield* persistAttachmentBudget(context.nativeThreadId);
11035 }
11036 + deliveredAppContext.delete(context.nativeThreadId);
11037 + context.appContextOffered = undefined;
11038 if (context.streamUsage !== null) context.streamUsage.usage = null;
11039 const postTokens = message.compact_metadata.post_tokens;
11040 const afterTokenCount =
@@ -13157,6 +13199,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
13199 turnInput.message.text,
13200 compileClaudeModelSelection(turnInput.modelSelection, modelCatalog).promptEffort,
13201 );
13202 + const appContext = turnInput.appContext ?? [];
13203 + const delivered = deliveredAppContext.get(nativeThreadId);
13204 + let appContextSent = false;
13205 const userMessage =
13206 promptUuid === null
13207 ? null
@@ -13185,6 +13230,15 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
13230 ...(skills === undefined ? {} : { skills }),
13231 uuid: promptUuid,
13232 }).pipe(
13233 + Effect.map((message) => {
13234 + const withContext = withClaudeAppContext(
13235 + message,
13236 + appContext.filter((entry) => delivered?.get(entry.key) !== entry.text),
13237 + pdfReservation,
13238 + );
13239 + appContextSent = withContext !== message;
13240 + return withContext;
13241 + }),
13242 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
13243 Effect.provideService(Path.Path, path),
13244 );
@@ -13332,17 +13386,27 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
13386 }),
13387 });
13388 });
13389 + // `offer` may call this twice; a second call must not restore notes compaction cleared.
13390 + let offerCommitted = false;
13391 + const commitOffer = () => {
13392 + if (offerCommitted) return;
13393 + offerCommitted = true;
13394 + pdfReservation.commit();
13395 + if (appContextSent) {
13396 + context.appContextOffered = new Map(
13397 + appContext.map((entry) => [entry.key, entry.text]),
13398 + );
13399 + }
13400 + };
13401 const offerUserMessage =
13402 userMessage === null
13403 ? Effect.void
13404 : startUserTurnForWakeReports(nativeThreadId).pipe(
13405 Effect.andThen(
13406 Effect.uninterruptibleMask((restore) =>
13341 - restore(
13342 - querySession.query.offer(userMessage, () => {
13343 - pdfReservation.commit();
13344 - }),
13345 - ).pipe(Effect.tap(() => Effect.sync(() => pdfReservation.commit()))),
13407 + restore(querySession.query.offer(userMessage, commitOffer)).pipe(
13408 + Effect.tap(() => Effect.sync(commitOffer)),
13409 + ),
13410 ),
13411 ),
13412 );
@@ -14390,6 +14454,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
14454
14455 const nativeThreadId = yield* getNativeThreadId(rollbackInput.providerThread);
14456 yield* closeLiveQueryForNativeThread(nativeThreadId);
14457 + // The rewound history may no longer hold the turns that carried app notes.
14458 + deliveredAppContext.delete(nativeThreadId);
14459 const now = yield* DateTime.now;
14460 const resumeSessionAt = yield* resolveClaudeRollbackResumeSessionAt(rollbackInput);
14461