Skip to content

feat(android): add mobile_logcat_dump mcp tool#257

Open
singhsume123 wants to merge 8 commits intomobile-next:mainfrom
singhsume123:feat/logcat-dump
Open

feat(android): add mobile_logcat_dump mcp tool#257
singhsume123 wants to merge 8 commits intomobile-next:mainfrom
singhsume123:feat/logcat-dump

Conversation

@singhsume123
Copy link
Copy Markdown
Contributor

@singhsume123 singhsume123 commented Jan 29, 2026

What

Adds a new Android-only MCP tool: mobile_logcat_dump, which allows agents to fetch recent logcat output for debugging mobile automation runs.

Why

When UI automation fails (taps ignored, deep links not handled, permission issues, crashes), there is currently no observability. Logcat provides the missing signal needed to diagnose these failures.

Features

  • Dump last N logcat lines (default 200, capped)
  • Filter by package name or PID
  • Uses logcat --pid when supported, with safe client-side fallback
  • Supports buffers (main, crash, system)
  • Supports minimum priority (I, W, E, etc.)
  • Optional include / exclude regex filtering
  • Output truncation to avoid oversized responses

Tests

  • Added Android device-gated tests following existing test patterns
  • Tests are skipped automatically when no Android device is connected

Also did some manual testing with running prompts . Attaching Screen shots for the same

Prompt 1

Screenshot 2026-01-28 at 3 34 38 PM

Prompt 2
Screenshot 2026-01-28 at 3 37 21 PM

Notes

  • Android-only by design
  • README updated under Diagnostics & Debugging

Summary by CodeRabbit

  • New Features

    • Added a diagnostic tool to dump recent Android logcat with advanced filtering capabilities including package name, process ID, priority levels, specific log buffers, and regex-based pattern matching for includes and excludes.
  • Documentation

    • Updated README with new Diagnostics & Debugging section documenting the logcat dump feature.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Jan 29, 2026

Walkthrough

Introduces a new logcat diagnostic tool for Android devices that enables dumping recent Android logcat entries with optional filtering by package name, buffers, priority levels, and regex patterns. The feature is integrated into the MCP server and includes comprehensive metadata in responses.

Changes

Cohort / File(s) Summary
Core Feature Implementation
src/android.ts
Added LogcatDumpOptions interface and public logcatDump() method to AndroidRobot class. Includes internal helpers for PID resolution (tryResolvePid), numeric clamping (clampInt), and text truncation (truncateText). Supports logcat filtering by buffers, format, priority, package name, and regex patterns with fallback mechanisms.
Server Tool Registration
src/server.ts
Registered new mobile_logcat_dump MCP tool with comprehensive input schema covering device selection, line limits, format, buffers, priority, PID, package name, and regex filters. Tool validates Android device type and returns formatted JSON response.
Test Coverage
test/android.ts
Added two test cases validating logcat dump functionality: basic package dump with output verification, and regex filtering capabilities with metadata assertions.
Documentation
README.md
Added Diagnostics & Debugging section documenting the mobile_logcat_dump tool and its filtering capabilities.
Artifact
src/Untitled
Single-line file containing text "logcatDump". Purpose unclear; may warrant review for removal or proper naming.
🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly and clearly summarizes the main change: adding the mobile_logcat_dump MCP tool to the Android functionality, which is the primary objective of the PR.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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 and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Fix all issues with AI agents
In `@src/android.ts`:
- Around line 595-602: Wrap each RegExp construction for opts.includeRegex and
opts.excludeRegex in a try-catch so invalid patterns don't crash the process:
when constructing new RegExp(opts.includeRegex) or new RegExp(opts.excludeRegex)
catch SyntaxError, log a clear user-facing message that includes the bad pattern
and error.message, and skip applying that particular filter (leave lines
unchanged) instead of letting the exception propagate; reference the existing
variables opts.includeRegex, opts.excludeRegex and lines when locating where to
add the try-catch.

In `@test/android.ts`:
- Around line 181-261: Remove the duplicated test blocks by deleting the second
copies of the two it(...) tests named "should be able to dump logcat for a
package" and "should support includeRegex / excludeRegex filtering in logcat
dump" (the repeated it(...) blocks starting after the first occurrences); keep
the original first instances (the initial it(...) with those exact names) and
remove the duplicated copies so each test appears only once in test/android.ts.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@src/android.ts`:
- Around line 642-657: The current fallback uses
this.silentAdb("shell","ps","-A") and finds a line with l.includes(packageName),
which can match partial package names; update the matching to require an exact
process name match (e.g., use a RegExp word-boundary match or compare the
process NAME column exactly to packageName) when selecting the line from
out.split("\n").find(...), and ensure you still parse PID from cols[1] only
after confirming the exact NAME match; use the existing silentAdb and
packageName symbols in the change.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@src/android.ts`:
- Around line 588-592: The client-side PID filter (using pidResolved,
pidFilterMode, pidRe and lines.filter) incorrectly assumes threadtime format and
can silently drop or mis-match lines; change the logic to only apply the
client-side filter when the log format is explicitly "threadtime" (reject or
skip filtering for "time", "brief", etc.), and implement a robust match for the
PID column instead of a loose /\s${pidResolved}\s/ regex — e.g. for threadtime
parse the whitespace-delimited columns (or target the PID column index) and
compare that column to pidResolved before keeping the line; ensure pidFilterMode
=== "client-side" still checks the format and falls back to no-op (or an
explicit error/warn) for non-threadtime formats.

@gmegidish
Copy link
Copy Markdown
Member

Hey @singhsume123 Thank you for this pull request. We had such a PR in the past, and it didn't work. I will have to check it manually. When you use 2000 rows, does it work? I found that on real android devices 99% of the logs are just wifi and 5G signal logs, so it requires additional filtering.

Can you share some prompts you have used this with?

Thank you! 🚀

@singhsume123
Copy link
Copy Markdown
Contributor Author

Hey @gmegidish , thanks for the review, you are correct.

With 2000 lines, the output was ~52k tokens which exceeds the LLM's context limit. The tool returned successfully but the agent couldn't process the full output. I've pushed fixes:

  1. Reduced max lines from 2000 → 500
  2. Reduced character truncation from 200k → 80k chars (~20k tokens)
  3. Added helpful truncation message pointing users to filters

Sample prompts tested:


Prompt 1: Dump last 500 logcat lines and summarize

Logcat Summary (Last 500 Lines)
Timeframe: 19:59:32 - 19:59:35 (~3 seconds of activity)

By Process/App
| Process               | PID   | Activity Level                   |
|-----------------------|-------|----------------------------------|
| YouTube               | 3952  | High - video playback, QoE pings |
| AiAiVC (Google AI)    | 1714  | High - many capture events       |
| GMS (Google Services) | 10388 | Low - SELinux denials            |
| adservices            | 3972  | Low - consent/Cobalt disabled    |
| AudioFlinger          | 485   | Low - audio track creation       |
| netd                  | 415   | Low - network stats              |

Error Summary
| Count | Type                               | Source     | Description                                |
|-------|------------------------------------|------------|--------------------------------------------|
| 3     | CancellationException              | YouTube    | Tasks cancelled (benign - user navigation) |
| 1     | No reel navigator                  | YouTube    | Missing navigator in Shorts                |
| 1     | Null interactionLoggingScreen      | YouTube    | Logging cleanup issue                      |
| 1     | Consent notification not displayed | adservices | Privacy consent pending                    |
| 4     | SELinux avc: denied                | GMS        | Access denied for ADB properties           |

Warning Summary
| Count | Type                                         | Source       |
|-------|----------------------------------------------|--------------|
| 15+   | Unexpected capture event type: 11            | AiAiVC       |
| 8+    | BitmapDrawable created with null Bitmap      | YouTube      |
| 6+    | Missing Vss3Config / VSS ping warnings       | YouTube      |
| 6+    | query failed / param skipped                 | Codec2Client |
| 4+    | LoggingNode without YouTubeLoggingProperties | YouTube      |
| 8+    | Image decoding logging dropped               | HWUI         |

Key Observations
1. No crashes - System is stable
2. YouTube Shorts playback active - Multiple video load/stop/queue cycles
3. Codec reuse working - c2.goldfish.vp9.decoder being reused efficiently
4. GC activity - One background GC freed 17MB (29% free, 56MB/80MB heap)
5. SELinux blocking GMS - Google Services denied access to ADB properties (normal behavior)

Prompt 2: Dump logcat logs for com.google.android.youtube

Summary:
- PID: 3952
- Timeframe: 19:51:31 - 19:53:34

| Level | Tag            | Description                                      |
|-------|----------------|--------------------------------------------------|
| E     | YT.mlplayer    | Media player end events                          |
| E     | YT.qoe         | Quality of Experience pings to YouTube stats API |
| W     | YouTube        | VSS ping warnings, missing Vss3Config            |
| W     | YT.mlplayer    | Stayawake ON/OFF toggles                         |
| W     | BitmapDrawable | BitmapDrawable created with null Bitmap          |

No crashes detected.

Prompt 3: Dump logcat for com.google.android.youtube with includeRegex "Exception|Error|Crash"

02-02 19:58:24.868  3952  4072 E YouTube : java.util.concurrent.CancellationException: Task was cancelled.
02-02 19:58:25.337  3952  4016 E YouTube : java.util.concurrent.CancellationException: Task was cancelled.

For the noise issue you mentioned (wifi/5G logs), the tool supports filtering on multiple dimensions: packageName, pid, minPriority, buffers, includeRegex, and excludeRegex. This lets agents scope down to relevant logs instead of drowning in system noise.

Let me know what do you think ?

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 Fix all issues with AI agents
In `@pinch_zoom_implementation_plan.md`:
- Around line 221-232: The fenced code block containing the touch script
starting with "d 0 300 800 50" and the separate example block that starts with
"Zoom in 2x on the center of a map:" are missing language identifiers and
trigger MD040; add an appropriate language tag (e.g., ```text or ```bash for the
touch script block and ```markdown for the explanatory example) immediately
after each opening triple-backtick so both fenced blocks include a language
identifier.

In `@src/android.ts`:
- Around line 14-18: Update the documentation comment for the
LogcatDumpOptions.lines field to reflect the actual enforced maximum (500)
instead of 2000 so users aren't misled; locate the LogcatDumpOptions interface
and change the comment on the lines property (currently "default 200, max 2000")
to state "default 200, max 500" (or similar) to match the clampInt behavior used
when parsing/validating lines.
- Around line 565-603: The code may set pidFilterMode = "client-side" even when
client-side filtering is skipped for non-"threadtime" formats; update the logic
around pidFilterMode (the variable used alongside pidResolved and format in the
conditional that performs client-side filtering) so that when format !==
"threadtime" and you skip filtering you change pidFilterMode to "none" (or a new
explicit "skipped" state) before returning/continuing, and ensure any downstream
uses of pidFilterMode reflect that change; modify the branch that currently only
logs the warning to also set pidFilterMode = "none" (or "skipped") to accurately
represent that no PID filtering was applied.
🧹 Nitpick comments (1)
src/Untitled (1)

1-1: Remove stray placeholder file.
A single-word file in src/ provides no functional value and may confuse tooling or reviewers. If this isn’t intentional, please delete it.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@src/android.ts`:
- Around line 90-93: The truncateText implementation slices the original text to
maxChars and then appends the truncation message, which can exceed the hard
limit; modify truncateText to reserve space for the truncation suffix (the
literal "[OUTPUT TRUNCATED - Use packageName, minPriority, includeRegex, or
excludeRegex filters to reduce output]\n\n") and if maxChars is smaller than the
suffix length, return a truncated suffix clipped to fit; ensure the returned
string length is always <= maxChars and that the function still returns
truncated: true when any truncation occurs.

@singhsume123
Copy link
Copy Markdown
Contributor Author

@gmegidish

Also happy to contribute to roadmap items. Happy to do non urgent requests if there are any

@singhsume123
Copy link
Copy Markdown
Contributor Author

Hey @gmegidish , I thought about this more and wanted to share a use case that I think really shows the value here.

Consider Jetpack Compose recomposition debugging. A developer adds SideEffect { Log.d("RecomposeTracker", "MyWidget recomposed") } in their composables. Today, an AI agent using mobile-mcp can see the UI via screenshots — but it's completely blind to what's happening at runtime. With mobile_logcat_dump, the agent can call it with includeRegex: "RecomposeTracker" and packageName, get just those tagged logs, and then tell the developer "hey, MyWidget is recomposing 40 times per frame because of unstable params — here's the fix."

That's the general pattern: devs instrument their code with specific log tags, and the agent filters on those tags to get signal instead of noise. The includeRegex / excludeRegex / minPriority / packageName filters are specifically designed to cut through the wifi/5G noise you mentioned from the earlier PR.

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.

2 participants