Skip to content
Merged
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
5 changes: 5 additions & 0 deletions apps/server/src/mcp/McpHttpServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,8 @@ import {
import * as HtmlHandlers from "./toolkits/html/handlers.ts";
import { MessageToolkit } from "./toolkits/message/tools.ts";
import * as MessageHandlers from "./toolkits/message/handlers.ts";
import * as ShowFileHandlers from "./toolkits/showFile/handlers.ts";
import { ShowFileToolkit } from "./toolkits/showFile/tools.ts";
import { HtmlPreviewTool, HtmlPreviewToolkit, HtmlRenderToolkit } from "./toolkits/html/tools.ts";
import { MCP_HTTP_PATH } from "../httpCors.ts";
import { requestUrl } from "../requestUrl.ts";
Expand Down Expand Up @@ -1280,6 +1282,8 @@ export const layerThreadToolkit = toolkitRegistration(ThreadToolkit, ThreadHandl

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

const layerShowFileToolkit = toolkitRegistration(ShowFileToolkit, ShowFileHandlers.layer);

const layerWorktreeToolkitRegistration = toolkitRegistration(
WorktreeToolkit,
WorktreeHandlers.layer,
Expand Down Expand Up @@ -1371,6 +1375,7 @@ export const layerTools = Layer.mergeAll(
layerDeviceToolkit,
layerHtmlToolkit,
layerMessageToolkit,
layerShowFileToolkit,
);

const layerToolExposure = Layer.effect(
Expand Down
97 changes: 97 additions & 0 deletions apps/server/src/mcp/toolkits/showFile/handlers.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import { expect, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Stream from "effect/Stream";

import * as ServerConfig from "../../../config.ts";
import * as ProjectService from "../../../project/ProjectService.ts";
import * as McpInvocationContext from "../../McpInvocationContext.ts";
import * as McpToolAccess from "../../McpToolAccess.ts";
import { liveThreadShell } from "../../McpToolAccess.testkit.ts";
import * as ThreadManagement from "../../../orchestration-v2/ThreadManagementService.ts";
import * as ShowFileHandlers from "./handlers.ts";
import { ShowFileToolkit } from "./tools.ts";

const SENTINEL = "SECRET_FILE_BYTES_9f3a";
const environmentId = EnvironmentId.make("environment:show-file");
const threadId = ThreadId.make("thread:show-file");

it.effect("returns path, size, and type and does not put file bytes in the result", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-show-file-" });
const filePath = path.join(directory, "answers.md");
yield* fileSystem.writeFileString(filePath, SENTINEL);
const layer = McpToolAccess.HandlersLayer.layer(ShowFileHandlers.layer).pipe(
Layer.provideMerge(
Layer.mergeAll(
Layer.succeed(McpInvocationContext.McpInvocationContext, {
environmentId,
requestNamespace: "provider:show-file",
thread: {
threadId,
providerSessionId: "provider:show-file",
providerInstanceId: ProviderInstanceId.make("codex"),
},
client: undefined,
capabilities: new Set(["orchestration" as const]),
issuedAt: 0,
}),
Layer.mock(ThreadManagement.ThreadManagementService)({
getThreadShell: () =>
Effect.succeed({ ...liveThreadShell(threadId), worktreePath: directory }),
}),
Layer.mock(ProjectService.ProjectService)({}),
ServerConfig.layerTest(directory, { prefix: "t3-show-file-config-" }),
),
),
Layer.provideMerge(NodeServices.layer),
);
const call = (params: { readonly path: string; readonly line?: number }) =>
Effect.gen(function* () {
const toolkit = yield* ShowFileToolkit;
const parts = yield* toolkit
.handle("show_file", params)
.pipe(Stream.unwrap, Stream.runCollect);
return parts.at(-1)?.result;
}).pipe(Effect.provide(layer));

const shown = yield* call({ path: filePath, line: 4 });
expect(shown).toEqual({
showFile: {
path: filePath,
byteSize: SENTINEL.length,
mediaType: "text/markdown",
line: 4,
},
message: "Shown in the file viewer. Do not read or quote the file.",
});
expect(JSON.stringify(shown)).not.toContain(SENTINEL);
expect(Object.keys(shown as object).sort()).toEqual(["message", "showFile"]);
expect(Object.keys((shown as { showFile: object }).showFile).sort()).toEqual([
"byteSize",
"line",
"mediaType",
"path",
]);

const relative = yield* call({ path: "answers.md" });
expect(relative).toMatchObject({
showFile: {
path: filePath,
byteSize: SENTINEL.length,
mediaType: "text/markdown",
},
});
expect(JSON.stringify(relative)).not.toContain(SENTINEL);

const missing = yield* call({ path: path.join(directory, "missing.md") });
expect(missing).toMatchObject({ code: "invalid_request", message: "File not found." });
expect(JSON.stringify(missing)).not.toContain(SENTINEL);
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
66 changes: 66 additions & 0 deletions apps/server/src/mcp/toolkits/showFile/handlers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { OrchestratorMcpFailure } from "@t3tools/contracts";
import { isNetworkPath } from "@t3tools/shared/path";
import { mediaTypeForPath } from "@t3tools/shared/showFile";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";

import { makeIsServerInternalPath } from "../../../auth/serverInternalPaths.ts";
import { expandHomePath } from "../../../os-jank.ts";
import { threadWorkspaceRoot } from "../../../project/threadWorkspaceRoot.ts";
import * as McpInvocationContext from "../../McpInvocationContext.ts";
import * as McpToolAccess from "../../McpToolAccess.ts";
import { ShowFileToolkit } from "./tools.ts";

const invalid = (message: string) =>
new OrchestratorMcpFailure({ code: "invalid_request", message });

const showFile = Effect.fn("ShowFile.stat")(function* (input: {
readonly path: string;
readonly line?: number | undefined;
}) {
const path = yield* Path.Path;
const fileSystem = yield* FileSystem.FileSystem;
const scope = yield* McpInvocationContext.McpInvocationContext;
const expanded = yield* expandHomePath(input.path);
const workspaceRoot =
scope.thread === undefined ? undefined : yield* threadWorkspaceRoot(scope.thread.threadId);
if (!path.isAbsolute(expanded) && workspaceRoot === undefined) {
return yield* invalid("Pass an absolute path or a path in this thread's workspace.");
}
const resolved = path.isAbsolute(expanded)
? path.resolve(expanded)
: path.resolve(workspaceRoot ?? expanded, expanded);
if (isNetworkPath(resolved)) {
return yield* invalid("That path cannot be shown.");
}
const stat = yield* fileSystem
.stat(resolved)
.pipe(Effect.mapError(() => invalid("File not found.")));
if (stat.type !== "File") {
return yield* invalid("Not a file.");
}
const isServerInternalPath = yield* makeIsServerInternalPath;
if (yield* isServerInternalPath(resolved)) {
return yield* invalid("That file cannot be shown.");
}
const byteSize = Number(stat.size);
if (!Number.isSafeInteger(byteSize) || byteSize < 0) {
return yield* invalid("That file cannot be shown.");
}
return {
showFile: {
path: resolved,
byteSize,
mediaType: mediaTypeForPath(resolved),
...(input.line === undefined ? {} : { line: input.line }),
},
message: "Shown in the file viewer. Do not read or quote the file.",
};
});

const handlers = {
show_file: McpToolAccess.actsAsCaller((input) => showFile(input)),
} satisfies McpToolAccess.Handlers<typeof ShowFileToolkit.tools>;

export const layer = McpToolAccess.toLayer(ShowFileToolkit, handlers);
60 changes: 60 additions & 0 deletions apps/server/src/mcp/toolkits/showFile/tools.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { OrchestratorMcpFailure } from "@t3tools/contracts";
import { SHOW_FILE_MAX_PATH_LENGTH, SHOW_FILE_TOOL_NAME } from "@t3tools/shared/showFile";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import { McpSchema, Tool, Toolkit } from "effect/ai";

import * as ServerConfig from "../../../config.ts";
import * as ProjectService from "../../../project/ProjectService.ts";
import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts";
import * as McpInvocationContext from "../../McpInvocationContext.ts";

const ShowFileTool = Tool.make(SHOW_FILE_TOOL_NAME, {
description:
"Show a file to the user in the file viewer. Pass its path. Returns only the path, byte size, and media type. Does not read the file, so its contents stay out of your context. Do not read or quote the file to show it.",
parameters: Schema.Struct({
path: Schema.String.check(
Schema.isMinLength(1),
Schema.isMaxLength(SHOW_FILE_MAX_PATH_LENGTH),
).annotate({
description: "Absolute path, ~/ path, or a path in this thread's workspace.",
}),
line: Schema.optional(
Schema.Int.check(
Schema.isGreaterThanOrEqualTo(1),
Schema.isLessThanOrEqualTo(1_000_000),
).annotate({
description: "1-based line to reveal. Omit to open the start of the file.",
}),
),
}),
success: Schema.Struct({
showFile: Schema.Struct({
path: Schema.String,
byteSize: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
mediaType: Schema.String,
line: Schema.optional(Schema.Int),
}),
message: Schema.String,
}),
failure: OrchestratorMcpFailure,
failureMode: "return",
dependencies: [
McpInvocationContext.McpInvocationContext,
ThreadManagementService.ThreadManagementService,
ProjectService.ProjectService,
FileSystem.FileSystem,
Path.Path,
ServerConfig.ServerConfig,
],
})
.annotate(Tool.Title, "Show a file")
.annotate(Tool.Readonly, true)
.annotate(Tool.Destructive, false)
.annotate(Tool.Idempotent, true)
.annotate(Tool.OpenWorld, false)
.annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromOutsideClients)
.annotate(Tool.Meta, { "anthropic/alwaysLoad": true });

export const ShowFileToolkit = Toolkit.make(ShowFileTool);
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderS
import { PreviewControlsToolkit } from "../../mcp/toolkits/previewControls/tools.ts";
import { HtmlToolkit } from "../../mcp/toolkits/html/tools.ts";
import { MessageToolkit } from "../../mcp/toolkits/message/tools.ts";
import { ShowFileToolkit } from "../../mcp/toolkits/showFile/tools.ts";
import { EnvironmentToolkit } from "../../mcp/toolkits/environment/tools.ts";
import { ThemeToolkit } from "../../mcp/toolkits/theme/tools.ts";
import { ProjectToolkit } from "../../mcp/toolkits/project/tools.ts";
Expand Down Expand Up @@ -794,6 +795,7 @@ describe("ClaudeAdapterV2 MCP query overrides", () => {
...Object.values(PreviewControlsToolkit.tools),
...Object.values(HtmlToolkit.tools),
...Object.values(MessageToolkit.tools),
...Object.values(ShowFileToolkit.tools),
]
.filter((tool) => Context.get(tool.annotations, Tool.Readonly))
.map((tool) => `mcp__t3-code__${tool.name}`)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2543,6 +2543,7 @@ export const CLAUDE_READ_ONLY_T3_MCP_ALLOWED_TOOLS: ReadonlyArray<string> = [
"mcp__t3-code__html_preview",
"mcp__t3-code__html_render",
"mcp__t3-code__send_to_user",
"mcp__t3-code__show_file",
];

// request_secret can wait an hour; exceed Claude's default 60 s timeout.
Expand Down
1 change: 1 addition & 0 deletions apps/server/src/orchestration-v2/ProjectionStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4702,6 +4702,7 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
{ toolName: "view_image", viewedImagePath: "/repo/screenshot.png" },
{ toolName: "mcp__docs__chart", output: { [MCP_APP_OUTPUT_KEY]: { uri: "ui://chart" } } },
{ toolName: "mcp__t3-code__send_to_user" },
{ toolName: "mcp__t3-code__show_file" },
// OpenCode Code Mode reports a nested send_to_user call as one `execute` item.
{ toolName: "execute", output: JSON.stringify({ sentMessage: "Draft" }) },
]) {
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/orchestration-v2/ProjectionStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2251,7 +2251,7 @@ const INLINE_WORK_OUTPUT = new RegExp(
"i",
);
const TOOL_NAME_PREFIX = /"toolName":"/i;
const INLINE_TOOL_NAME = /(?:delegate.task|send.to.user)"/is;
const INLINE_TOOL_NAME = /(?:delegate.task|send.to.user|show.file)"/is;

const isInlineWorkOutput = (payloadJson: string) => {
if (INLINE_WORK_OUTPUT.test(payloadJson)) return true;
Expand Down
3 changes: 2 additions & 1 deletion apps/server/src/provider/AgentContextBudget.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ const layerAdvertisedTools = McpHttpServer.layerTools.pipe(
);

// Claude Code loads these tools up front instead of behind ToolSearch, outside this budget.
it.effect("only request_secret and send_to_user ask Claude Code to load them up front", () =>
it.effect("request_secret, send_to_user, and show_file ask Claude Code to load them up front", () =>
Effect.gen(function* () {
const mcp = yield* McpServer.McpServer;
const alwaysLoad = mcp.tools
Expand All @@ -129,6 +129,7 @@ it.effect("only request_secret and send_to_user ask Claude Code to load them up
expect(alwaysLoad).toEqual([
["request_secret", { "anthropic/alwaysLoad": true }],
["send_to_user", { "anthropic/alwaysLoad": true }],
["show_file", { "anthropic/alwaysLoad": true }],
]);
}).pipe(Effect.provide(layerAdvertisedTools)),
);
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/provider/agentContextBudget.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"claudeSystemAppendBytes": 5930,
"codexAdditionalContextBytes": 7324,
"mcpToolListJsonBytes": 55240
"mcpToolListJsonBytes": 55827
}
42 changes: 42 additions & 0 deletions apps/web/src/components/chat/MessagesTimeline.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,13 @@ import {
ThreadId,
} from "@t3tools/contracts";
import { parseScopedThreadKey } from "@t3tools/client-runtime/environment";
import { useRightPanelStore } from "../../rightPanelStore";
import {
latestShownFileCreatedAt,
shownFileKey,
shownFileTargets,
shownFilesToOpen,
} from "./shownFileOpen";
import { resolveWorkGroupScrollAnchor } from "@t3tools/client-runtime/work-log/scroll-anchor";
import type { WorkflowOpening } from "@t3tools/client-runtime/state/subagentRuntime";
import { observeResize } from "~/lib/observeResize";
Expand All @@ -40,6 +47,7 @@ import {
useLayoutEffect,
useEffect,
useEffectEvent,
useMemo,
useRef,
useState,
type ReactNode,
Expand Down Expand Up @@ -483,6 +491,40 @@ const ConversationTimeline = memo(function ConversationTimeline({
setExpandedAttemptIds(paintedExpandedAttemptIds);
}
const citationThreadRef = parseScopedThreadKey(routeThreadKey);
const shownFilePlan = useMemo(() => {
const files = shownFileTargets(timelineEntries);
return {
files,
signature: shownFileKey(files),
latestCreatedAt: latestShownFileCreatedAt(files),
entryCount: timelineEntries.length,
};
}, [timelineEntries]);
const shownFilesRef = useRef(shownFilePlan.files);
shownFilesRef.current = shownFilePlan.files;
const shownFileBaseline = useRef<string | null>(null);
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a show_file completion opens the existing file viewer with a panel state update; the viewer reads the file after paint, and files already on screen stay put
useEffect(() => {
const plan = shownFilesToOpen({
threadKey: routeThreadKey,
previous: shownFileBaseline.current,
nextKey: shownFilePlan.signature,
files: shownFilesRef.current,
entryCount: shownFilePlan.entryCount,
latestCreatedAt: shownFilePlan.latestCreatedAt,
});
shownFileBaseline.current = plan.baseline;
const threadRef = parseScopedThreadKey(routeThreadKey);
if (threadRef === null) return;
for (const file of plan.open) {
useRightPanelStore.getState().openFile(threadRef, file.path, file.line);
}
}, [
routeThreadKey,
shownFilePlan.entryCount,
shownFilePlan.latestCreatedAt,
shownFilePlan.signature,
]);
const openPullRequest = useOpenPrLink(citationThreadRef ?? undefined);
const [minimapStripMap] = useState(() => new Map<string, HTMLSpanElement>());
const normalizedFindQuery = findQuery.trim();
Expand Down
Loading
Loading