Skip to content

feat: add opt-in file output mode for snapshot and get_elements (#178) - #184

Open
hoanle0126 wants to merge 5 commits into
webdriverio:mainfrom
hoanle0126:feat/snapshot-file-output-178
Open

hoanle0126 wants to merge 5 commits into
webdriverio:mainfrom
hoanle0126:feat/snapshot-file-output-178

Conversation

@hoanle0126

@hoanle0126 hoanle0126 commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

Closes #178

Summary

Adds an opt-in outputMode ("inline" | "file") parameter and outputDir option (plus WDIO_MCP_OUTPUT_MODE and WDIO_MCP_OUTPUT_DIR environment defaults) to snapshot and get_elements so agents can write large accessibility trees and element lists to disk instead of returning the full payload inline in context.

Changes

  • Adds file output helpers in src/utils/file-output.ts to write session-scoped output files with owner-only 0600 file and 0700 directory permissions, creating a private subdirectory when a configured output directory is shared.
  • Cleans up session output files (and empty private temp directories) when sessions close, are replaced, or on server exit, and prunes orphaned output directories and files from dead server processes on startup.
  • Updates snapshot and get_elements to support file output mode, skip inline truncation when writing to disk, and note in the summary when a shared output directory required a private subdirectory.
  • Documents the new parameters, environment variables, permissions, and cleanup lifecycle in README.md, with unit tests in tests/tools/snapshot-file-output.test.ts.

@greptile-apps

greptile-apps Bot commented Nov 1, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 3/5

[Medium impact] The PR changes how two page-inspection tools return results and manage local output files.

The PR should not merge until the two outstanding cleanup findings are fixed.

Findings

  1. P1 Cleanup deletes unrelated files ▶
  2. P1 Live output files disappear ▶

Summary

Adds optional file output for snapshot and get_elements, with private files and session-based cleanup.

  • Snapshots and element lists can go to files instead of the response.
  • Session output files disappear when their session or server ends.

Reviews (7) · Last reviewed commit: "feat: prune stale output files on startu..." · Reviewed by Greptile

Comment thread src/utils/file-output.ts Outdated
Comment on lines +50 to +59
const dir = outputDir?.trim() || process.env.WDIO_MCP_OUTPUT_DIR?.trim() || join(tmpdir(), DEFAULT_OUTPUT_SUBDIR);
mkdirSync(dir, { recursive: true });

fileCounter = (fileCounter + 1) % 1_000_000;
const prefix = sessionFilePrefix(sessionId);
const safeKind = sanitizeSegment(kind);
const fileName = `${prefix}-${safeKind}-${Date.now()}-${fileCounter}.${ext}`;
const filePath = join(dir, fileName);

writeFileSync(filePath, content, 'utf8');

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 security Other users can read snapshots

If the server runs on a shared Linux host with the usual 022 umask, file mode saves page contents in /tmp/wdio-mcp-outputs with readable-by-everyone files. Neither mkdirSync nor writeFileSync sets private permissions, so another local user can list and read snapshots from logged-in pages. Use a private directory owned by the current user and create files with owner-only access.

How this was verified: Both tools pass page contents to writeSessionOutputFile, which writes them under the shared temporary directory without restricting access.

Comment thread src/session/lifecycle.ts
});
state.browsers.delete(oldSessionId);
state.sessionMetadata.delete(oldSessionId);
cleanupSessionOutputFiles(oldSessionId);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Late files escape cleanup

A snapshot already running when start_session replaces its session can write a file after this cleanup finishes. Replacement runs outside the old session’s queue, and the running call keeps its old sessionId. When its browser request returns, writeSessionOutputFile recreates the deleted tracking entry. Nothing cleans that entry again, so the file remains after replacement. Reject writes for removed sessions, or arrange cleanup after running writers finish.

Comment thread src/utils/file-output.ts Outdated
if (typeof process.getuid === 'function' && stat.uid !== process.getuid()) {
throw new Error(`Invalid output directory "${configuredDir}": not owned by current user.`);
}
chmodSync(configuredDir, 0o700);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Shared directories lose access

If a user points outputDir or WDIO_MCP_OUTPUT_DIR at an existing shared project directory, chmodSync(configuredDir, 0o700) removes everyone else’s access to that directory and its unrelated files. Closing the session does not restore those permissions.

Create a private subdirectory for outputs, or reject directories with unsuitable permissions without changing them.

Comment thread src/utils/file-output.ts Outdated
Comment on lines +62 to +68
let subdir = privateSubdirs.get(configuredDir);
if (!subdir || !existsSync(subdir)) {
subdir = mkdtempSync(join(configuredDir, DEFAULT_OUTPUT_PREFIX));
chmodSync(subdir, 0o700);
privateSubdirs.set(configuredDir, subdir);
}
return subdir;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 security Shared paths can expose snapshots

If another local user can change entries in a shared outputDir without the sticky bit, they can rename the private subdirectory and replace its path with a symlink. existsSync accepts that replacement, so later writes use the attacker’s directory.

The attacker can precreate writable files for upcoming timestamp-and-counter names. writeFileSync overwrites those attacker-owned files before chmodSync runs, exposing page contents even if the permission change fails. Reject unsafe shared parents or use directory and file creation that cannot follow substituted paths.

How this was verified: Both tools pass page contents to this writer, which reuses cached directory paths after only existsSync and writes predictable filenames without exclusive creation.

@anthonypdawson anthonypdawson left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for picking this up, this is pretty much exactly what I described in #178. The opt-in outputMode: "file", the WDIO_MCP_OUTPUT_MODE / WDIO_MCP_OUTPUT_DIR env defaults, and skipping the truncation in file mode are all the right calls. The compact summary with path, refs, lines, and bytes is what I wanted for keeping large snapshots and element lists out of context.
A few things worth noting before merge:

  1. There is no way to list or prune the files after they are written. You get the path once in the result, and cleanup only runs on close or replace. If the server crashes or you reconnect, those files are orphans in a temp dir with no way to discover them. A list tool, or at least a prune / cleanup on startup, would close that gap.
  2. If you point outputDir at an existing shared directory, the code creates a private subdir inside it and writes there instead. That is the safe choice, but it is surprising. The returned path is correct, so the agent will find it, but a person looking in the directory they asked for will not. Worth calling out in the docs, or in the result message.
  3. Docs need an update. The PR touches the server, lifecycle, both tools, file-output.ts, and tests, but I did not see a docs update for the new outputMode / outputDir params or the env vars. The tool descriptions cover the basics, but the docs page for snapshot and get_elements should list the file mode, the env vars, the default temp location, the 0600 / 0700 permissions, and the cleanup behavior on close / replace.
    Happy to test this once it lands. Thanks again for building it.

@hoanle0126

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review @anthonypdawson! Addressed all three points in f547c4b:

  1. Startup prune & exit cleanup: Added pruneStaleOutputFiles() (called on server startup in src/server.ts and when first initializing a configured outputDir) to prune orphaned wdio-mcp-outputs-* directories and output files left behind by dead/crashed server processes while skipping directories/files owned by any live process. Also added cleanupAllOutputFiles() on process exit and automatic removal of empty wdio-mcp-outputs-* directories when sessions close or are replaced.
  2. Shared outputDir private subdirectory notice: writeSessionOutputFile() now tracks when an existing shared outputDir (mode & 0o077 !== 0) caused a private 0700 wdio-mcp-outputs-* subdirectory to be used, and both snapshot and get_elements include ; written to private 0700 subdirectory because outputDir is shared in the returned summary (as well as noting it in the tool schema descriptions and docs).
  3. Documentation (README.md & CLAUDE.md): Added documentation covering outputMode ("inline" | "file"), outputDir, WDIO_MCP_OUTPUT_MODE, WDIO_MCP_OUTPUT_DIR, the default temp directory (<os.tmpdir()>/wdio-mcp-outputs-<pid>-<random>), 0600/0700 permissions and shared-directory behavior, and cleanup on session close / replace / startup.

Comment thread src/utils/file-output.ts
Comment on lines +150 to +160
for (const childName of readdirSync(entryPath)) {
const childPath = join(entryPath, childName);
if (isTrackedOutputFile(childPath)) continue;
try {
const childStat = lstatSync(childPath);
if (
childStat.isFile() &&
!childStat.isSymbolicLink() &&
(typeof process.getuid !== 'function' || childStat.uid === process.getuid())
) {
unlinkSync(childPath);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Cleanup deletes unrelated files

pruneDirectory deletes every same-user regular file inside a private directory whose name merely starts with wdio-mcp-outputs-. If an outputDir contains a private wdio-mcp-outputs-backup directory, its unrelated files are deleted. Names without a PID bypass the live-process check, and startup runs this cleanup even in inline mode.

Require proof that the directory and files belong to this feature before deleting them.

Comment thread src/utils/file-output.ts
Comment on lines +170 to +175
} else if (baseIsPrivate && !isTrackedOutputFile(entryPath)) {
const fileMatch = entryName.match(OUTPUT_FILE_PATTERN);
if (!fileMatch) continue;
const ownerPid = fileMatch[1] ? Number(fileMatch[1]) : undefined;
if (ownerPid !== undefined && ownerPid !== process.pid && isProcessAlive(ownerPid)) {
continue;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Live output files disappear

If two calls use a relative outputDir and its absolute equivalent, the second call scans the same directory again. Tracking compares path strings, so the scan does not recognize the first call's files. The PID guard explicitly excludes process.pid, allowing cleanup to delete those live snapshot or element files.

Use one absolute, canonical path for tracking and cleanup, or skip all files owned by a running process, including this one.

@Winify

Winify commented Nov 14, 2026

Copy link
Copy Markdown
Collaborator

Hey @anthonypdawson @hoanle0126, thanks for the work and the patience here, and sorry for the late direction change.

I would not merge this in its current shape, for two reasons:

  1. get_elements is on its way out. Actions like click_element already return what changed on the page through the @wdio/session agent, so get_elements is rarely needed, and I want to move toward the session + snapshot combo instead of adding surface to it.
  2. @wdio/session already has most of this. On the CLI path a snapshot is written to the session's artifacts directory, with a fileOnly option that returns just a summary and the path. The agent path the MCP server uses skips that write today, so an oversized snapshot only gets a "too big" message. That gap is the real fix for Opt-in file output for large snapshots / page source, so agents can grep instead of loading the full XML #178.

What I'd like instead:

  • In @wdio/session: make the agent snapshot write the file when the output is too big or fileOnly is set, and return the path.
  • In this repo: snapshot passes one flag through and the session directory is cleaned up on close. No outputDir tool parameter, no separate file store.

That replaces most of file-output.ts, and the CLI and MCP then behave the same. @hoanle0126, would you be up for taking the @wdio/session side in the webdriverio repo? If not, I can do it and you could pick up the small MCP half afterwards. @anthonypdawson, what you asked for in #178 stays: path plus compact summary instead of the full tree in context.

@anthonypdawson

Copy link
Copy Markdown
Contributor

Thanks for the direction, this makes sense to me. The session-side fix is the better home for it. One file store, CLI and MCP behaving the same, and a lot less surface in this repo.

What I asked for in #178 is just the behavior: path plus compact summary instead of the full tree in context. As long as that survives the move, I'm good with reworking this however you and @hoanle0126 want to split it. My approval was on the old shape, so consider it superseded.

@hoanle0126

Copy link
Copy Markdown
Contributor Author

Thanks @Winify, that split makes a lot of sense and keeps CLI and MCP behavior consistent.

I opened webdriverio/webdriverio#16461 for the @wdio/session half so agent.snapshot() writes the snapshot file to the session artifacts directory when the output exceeds maxChars or fileOnly is set, and returns file plus the path in text.

Once that lands and @wdio/session is published, I will update this PR to pass the flag through snapshot and clean up the session directory on close, dropping file-output.ts and the get_elements changes.

@Winify

Winify commented Nov 19, 2026

Copy link
Copy Markdown
Collaborator

@hoanle0126 #195 is merged to main, so here is the reduced scope for this PR once webdriverio/webdriverio#16461 is released:

  1. Rebase on main and drop src/utils/file-output.ts, the get_elements changes, the outputMode/outputDir params and the WDIO_MCP_OUTPUT_* env vars.
  2. pnpm add @wdio/session@<release with #16461>. snapshot already passes maxChars: SNAPSHOT_MAX_CHARS, so oversized snapshots then write the file and return the path without further changes.
  3. src/tools/snapshot.tool.ts: add an optional fileOnly boolean (coerceBoolean) and pass it to agent.snapshot().
  4. Cleanup: src/session/agent.ts caches agents in a WeakMap and nothing calls AgentSession.dispose(), so the temp wdio-agent-* dir is never removed. Dispose the agent when a session closes or is replaced (src/session/lifecycle.ts).
  5. Tests for 3 and 4, plus a README note for fileOnly.

@hoanle0126

Copy link
Copy Markdown
Contributor Author

Sounds good, thanks @Winify! I'll rebase onto main and trim this PR down to those five items once webdriverio/webdriverio#16461 lands in a @wdio/session release.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Opt-in file output for large snapshots / page source, so agents can grep instead of loading the full XML

3 participants