Skip to content

fix(mcp): escape control characters in the paths CodeGraph prints - #383

Merged
sunerpy merged 12 commits into
mainfrom
fix/escape-control-chars
Dec 2, 2026
Merged

sunerpy merged 12 commits into
mainfrom
fix/escape-control-chars

Conversation

@sunerpy

@sunerpy sunerpy commented Dec 2, 2026

Copy link
Copy Markdown
Owner

Summary

Text output writes the control characters of a stored path or file name as \u{XXXX}, so a file name can no longer add lines or Markdown structure to an MCP answer, or run an escape sequence in a terminal.

  • What is escaped. C0 controls, DEL, C1 controls, U+061C, U+200E, U+200F, U+2028, U+2029, U+202A–U+202E and U+2066–U+2069. src/a<LF>b.ts prints as src/a\u{000A}b.ts; a clean name is printed as it is and not copied.
  • Where. MCP Markdown (file view titles, Location lines, search, callers, callees and impact lists and headings, explore, the files tree, status pending lists, hints), the CLI's text output (search, node, callers, callees, impact, files, explore, context, status, affected, check, audit and the index messages), the prompt hook, and error messages and warnings that name a file. A qualified name that holds a stored path, such as a Vue component's src/x/Button.vue::Button, is escaped too.
  • Reading it back. A path argument accepts the printed form: node src/a\u{000A}b.ts names src/a<LF>b.ts. When the same argument read with its \ as a separator names another stored file, the answer lists both files (audit --impact, which has no list form, stops with an error that names both).
  • JSON output of search, callers, callees, impact, files, status, check, audit, affected, export and context --format json keeps the stored names; node --json and explore --json wrap the same escaped Markdown the MCP tools return.
  • docs/cli.md and docs/mcp.md describe this.

No graph, schema or extraction change: the 32 golden corpora re-extract identically.

Tests

  • crates/codegraph-cli/tests/c_early_index/control_char_names.rs (Unix; the files a<LF>b.ts, c<ESC>[2Jd.ts, e<DEL>f.ts and g<U+202E>h.ts are created at test time): every MCP tool, every CLI text command, the prompt hook, the audit and index messages, definition headings that hold a stored path, error text for an unreadable file and for a link to one outside the project, printed paths passed back as arguments (with a decoy file that the \-as-separator reading names), and the JSON outputs. Each case failed on the base for the reason it targets.
  • Unit tests for escape_name, unescape_name, path_readings and escape_path; the escaping sites were also run against deliberately broken variants, and each variant failed a case.

Verification

  • cargo fmt --all --check, cargo clippy --workspace --all-targets --locked -- -D warnings, and the same for x86_64-pc-windows-msvc through cargo xwin.
  • codegraph-core, codegraph-mcp (with golden_mcp), codegraph-graph, codegraph-extract, codegraph-watch, codegraph-rs --bins and 42 CLI integration targets pass; scripts/regen-goldens.sh --check with this branch's release binaries: 32/32 identical.
  • Performance, on this branch's own diff (base d42206f, the branch head before its rebase), with the repository's frozen A/B method on a quiet 32-core host (one-minute load below 3 at three checks in a row before it started, 5 valid alternating rounds, explore 25 samples per side): typescript-large explore p50 0.992× (0.7166 s against 0.7223 s, same output hash), single-file sync 0.995×, peak RSS 0.999×; express-medium explore p50 1.004×, sync 1.018×, RSS 0.943–0.962×. Both sides' graphs agree.

Known limits

  • Symbol names, including component and route names that come from a path, signatures and docstrings are content and appear as stored.
  • Windows file names cannot hold these characters, so the cases run on Unix only.
  • For an argument given in the escaped form, affected --json reports the decoded stored name in changedFiles.

A file name on Linux or macOS can hold a line feed, an escape sequence,
a DEL or a bidirectional override, and the index stores it exactly. The
new c_early_index test target (Unix only) creates four such files, each
defining one function, and runs the built binary with no daemon, no
watcher and its own home and registries:

- every MCP tool through a stdio session, including the pending-sync
  list and the stale-file notes once the files change on disk;
- every CLI text command with its standard error, and the Markdown in
  the output field of node --json and explore --json;
- both kinds of text the prompt hook prints.

Text output must write those code points as \u{XXXX} (four upper-case
hex digits) and never hold a raw name. A JSON answer must keep the
stored names: each parses back to the name in the index.

The text checks fail on the current code, which prints the names raw.
The JSON check passes and guards JSON output against escaping.
A stored file name on Linux or macOS can hold a line feed, an escape
sequence, a DEL, a C1 control or a bidirectional control. The MCP
tools wrote such names raw into their Markdown, so a name could add
lines to an answer or change how a terminal shows it.

codegraph_core::display::escape_name writes those code points as
\u{XXXX}, four upper-case hex digits, and returns any other name
borrowed and unchanged. The escaped set is U+0000-U+001F,
U+007F-U+009F, U+061C, U+200E, U+200F, U+2028-U+202E and
U+2066-U+2069. A stored name never holds a backslash, so an escaped
form cannot be read as another file's name. node_name and
node_qualified_name apply it to a file node, whose name is the last
segment of its path; a symbol's name is shown as stored.

The MCP engine and the context renderer use it wherever they write a
stored path or a file node's name: the search, callers, callees and
impact lists, the node view and its trail, the file view, explore
(flow, blast radius, relationships, dynamic boundaries, section
headers, gap markers, pointers and the completeness note), files,
check, the pending-sync list of status, the stale-file notes, and the
Markdown and notices of codegraph context. The wiring site of a
synthesized hop is escaped too. Explore measures and finds its section
headers in the escaped form, so its budget bounds still hold.

JSON output keeps the stored names: codegraph_export and
context --format json are unchanged. Ordinary names print byte for
byte as before, and the MCP goldens are unchanged.
The control-character tests now also cover the CLI text that names
files outside the query commands, each on a project of its own:

- audit on a Godot project whose resources and scenes have a line
  feed, an escape sequence, a DEL or a right-to-left override in their
  names: orphans, dangling references, the sites that reference a
  path and the verify plan, and the same report in --json;
- a TypeScript file that parses to nothing: the warning init, index
  and sync print on standard error, and the files missing their
  symbols in status;
- a project with no supported file: the skipped extensions init lists.

Text must write those code points as \u{XXXX} and never hold a raw
name; the audit JSON must keep the stored names. The text checks fail
on the current code, which prints the names raw.
The CLI's own text output wrote stored paths raw, so a file name with a
line feed, an escape sequence, a DEL, a C1 control or a bidirectional
control could add lines to the output or run an escape sequence in a
terminal. It now writes them through codegraph_core::display, as the
MCP tools do: those code points become \u{XXXX}, and a file node's name
is escaped while a symbol's name is shown as stored.

This covers search, callers, callees, impact, files in all three
formats, check, the pending-sync list and the files missing their
symbols in status, the audit reports and the verify plan, the parse
warnings init, index and sync print on standard error, the skipped
extensions of an index with no supported file, the progress message
for a stuck file, and the symbol pointers the prompt hook prints. node,
explore and context already render through the MCP engine. The new
escape_node_name escapes a name by its node kind alone, for summaries
that carry no Node.

--json output, affected, export, context --format json and the --debug
log keep the stored names. Ordinary names print byte for byte as
before. docs/cli.md and docs/mcp.md describe the escaping.
Text output writes the control characters of a stored path as \u{XXXX},
and a reader passes such a path back to a path argument: the file of
codegraph_node, a path in an explore query, node -f, the --file filter of
callers, callees and impact, files --filter and --pattern, affected and
audit. Each of them reads a \ as a path separator today, so the printed
form of src/a<LF>b.ts stands for src/a/u{000A}b.ts: the file cannot be
read by the name CodeGraph printed for it, and where src/a/u{000A}b.ts
exists, that file is answered instead.

The tests take a printed path from an answer and pass it back. It must
answer as the stored name does. Beside a file that the separator reading
names, the answer must name the file the path was printed for or list
both, and audit --impact must stop and name both paths. A printed path
that names no file stays in explore's note as the query wrote it.
Text output writes the control characters of a stored path as \u{XXXX},
and the path arguments of codegraph_node, the --file filters, explore,
files, affected and audit read each \ as a path separator, so the printed
form of src/a<LF>b.ts stood for src/a/u{000A}b.ts.

codegraph_core::display gains unescape_name, which decodes exactly the
escapes escape_name writes and keeps everything else, and path_readings,
which yields that decoded reading and, when the argument holds an escape,
the argument as written, where a \ may be a separator (the native
spelling on Windows). Each path argument is resolved under both readings
before its \ is folded. Where they name different stored files, the
answer lists both: the file view's candidate list, the multi-definition
answers, and an explore pin for each file. audit --impact has no such
answer, so it stops with an error that names both. affected matches
stored names exactly and never reads \ as a separator, so it decodes
only.

Explore escapes a span it did not pin and the span of the files it set
aside, and audit escapes the changed path it prints, since these now hold
the decoded path. The display module no longer claims that an escaped
form cannot be read as another stored name.
A Vue component's qualified name is its stored path, `::` and the
component's name, and many framework nodes (routes, CFML and Godot
nodes) start theirs the same way. callers, callees and impact head an
answer with that name: the CLI for one definition or several, MCP when
it lists several. Each heading writes the directory raw today, while the
path beside it on the same line is escaped, so a line feed in the
directory breaks the heading across two lines.

The new test indexes src/x<LF>y/Button.vue beside src/other/Button.vue,
and alone, and requires every such heading to show the escaped
qualified name and never the raw directory.

The display unit test that asserted a symbol's qualified name is shown
as stored now asserts that every qualified name is escaped as a path
is: the function cannot tell which part of a qualified name came from a
path, and a route's ends in a path made of its directories. The
node-name assertions are unchanged; their test is renamed to say it
covers the name alone.
A file node's qualified name is its stored path, and many other nodes
hold that path too: a Vue or Svelte component's qualified name is
{path}::{name}, a route's is {path}::route:{url}, where a file-system
router builds the URL from directory names, and CFML and other framework
nodes start theirs the same way. node_qualified_name escaped the
qualified name of a file node only, so the definition headings of
callers, callees and impact, in the CLI and in MCP, and explore's
dynamic-dispatch candidates wrote such a directory raw, while the path
beside it on the same line was escaped.

node_qualified_name now escapes the qualified name of every node, since
which part of it came from a path is not recorded. An ordinary name is
still borrowed and prints byte for byte as before, and a symbol's name
shown on its own stays as stored. docs/cli.md and docs/mcp.md say that a
qualified name is escaped whole.
init, status, sync and an index upgrade stop with an error that names a
file they cannot read, stat or list, and an MCP session answers and logs
the same error. The tests make such files: one that is chmod 000, a link
to a chmod 000 file outside the project, and a directory that cannot be
listed or searched, each named with an escape sequence or a line feed.
The error must write the path with those characters as \u{XXXX}, as text
output writes a stored name, and never raw. The extraction reads that
fail the same way are covered by a unit test. The checks are skipped for
root, which chmod 000 does not stop.
An error or a warning that named a file or directory of the project
wrote its path as it is. A name holding a line feed split the message,
which forged a line in the terminal, in an MCP tool result or in the
session's log, and a name holding an escape sequence ran it in the
terminal. This held for the read, stat and list-directory errors of
init, index, sync, status and the index upgrade, which the MCP
codegraph_status tool and the start-up catch-up sync pass on, and for
the watch failures the file watcher reports.

Each of these now writes the path through the new
codegraph_core::display::escape_path, which writes the control and
bidirectional characters of a name as \u{XXXX}, as text output does.
Only the path is escaped; the rest of a message keeps its layout.

The sync change only rewrites the text of an error and nothing sync
stores changes, so it adds no convergence case.
json_output_keeps_the_stored_names required node --json to hold the
stored name in a field other than output, and only query did: it echoes
the argument, which here is the stored name. For explore --json it
required nothing. Both print {command, query, output, isError}, whose
output is the Markdown codegraph_node or codegraph_explore returns and
names each file escaped.

The test now checks that envelope: its keys alone, command and query
echoing the subcommand and the argument, isError false, and output
naming each file escaped and none raw. The other JSON answers must still
hold each stored name.
docs/cli.md said that --json keeps the stored name of a file. node --json
and explore --json do not: they print {command, query, output, isError},
whose output is the Markdown codegraph_node or codegraph_explore returns,
escaped as text output is, and whose query echoes the argument. The page
now lists the JSON output that keeps the stored name, names these two as
the exception, and points to node.filePath in search --json and path in
files --json for a file's exact stored path.

docs/cli.md and docs/mcp.md also say that a path argument whose two
readings name two stored files is ambiguous, so the answer lists both.
@codecov

codecov Bot commented Dec 2, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.06651% with 8 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/codegraph-cli/src/diagnostics.rs 80.00% 3 Missing ⚠️
crates/codegraph-watch/src/watcher.rs 0.00% 3 Missing ⚠️
crates/codegraph-extract/src/engine.rs 97.82% 1 Missing ⚠️
crates/codegraph-mcp/src/engine.rs 99.55% 1 Missing ⚠️

Impacted file tree graph

@@            Coverage Diff             @@
##             main     #383      +/-   ##
==========================================
+ Coverage   96.45%   96.49%   +0.04%     
==========================================
  Files         381      382       +1     
  Lines      267232   267937     +705     
==========================================
+ Hits       257752   258547     +795     
+ Misses       9480     9390      -90     
Files with missing lines Coverage Δ
crates/codegraph-cli/src/main.rs 93.43% <100.00%> (+0.75%) ⬆️
crates/codegraph-core/src/display.rs 100.00% <100.00%> (ø)
crates/codegraph-graph/src/graph/mod.rs 94.97% <100.00%> (+0.30%) ⬆️
crates/codegraph-mcp/src/context.rs 99.74% <100.00%> (+0.01%) ⬆️
crates/codegraph-mcp/src/query_paths.rs 98.41% <100.00%> (+0.12%) ⬆️
crates/codegraph-watch/src/migrate.rs 96.68% <100.00%> (ø)
crates/codegraph-watch/src/sync.rs 98.75% <100.00%> (+0.06%) ⬆️
crates/codegraph-extract/src/engine.rs 97.42% <97.82%> (+<0.01%) ⬆️
crates/codegraph-mcp/src/engine.rs 98.17% <99.55%> (+0.18%) ⬆️
crates/codegraph-cli/src/diagnostics.rs 93.40% <80.00%> (+0.72%) ⬆️
... and 1 more

... and 5 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@sunerpy
sunerpy merged commit 5f7ff6b into main Dec 2, 2026
12 checks passed
@sunerpy
sunerpy deleted the fix/escape-control-chars branch December 2, 2026 23:06
@github-actions github-actions Bot mentioned this pull request Dec 2, 2026
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.

1 participant