Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 69 additions & 4 deletions apps/server/src/mcp/McpHttpServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@ import * as McpInvocationContext from "./McpInvocationContext.ts";
import * as McpToolAccess from "./McpToolAccess.ts";
import * as McpToolExposure from "./McpToolExposure.ts";
import * as McpWebhookTransport from "./McpWebhookTransport.ts";
import { HTML_RENDER_TOOL_NAME } from "@t3tools/shared/htmlRender";
import { compactT3McpToolOutput } from "@t3tools/shared/toolOutput";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import { MCP_TOOL_EXPOSURE_HEADER } from "@t3tools/provider-core/server/mcpSession";
import * as OrchestratorMcpService from "./OrchestratorMcpService.ts";
import { PreviewControlsToolkit } from "./toolkits/previewControls/tools.ts";
Expand Down Expand Up @@ -1218,6 +1221,66 @@ const withToolAnalytics =
return yield* registration.pipe(Effect.provideService(McpServer.McpServer, recordingServer));
});

/**
* ACP runtimes and Code Mode wrappers can drop or replace structured MCP tool results on
* completion. Recording each thread-scoped call's compact result before returning lets adapters
* recover sent messages, IDs, counts, and error flags without depending on output passthrough.
*/
const withToolResultCapture = Effect.fn("McpHttpServer.withToolResultCapture")(function* <A, E, R>(
registration: Effect.Effect<A, E, R>,
) {
const server = yield* McpServer.McpServer;
const mcpSessions = yield* Effect.serviceOption(McpProviderSessions.McpProviderSessions);
if (Option.isNone(mcpSessions)) {
return yield* registration;
}
const capturingServer = McpServer.McpServer.of({
...server,
addTool: Effect.fn("McpServer.addTool")(function (options) {
const toolName = options.tool.name;
// html_render tracks its own path/hash recovery with publish cleanup in HtmlRender.
if (toolName === HTML_RENDER_TOOL_NAME) {
return server.addTool(options);
}
return server.addTool({
...options,
handle: Effect.fnUntraced(function* (payload) {
const scopeOption = yield* Effect.serviceOption(
McpInvocationContext.McpInvocationContext,
);
const thread = Option.getOrUndefined(scopeOption)?.thread;
const epoch =
thread === undefined
? undefined
: yield* mcpSessions.value.toolResultEpoch(thread.threadId);
return yield* options.handle(payload).pipe(
Effect.onExit((exit) => {
if (thread === undefined) return Effect.void;
if (exit._tag === "Success" && exit.value instanceof McpSchema.InputRequired) {
return Effect.void;
}
if (exit._tag === "Failure" && Cause.hasInterruptsOnly(exit.cause)) {
return Effect.void;
}
const output =
exit._tag === "Success"
? compactT3McpToolOutput(toolName, exit.value)
: { isError: true };
return output === undefined
? Effect.void
: mcpSessions.value.recordToolResult(thread.threadId, toolName, payload, output, {
providerSessionId: thread.providerSessionId,
epoch,
});
}),
);
}),
});
}),
});
return yield* registration.pipe(Effect.provideService(McpServer.McpServer, capturingServer));
});

/** Each tool call gets a span named for its tool; arguments stay out, as they carry prompts and IDs. */
const withToolSpans = Effect.fn("McpHttpServer.withToolSpans")(function* <A, E, R>(
registration: Effect.Effect<A, E, R>,
Expand Down Expand Up @@ -1300,8 +1363,10 @@ export const toolkitRegistration = <Tools extends Record<string, Tool.Any>, EX,
) =>
Layer.effectDiscard(
withToolAnalytics(
withToolSpans(
withAdvertisedSchemas(toolkit, McpServer.registerToolkit(decodeAsAdvertised(toolkit))),
withToolResultCapture(
withToolSpans(
withAdvertisedSchemas(toolkit, McpServer.registerToolkit(decodeAsAdvertised(toolkit))),
),
),
),
).pipe(
Expand All @@ -1318,7 +1383,7 @@ const imageToolRegistration = <Tools extends Record<string, Tool.Any>, A, E, R,
register: Effect.Effect<A, E, R>,
handlers: McpToolAccess.HandlersLayer<Tools, EX, RX>,
) =>
Layer.effectDiscard(withToolAnalytics(withToolSpans(register))).pipe(
Layer.effectDiscard(withToolAnalytics(withToolResultCapture(withToolSpans(register)))).pipe(
Layer.provide(McpToolAccess.HandlersLayer.layer(handlers)),
);

Expand Down Expand Up @@ -1350,7 +1415,7 @@ export const layerOrchestratorToolkit = toolkitRegistration(
export const layerThreadToolkit = toolkitRegistration(ThreadToolkit, ThreadHandlers.layer);
const layerWorkflowToolkit = toolkitRegistration(WorkflowToolkit, WorkflowHandlers.layer);

const layerMessageToolkit = toolkitRegistration(MessageToolkit, MessageHandlers.layer);
export const layerMessageToolkit = toolkitRegistration(MessageToolkit, MessageHandlers.layer);

const layerWorktreeToolkitRegistration = toolkitRegistration(
WorktreeToolkit,
Expand Down
41 changes: 41 additions & 0 deletions apps/server/src/mcp/toolkits/core.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -416,6 +416,47 @@ it.effect("returns an HTML render reference that Codex and Claude tool rows both
),
);

it.effect("captures send_to_user results for providers that drop MCP outputs", () =>
Effect.gen(function* () {
const server = yield* McpServer.McpServer;
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
const draft = "### Status\n\nAll checks passed.";
const result = yield* server
.callTool({ name: "send_to_user", arguments: { message: draft } })
.pipe(
Effect.provideService(McpInvocationContext.McpInvocationContext, scope),
Effect.provideService(McpSchema.McpServerClient, client),
);
expect(result.isError).not.toBe(true);
expect(yield* mcpSessions.takeToolResult(threadId, "send_to_user", { message: draft })).toEqual(
{ sentMessage: draft },
);
expect(yield* mcpSessions.takeToolResult(threadId, "send_to_user", { message: draft })).toBe(
undefined,
);

const invalid = yield* server
.callTool({ name: "send_to_user", arguments: { message: "" } })
.pipe(
Effect.provideService(McpInvocationContext.McpInvocationContext, scope),
Effect.provideService(McpSchema.McpServerClient, client),
Effect.flip,
);
expect(invalid).toMatchObject({ _tag: "InvalidParams" });
expect(yield* mcpSessions.takeToolResult(threadId, "send_to_user", { message: "" })).toEqual({
isError: true,
});
}).pipe(
Effect.provide(
McpHttpServer.layerMessageToolkit.pipe(
Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
Layer.provideMerge(McpProviderSessions.layer),
Layer.provide(McpToolAccessTestkit.liveThreadsLayer),
),
),
),
);

it.effect("records only failed calls of tools that hand off no work", () => {
// Recording runs detached from the tool response, so the first event is awaited.
const recorded = Deferred.makeUnsafe<{ event: string; properties: object }>();
Expand Down
Loading
Loading