Skip to content

fix: preserve multi-line message body in read_console#1227

Open
GallopingDino wants to merge 1 commit into
CoplayDev:betafrom
GallopingDino:fix/multiline-console-logs
Open

fix: preserve multi-line message body in read_console#1227
GallopingDino wants to merge 1 commit into
CoplayDev:betafrom
GallopingDino:fix/multiline-console-logs

Conversation

@GallopingDino

@GallopingDino GallopingDino commented Jul 1, 2026

Copy link
Copy Markdown

Description

read_console truncated every log entry's message to its first line, so a multi-line Debug.Log("a\nb\nc") came back as just "a" — lines b and c were dropped from message and never surfaced in stackTrace either, with no parameter or resource to recover them. This preserves the full multi-line message body while still separating the appended stack trace into its own gated field.

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Documentation update
  • Refactoring (no functional changes)
  • Test update

Changes Made

  • Replaced ExtractStackTrace with SplitMessageAndStackTrace (+ extracted FindStackStartIndex) in MCPForUnity/Editor/Tools/ReadConsole.cs: the log entry is split into body and appended stack trace at the first stack-frame boundary, and message now receives the entire body instead of only the first line.
  • Line endings are normalized (\r\n/\r\n) and split without RemoveEmptyEntries, so internal blank lines in the body are preserved (e.g. "a\n\nc" stays "a\n\nc").
  • include_stacktrace behavior is unchanged: it still only gates the separate stackTrace field; message is returned independently of it.
  • The stack-frame detection heuristic is intentionally unchanged (only extracted into FindStackStartIndex), so severity classification and stack detection carry no regression.
  • Added EditMode test HandleCommand_Get_PreservesMultilineMessageBody (multi-line log with an internal blank line; asserts the body is preserved and that the appended stack does not leak into message).

Compatibility / Package Source

  • Unity version(s) tested: 2021.3.43f1, 6000.3.12f1
  • Package source used (#beta, #main, tag, branch, or file:): local checkout of CoplayDev/unity-mcp#beta
  • Resolved commit hash from Packages/packages-lock.json (if using a Git package URL): N/A (C#-only change, no package-source change)

Testing/Screenshots/Recordings

  • Python tests (cd Server && uv run pytest tests/ -v)
  • Unity EditMode tests
  • Unity PlayMode tests
  • Package import/compile check
  • Not applicable (explain why in Additional Notes)
    ReadConsole EditMode tests pass on Unity 2021.3.43f1.

Documentation Updates

  • I have added/removed/modified tools or resources
  • If yes, I have updated all documentation files using:
    • The LLM prompt at tools/UPDATE_DOCS_PROMPT.md (recommended)
    • Manual review of the generated changes

No tool/resource surface changed — no new tools, resources, or parameters. Only the value of the existing message field changed (now multi-line), and the auto-generated docs are driven by the parameter registry, which is untouched.

Related Issues

N/A

Additional Notes

  • Change is C#-only; the Python read_console tool passes message through unchanged, and no consumer parses the plain output line-by-line (verified against Server/src/services/tools/read_console.py and the CLI), so a multi-line message breaks nothing downstream.
  • Validated by running Editor tests in UnityMCPTests project on Unity 2021.3.43f1 and by calling read_console via HTTP server on Unity 6000.3.12f1.

Summary by CodeRabbit

  • Bug Fixes
    • Console log entries now preserve multi-line message bodies correctly, including blank lines.
    • Stack traces are separated more reliably from the main message, and can still be hidden when not requested.
  • Tests
    • Added coverage for retrieving detailed console output with multi-line messages to ensure the message text is returned in the expected format.

@coderabbitai

coderabbitai Bot commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Refactors ReadConsole.cs's stack-trace extraction logic, replacing ExtractStackTrace with SplitMessageAndStackTrace and FindStackStartIndex helpers that jointly derive message body and stack trace from log text. Adds a corresponding edit-mode test verifying multiline message body preservation.

Changes

Console message parsing refactor

Layer / File(s) Summary
Message/stack splitting implementation
MCPForUnity/Editor/Tools/ReadConsole.cs
Replaces ExtractStackTrace with SplitMessageAndStackTrace, which normalizes line endings and uses FindStackStartIndex to detect stack-trace boundaries, returning a message/stackTrace tuple; GetConsoleEntries updated to use this and nulls stackTrace when includeStacktrace is false.
Multiline message preservation test
TestProjects/UnityMCPTests/.../ReadConsoleTests.cs
Adds HandleCommand_Get_PreservesMultilineMessageBody test asserting multi-line message bodies (including blank lines) are preserved and the UnityEngine.Debug prefix is excluded.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related PRs

Suggested labels: bug

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main fix: preserving multi-line message bodies in read_console.
Description check ✅ Passed The description mostly matches the template and includes the required sections, change details, compatibility, testing, and notes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot 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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
MCPForUnity/Editor/Tools/ReadConsole.cs (1)

519-547: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

The uppercase+dot fallback can still split legitimate multi-line log bodies (for example Status.\nDetails: X.Y) as stack traces, so some message content will still be lost. Tightening this heuristic would make the split safer for multi-line logs.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@MCPForUnity/Editor/Tools/ReadConsole.cs` around lines 519 - 547, The fallback
in FindStackStartIndex is too permissive and can misclassify normal multi-line
log text as a stack trace, causing message content to be split and lost. Tighten
the heuristic in ReadConsole.FindStackStartIndex by requiring stronger
stack-trace indicators than just an uppercase token with a dot, and prefer the
existing explicit patterns like "at ", "UnityEngine.", "UnityEditor.", or "(at "
before treating a line as stack start.
🧹 Nitpick comments (1)
MCPForUnity/Editor/Tools/ReadConsole.cs (1)

509-517: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Minor: simplify sentinel check.

FindStackStartIndex can only return -1 or an index >= 1 (loop starts at i = 1), so stackStartIndex <= 0 is equivalent to stackStartIndex == -1 here. Not a bug, just slightly misleading.

♻️ Suggested simplification
-            int stackStartIndex = FindStackStartIndex(lines);
-            if (stackStartIndex <= 0)
+            int stackStartIndex = FindStackStartIndex(lines);
+            if (stackStartIndex == -1)
                 return (string.Join("\n", lines), null);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@MCPForUnity/Editor/Tools/ReadConsole.cs` around lines 509 - 517, Simplify the
sentinel check in ReadConsole’s stack-splitting logic: in the code that calls
FindStackStartIndex, replace the broad “<= 0” guard with an explicit “== -1”
check since FindStackStartIndex only returns -1 or a valid index starting at 1.
Keep the existing tuple return behavior in the same parsing block, just make the
condition match the actual return contract of FindStackStartIndex.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@MCPForUnity/Editor/Tools/ReadConsole.cs`:
- Around line 519-547: The fallback in FindStackStartIndex is too permissive and
can misclassify normal multi-line log text as a stack trace, causing message
content to be split and lost. Tighten the heuristic in
ReadConsole.FindStackStartIndex by requiring stronger stack-trace indicators
than just an uppercase token with a dot, and prefer the existing explicit
patterns like "at ", "UnityEngine.", "UnityEditor.", or "(at " before treating a
line as stack start.

---

Nitpick comments:
In `@MCPForUnity/Editor/Tools/ReadConsole.cs`:
- Around line 509-517: Simplify the sentinel check in ReadConsole’s
stack-splitting logic: in the code that calls FindStackStartIndex, replace the
broad “<= 0” guard with an explicit “== -1” check since FindStackStartIndex only
returns -1 or a valid index starting at 1. Keep the existing tuple return
behavior in the same parsing block, just make the condition match the actual
return contract of FindStackStartIndex.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 1a7cdd0b-5c23-4f51-8dff-de2f0d64f895

📥 Commits

Reviewing files that changed from the base of the PR and between 8618f83 and 85b6939.

📒 Files selected for processing (2)
  • MCPForUnity/Editor/Tools/ReadConsole.cs
  • TestProjects/UnityMCPTests/Assets/Tests/EditMode/Tools/ReadConsoleTests.cs

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