ScreenSync MCP guide

Testing Android FileProvider with Claude Code and MCP

Test Android FileProvider and secure content URI sharing with Claude Code and ScreenSync MCP. Verify intent grants, share sheets, and permissions on hardware.

Testing Android FileProvider with Claude Code and MCP

Securing inter-process file communication on modern mobile operating systems represents one of the most critical security boundaries in mobile software engineering. Starting with Android 7.0 (Nougat, API level 24), the Android platform strictly prohibits the exposure of raw filesystem paths via file:// Uniform Resource Identifiers (URIs). Attempting to pass a raw filesystem pointer across application sandbox boundaries immediately throws a runtime FileUriExposedException, abruptly crashing the originating process. To facilitate secure inter-app data exchange—such as sharing PDF invoices, sending exported CSV reports, attaching high-resolution photos to support tickets, or handing off captured videos to external editors—Android mandates the use of androidx.core.content.FileProvider. This specialized ContentProvider subclass encapsulates private disk paths behind virtual, encrypted content:// URIs and enforces granular, temporary access grants through Android's binder architecture.

Despite its ubiquity across modern enterprise and consumer applications, FileProvider remains notoriously difficult to validate within traditional continuous integration (CI) and automated quality assurance pipelines. Standard unit tests running in headless Java Virtual Machine (JVM) harnesses mock away underlying Linux file permissions, SELinux policies, and binder transaction boundaries. Meanwhile, synthetic emulator tests often obscure OEM-specific share sheet customizations, asynchronous content resolution race conditions, and transient permission revocation triggered by task destruction. When a user taps an export button, the interaction frequently crosses multiple external processes: the originating application, the system Android Intent Resolver (or ChooserActivity), and an untrusted recipient application like Gmail, Slack, Google Drive, or an OEM document viewer. If an application developer neglects to supply Intent.FLAG_GRANT_READ_URI_PERMISSION, misconfigures res/xml/file_paths.xml, or omits secondary clip data grants in Android 10 and later, the receiving process crashes with an unrecoverable SecurityException: Permission Denial.

The Model Context Protocol (MCP) revolutionizes this validation paradigm by bridging autonomous AI coding assistants, such as Claude Code, Cursor, and VS Code in agent mode, directly to physical Android hardware. By decoupling high-speed visual display perception via Android's native MediaProjection API from deterministic device control and low-level debugging telemetry over Android Debug Bridge (ADB), ScreenSync MCP equips autonomous agents with the perceptual and analytical capabilities of a senior mobile systems architect. Operating locally on the developer workstation, Claude Code can autonomously launch target application builds, trigger multi-step file generation workflows, parse the Android system share sheet hierarchy, verify recipient preview rendering, extract logcat binder grant telemetry in real time, and surgically refactor XML path configurations and Kotlin intent builders directly in the repository source code.

Key Takeaways

  • Hardware Sandbox Boundary Testing: ScreenSync MCP bridges Claude Code directly to physical Android silicon, enabling automated validation of FileProvider content URIs, Linux DAC sandbox boundaries, and binder access tokens across real-world application processes.
  • Non-Invasive Frame Perception: Display capture runs natively through Android's MediaProjection API without requiring root access or ADB screen capture overhead, streaming sub-100 millisecond visual frames across the local network to verify share sheet dialogs and file previews.
  • Deterministic Share Sheet Traversal: Autonomous device control commands—including coordinate taps, swipe gestures, and system back-presses—execute deterministically over ADB via USB or wireless debugging to navigate system IntentResolver dialogs without flaky OCR heuristics.
  • Autonomous Logcat Grant Auditing: Claude Code queries device system buffers via get_logcat to instantly isolate SecurityException: Permission Denial stack traces, IllegalArgumentException path mapping mismatches, and FileUriExposedException crashes.
  • In-Repo XML & Kotlin Remediation: Operating directly inside the project repository, Claude Code cross-references caught permission denials with local file_paths.xml declarations and Kotlin intent structures, adding missing flags or cache path roots in seconds.
  • Unified Cross-Surface Workflows: By pairing 29 mobile and desktop tools with 197 browser automation tools across 226 total MCP tools, ScreenSync MCP enables end-to-end testing where files exported from an Android application are verified inside web portal dashboards.

The Mechanics of Android FileProvider: Sandbox Isolation, Content URIs, and Binder Grants

Testing Android FileProvider with Claude Code and Model Context Protocol (MCP) requires understanding how Android isolates file storage across Unix user identifiers (UIDs). By converting private files into content URIs, FileProvider allows applications to share data securely with temporary read and write permissions without exposing internal filesystem paths or triggering runtime crashes.

Android's core security model is grounded in Linux Discretionary Access Control (DAC) and Security-Enhanced Linux (SELinux) policies. Each installed application is assigned a unique, isolated Unix user identifier (e.g., u0_a214). By default, files created by an application inside internal storage directories—such as /data/user/0/com.example.app/files or /data/user/0/com.example.app/cache—possess strict 0700 filesystem permissions, making them completely inaccessible to any other user process on the operating system.

Prior to Android 7.0, applications frequently bypassed this isolation by placing files into shared public storage (e.g., /sdcard/Download) or passing raw file:/// filesystem paths directly inside an Intent. When a recipient application received a file URI, it attempted to open the path using standard POSIX open() system calls. If the file resided in the originating application's internal directory, the Linux kernel blocked the call with EACCES (Permission denied). To prevent security vulnerabilities and inconsistent behavior across OEM builds, Google introduced the StrictMode.VmPolicy check, which enforces FileUriExposedException whenever a file URI leaves an application boundary.

To bridge this barrier securely, androidx.core.content.FileProvider extends ContentProvider to synthesize virtual, temporary content URIs under the content:// scheme. Instead of revealing physical directory hierarchies on disk, FileProvider replaces filesystem roots with path aliases declared in an XML resource file. When an application generates a content URI via FileProvider.getUriForFile(), the system maps the physical file path to the declared alias.

Crucially, content URIs do not confer ambient filesystem access. Instead, the originating application attaches explicit grant flags to the outgoing Intent:

  1. Intent.FLAG_GRANT_READ_URI_PERMISSION: Grants the recipient application ephemeral read access to the specific content URI.
  2. Intent.FLAG_GRANT_WRITE_URI_PERMISSION: Grants the recipient application ephemeral write access to overwrite or stream data into the target file descriptor.

When the user selects a recipient application from the system share sheet, Android's ActivityManagerService registers a temporary URI permission grant in its internal binder grant tables. When the recipient process invokes contentResolver.openInputStream(contentUri), the Android platform intercepts the Binder transaction, verifies the active grant token against the caller's UID, requests the ParcelFileDescriptor from FileProvider, and pipes the data across the sandbox boundary. Once the recipient activity finishes or the originating task is eviscerated, the temporary grant token expires automatically. For a broader exploration of how Android sandboxes persistent data and media collections, explore our guide on testing Android Scoped Storage with Claude Code and MCP.

The following production-grade Kotlin implementation demonstrates how to build and configure a resilient, modern file sharing workflow utilizing FileProvider, secondary ClipData grants, and system chooser intents:

package com.example.screensync.sharing

import android.content.ClipData
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.core.content.FileProvider
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

object DocumentSharingEngine {

    private const val FILE_PROVIDER_AUTHORITY = "com.example.screensync.fileprovider"

    /**
     * Generates a sample export file in the internal cache directory, encapsulates it
     * behind a secure FileProvider content URI, and builds a chooser Intent with explicit
     * read permission grants.
     */
    fun createShareIntent(context: Context, reportName: String, content: String): Intent {
        // 1. Write the payload into the dedicated 'reports' subdirectory inside private cache
        val reportsDir = File(context.cacheDir, "reports").apply {
            if (!exists()) mkdirs()
        }
        val targetFile = File(reportsDir, "$reportName.txt")

        try {
            FileOutputStream(targetFile).use { outputStream ->
                outputStream.write(content.toByteArray(Charsets.UTF_8))
                outputStream.flush()
            }
        } catch (e: IOException) {
            throw IllegalStateException("Failed to write report payload to disk: ${e.message}", e)
        }

        // 2. Encapsulate the canonical disk file behind a virtual content URI
        val contentUri: Uri = FileProvider.getUriForFile(
            context,
            FILE_PROVIDER_AUTHORITY,
            targetFile
        )

        // 3. Assemble the outgoing ACTION_SEND Intent
        val shareIntent = Intent(Intent.ACTION_SEND).apply {
            type = "text/plain"
            putExtra(Intent.EXTRA_STREAM, contentUri)
            putExtra(Intent.EXTRA_SUBJECT, "Audited System Diagnostics Report")
            putExtra(Intent.EXTRA_TEXT, "Attached is the validated test report.")

            // MANDATORY: Attach read permission grant flag to the Intent
            addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)

            // MANDATORY FOR ANDROID 10+ (API 29+): Set ClipData to ensure permission propagation
            // ChooserActivity and target apps reliably extract grants from ClipData
            clipData = ClipData.newRawUri("System Diagnostics", contentUri)
        }

        // 4. Wrap with Intent.createChooser to display the native system share sheet
        return Intent.createChooser(shareIntent, "Share Diagnostics Via").apply {
            // Re-apply grant flags to the chooser container intent
            addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        }
    }
}

Alongside the Kotlin intent builder, the application must configure its XML path mapping in res/xml/file_paths.xml and register the provider in AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<!-- res/xml/file_paths.xml -->
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Maps context.cacheDir/reports to content://.../export_cache/reports/ -->
    <cache-path name="export_cache" path="reports/" />

    <!-- Maps context.filesDir/exports to content://.../export_files/exports/ -->
    <files-path name="export_files" path="exports/" />
</paths>
<!-- AndroidManifest.xml provider registration -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <application>
        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="com.example.screensync.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>
    </application>
</manifest>

When applications fail to maintain absolute alignment between the physical file directory created on disk and the <paths> declared in XML, FileProvider throws an unhandled IllegalArgumentException: Failed to find configured root that contains.... To understand how custom providers manage broader database and query operations, consult our architecture review on testing Android Content Providers with Claude Code and MCP.

Architectural Pipeline: How ScreenSync MCP Decouples Frame Perception from ADB Intent Telemetry

The ScreenSync MCP architectural pipeline separates high-speed visual display perception from deterministic ADB device control and low-level diagnostic telemetry. Display frames stream continuously from the physical Android device via Android's native MediaProjection API to a local Node.js desktop hub, while device interactions, UI hierarchy queries, and logcat buffer inspection execute over Android Debug Bridge (ADB).

In conventional automated testing architectures, evaluating inter-process file sharing introduces severe technical challenges. When an application launches the system share sheet, the test runner transitions from inspecting the private application window to inspecting a system-level process managed by com.android.intentresolver or com.google.android.apps.messaging. Standard UI test frameworks like Espresso cannot interact with UI components belonging to other application packages unless developers integrate complex UI Automator configurations. Furthermore, trying to extract visual proof of file previews via adb exec-out screencap saturates workstation USB communication channels, causing capture latencies between 900 ms and 3,200 ms per screen. When an AI agent must interactively choose an app, dismiss runtime prompts, and inspect preview dialogs, this transmission latency cripples agent responsiveness.

ScreenSync MCP resolves this communication bottleneck through a high-performance dual-channel architecture. On the mobile hardware, a lightweight native Android application (package com.screensync.mcp, compatible with Android 7.0 and later) runs as a foreground service. Upon initialization, the app requests one-time user consent through Android's native MediaProjection API. Once authorized, the device hardware video encoder streams high-speed display frames over local Wi-Fi or LAN directly to the ScreenSync MCP desktop hub running on Node.js 18+. This direct streaming architecture achieves a median visual mirror latency of approximately 94 ms, operating completely without root privileges and without consuming ADB bandwidth.

Simultaneously, device control tools (control_tap, control_swipe, control_type) and diagnostic observation tools (get_ui_hierarchy, get_logcat) execute over standard ADB protocols via USB or authenticated wireless debugging. Because video frames do not traverse the ADB daemon, diagnostic telemetry calls execute with rapid sub-50ms roundtrip speeds. Claude Code can dispatch a tap to trigger the share sheet, fetch the structural Accessibility Node tree via get_ui_hierarchy to identify system chooser options, and stream logcat buffers via get_logcat to confirm binder URI grant allocations in real time. To learn more about low-level display capture mechanisms, read our guide on how screen MCP servers capture mobile displays.

The following comparison table highlights the architectural differences between ScreenSync MCP and traditional mobile file sharing testing methodologies:

Testing & Validation Paradigm Telemetry & Capture Mechanism Cross-App Sandbox Traversal Visual Preview Verification Real Hardware Execution Agentic AI Remediation Support
ScreenSync MCP + Claude Code Stdio MCP + MediaProjection + ADB Logcat Native (Inspects system IntentResolver & recipient apps) Yes (~94 ms live visual mirror) Yes (Physical Android 7.0+ devices) Yes (Direct repository Kotlin & XML edits)
Espresso Intents (IntentsTestRule) In-Process Binder Interception None (Mocks external Intent matching; does not launch) None (Blind assertion on intent fields) Optional (Typically run on emulators) None (Requires manual script maintenance)
UI Automator (Standalone) Accessibility Node Tree via ADB Yes (Can traverse across system packages) Slow (Relies on manual screencap dumps) Yes None (Requires static script authoring)
Android Studio Intent Debugger Manual Logcat & Shell (am start) Manual (Requires human operator) Manual (Human visual verification) Yes None (Manual developer debugging)
Robolectric (JVM Shadow Mocks) ShadowContentResolver / ShadowIntent None (Synthetic in-memory JVM structures) None (No graphics rendering engine) No (Synthetic JVM host only) None (Fails to catch real Linux DAC leaks)

Intercepting File Sharing Failures: SecurityException, Path Traversal, and URI Permission Denials

Intercepting file sharing failures with Claude Code requires capturing system logcat streams and analyzing permission exceptions during inter-process communication. When an application exports a file without granting read permissions or declares invalid directory paths, Claude Code isolates the stack trace using the get_logcat MCP tool and identifies the exact architectural failure.

When engineering inter-app file handoffs, mobile developers routinely encounter three fatal exception categories that escape synthetic test suites but instantly disrupt end users on physical hardware:

1. SecurityException: Permission Denial

The most prevalent FileProvider defect occurs when an application dispatches an ACTION_SEND or ACTION_VIEW intent containing a content:// URI but forgets to attach Intent.FLAG_GRANT_READ_URI_PERMISSION. When the recipient application attempts to resolve the URI via ContentResolver.openInputStream(), the Android platform checks the calling package's active grants. Finding no active authorization token in the kernel binder table, the platform terminates the recipient process with a fatal exception:

java.lang.SecurityException: Permission Denial: reading androidx.core.content.FileProvider 
uri content://com.example.screensync.fileprovider/export_cache/reports/diagnostic_dump.txt 
from pid=14892, uid=10287 requires the provider be exported, or grantUriPermission()
    at android.os.Parcel.createExceptionOrNull(Parcel.java:3011)
    at android.os.Parcel.createException(Parcel.java:2995)
    at android.os.BinderProxy.transactNative(Native Method)
    at android.os.BinderProxy.transact(BinderProxy.java:584)
    at android.content.IContentProvider$Stub$Proxy.openAssetFile(IContentProvider.java:628)
    at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:1812)
    at android.content.ContentResolver.openInputStream(ContentResolver.java:1528)

Because ScreenSync MCP equips Claude Code with 29 phone and desktop tools, the agent queries device telemetry immediately following a share sheet action:

{
  "name": "get_logcat",
  "arguments": {
    "grep": "SecurityException",
    "lines": 150
  }
}

Claude Code ingests this logcat buffer, extracts the offending content URI (content://com.example.screensync.fileprovider/...), identifies the missing grant flag, and immediately reviews the local Kotlin intent builder to inject Intent.FLAG_GRANT_READ_URI_PERMISSION.

2. IllegalArgumentException: Unconfigured Storage Roots

A second common failure occurs when an application attempts to encapsulate a file stored in a directory that is not registered in res/xml/file_paths.xml. For example, if a developer saves a temporary log file to context.filesDir but only declared <cache-path> in XML, invoking FileProvider.getUriForFile() causes an immediate crash:

java.lang.IllegalArgumentException: Failed to find configured root that contains 
/data/user/0/com.example.screensync/files/telemetry/session_82.log
    at androidx.core.content.FileProvider$SimplePathStrategy.getUriForFile(FileProvider.java:744)
    at androidx.core.content.FileProvider.getUriForFile(FileProvider.java:442)
    at com.example.screensync.sharing.DiagnosticExporter.exportLogs(DiagnosticExporter.kt:48)

Claude Code detects this trace, inspects the canonical disk path in the exception message, and edits res/xml/file_paths.xml to add the missing <files-path name="telemetry" path="telemetry/" /> entry.

3. Missing ClipData Grants in Android 10 and Above

Starting in Android 10 (API level 29), the Android framework modified how permissions propagate through Intent.createChooser(). If an application attaches a content URI exclusively to Intent.EXTRA_STREAM without explicitly setting intent.clipData = ClipData.newRawUri(...), certain third-party recipient apps and system share sheets fail to inherit the underlying URI permission grant. The user sees the chooser dialog, but upon selecting an app, the recipient opens with a blank screen or a "File not found" error.

By taking a hardware screenshot with get_latest_screenshot and correlating the visual state with system logcat telemetry, Claude Code catches these silent permission drop-offs that traditional assertions miss entirely. To review how runtime permissions interact with broader security privileges, read testing Android Runtime Permissions with Claude Code and MCP.

Step-by-Step Setup: Configuring Claude Code and ScreenSync MCP for FileProvider Validation

Configuring Claude Code and ScreenSync MCP for FileProvider validation requires four systematic steps: verifying developer workstation prerequisites, launching the local Node.js desktop hub, registering the MCP server inside Claude Code, and establishing a physical device connection over USB or wireless debugging.

Step 1: Workstation and Hardware Verification

Before initializing autonomous testing routines, ensure your development workstation and test device satisfy the following specifications:

  1. Host Computer: Windows 10/11, macOS (Intel or Apple Silicon), or modern Linux distribution with Node.js 18+ installed and configured on your system PATH.
  2. Physical Android Device: A physical smartphone or tablet operating on Android 7.0 (API level 24) or newer.
  3. Android Platform Tools: Android Debug Bridge (adb) installed and accessible from terminal environments.
  4. Unified Local Network: The developer workstation and Android test device must be connected to the same Wi-Fi router or local subnet to enable low-latency MediaProjection streaming and mDNS hub discovery.

Step 2: Initialize the ScreenSync MCP Desktop Hub

Download the ScreenSync MCP desktop hub package from ScreenSync MCP. Extract the package into a dedicated workstation directory (such as C:\tools\screensync-hub on Windows or ~/tools/screensync-hub on macOS/Linux).

Start the desktop hub by running the platform launcher script:

# On Linux or macOS
cd ~/tools/screensync-hub
chmod +x start-hub.sh
./start-hub.sh

# On Windows (PowerShell or Command Prompt)
cd C:   ools\screensync-hub
.\start-hub.bat

The desktop hub initializes a local HTTP server listening on port 3000 to receive MediaProjection video frames and registers Model Context Protocol endpoints over standard input/output (stdio). The hub console output displays your session bearer token (SCREEN_SYNC_TOKEN) and prints an ASCII QR code for fast mobile onboarding.

Step 3: Register ScreenSync MCP in Claude Code and Claude Desktop

To connect the Claude Code CLI tool to ScreenSync MCP, open your terminal and register the server using the standard CLI command:

# Register ScreenSync MCP in Claude Code CLI
claude mcp add screensync node "/path/to/screensync-hub/screensync-hub.js"

If you are using Claude Desktop, open your configuration file (claude_desktop_config.json, accessible via Settings > Developer > Edit Config) and insert the server configuration block:

{
  "mcpServers": {
    "screensync": {
      "command": "node",
      "args": [
        "/path/to/screensync-hub/screensync-hub.js"
      ],
      "env": {
        "SCREEN_SYNC_TOKEN": "your_hub_bearer_token_here"
      }
    }
  }
}

Note: Web-based chat interfaces such as ChatGPT cannot connect directly to ScreenSync MCP because browser web apps require remote HTTPS-based MCP relays rather than local stdio processes. ScreenSync MCP is built specifically for local engineering environments including Claude Desktop, Claude Code, Cursor, and VS Code.

Step 4: Install the Mobile App and Pair Device Debugging

On your physical Android test smartphone, download and install the free ScreenSync MCP application (package com.screensync.mcp) directly from Google Play.

  1. Launch the ScreenSync MCP application on your Android device.
  2. The app will discover your desktop hub automatically using mDNS on your local Wi-Fi. If your local network isolates UDP broadcast packets, tap the QR scanner icon inside the mobile app and scan the terminal QR code displayed by the hub.
  3. Tap Start Projection. Android will display a system security dialog asking for screen capture authorization. Tap Start Now to begin streaming graphics compositor frames via MediaProjection.
  4. Enable Developer Options on your device (open Settings > About Phone and tap Build Number seven times), navigate to Developer Options, and enable USB Debugging or Wireless Debugging.
  5. Connect your device via USB or pair wirelessly using our comprehensive tutorial on Android wireless debugging for MCP servers. Run adb devices in your workstation terminal to verify the active hardware connection. For complete setup guidance, visit the official ScreenSync MCP setup guide.

End-to-End Autonomous FileProvider Workflows in Practice

End-to-end autonomous FileProvider workflows with Claude Code execute structured file export sequences across physical Android devices to validate content URIs and binder permissions. Claude Code triggers file generation in target applications, parses system share sheet dialogs, verifies recipient preview rendering, and edits local source files to eliminate permission errors.

Workflow 1: Triggering Document Export and Share Sheet Traversal

In an enterprise banking, healthcare, or field service application, exporting reports requires coordinating multiple system services. A developer instructs Claude Code to validate the export journey:

Developer Directive to Claude Code:
"Claude, launch our staging app, navigate to the Invoices tab, export the invoice for Order #8491 as a PDF, verify that the Android system share sheet opens with the correct file thumbnail, and ensure no SecurityException is logged in logcat."

Upon receiving this prompt, Claude Code initiates an autonomous execution loop:

  1. Launch Target Application:
    Claude Code calls control_launch_app to bring the staging build to the foreground:

    {
      "name": "control_launch_app",
      "arguments": {
        "packageName": "com.example.screensync.billing",
        "activity": "com.example.screensync.billing.MainActivity"
      }
    }
  2. Locate and Tap Export Button:
    Claude Code calls get_ui_hierarchy to locate the invoice export button in the View tree or Compose layout:

    {
      "name": "get_ui_hierarchy",
      "arguments": {}
    }

    Finding resource-id="com.example.screensync.billing:id/btn_export_pdf" at bounds [780, 1920, 1020, 2040], Claude Code dispatches control_tap to coordinates (900, 1980).

  3. Traverse System Share Sheet:
    The operating system displays the native Android Chooser (com.android.intentresolver). Claude Code invokes get_ui_hierarchy again. Because ScreenSync MCP reads the system-level accessibility tree, Claude Code inspects the chooser components:

    • Header text: "Share Diagnostics Via"
    • Preview image container: resource-id="android:id/content_preview_image"
    • File title: "invoice_8491.pdf"
  4. Visual Frame Confirmation:
    Claude Code invokes get_latest_screenshot to confirm that the PDF icon and title rendered correctly in the UI without clipping or placeholder glitches. To understand why combining structural node trees with visual frames prevents touch target drift during rapid navigation loops, review our analysis on Android UI hierarchy vs computer vision: why LLMs need structural node trees to prevent drift.

Workflow 2: Cross-Application Handoff and SecurityException Remediation

To verify that the recipient application can actually read the shared file descriptor, Claude Code completes the handoff:

  1. Select Recipient Target:
    Inside the share sheet, Claude Code uses control_tap to select a recipient app, such as Google Drive or an OEM file viewer.
  2. Audit System Logcat Telemetry:
    Claude Code immediately checks device logs using get_logcat:
    {
      "name": "get_logcat",
      "arguments": {
        "grep": "Permission Denial",
        "lines": 100
      }
    }
  3. Isolate Root Cause:
    If get_logcat reveals a SecurityException: Permission Denial because the originating intent omitted Intent.FLAG_GRANT_READ_URI_PERMISSION, Claude Code does not stop. It transitions from tester to software engineer:
    • Locates InvoiceExportManager.kt in the local repository.
    • Modifies the intent creation logic to add addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) and populates clipData.
    • Triggers ./gradlew assembleDebug and installs the updated build via ADB.
    • Re-executes the test loop on hardware and confirms that get_logcat reports zero permission errors. For a comprehensive overview of building automated testing pipelines, read our guide to autonomous mobile app testing with Claude Code.

The following technical benchmark table outlines the diagnostic tools provided by ScreenSync MCP for validating Android file sharing workflows:

ScreenSync MCP Tool Underlying Platform API Diagnostic Data Captured Execution Latency Primary FileProvider QA Purpose
get_ui_hierarchy Accessibility Node Provider System Chooser hierarchy, file titles, app icons 110–240 ms Validating share sheet UI components
get_latest_screenshot Native MediaProjection API Hardware compositor display frame 80–110 ms Verifying file preview rendering & thumbnails
get_logcat ADB Logcat Stream (logcat -d) SecurityException, FileUriExposedException, binder grants 70–180 ms Catching URI permission denials in real time
control_tap ADB Shell Input (input tap x y) Coordinate touch injection 45–90 ms Tapping export triggers & chooser targets
control_launch_app Activity Manager (am start) Process initialization status 150–320 ms Launching test harnesses & recipient apps
record_screen Android Screenrecord (screenrecord) High-resolution MP4 video buffer Configurable (1–15 s) Archiving end-to-end share flows for QA

Production Best Practices: Hardening Inter-App Data Handoffs in CI/CD Pipelines

Production best practices for automated FileProvider testing require maintaining local network isolation, securing private cache directories, and enforcing strict path mapping hygiene. Adhering to these engineering standards ensures that automated file sharing audits remain secure, reliable, and compliant with enterprise privacy guidelines.

When integrating autonomous AI agents into enterprise continuous integration and deployment pipelines, teams must establish robust guardrails around data privacy, device sanitization, and filesystem cleanup:

Local LAN Isolation vs Cloud Relays

A fundamental architectural guarantee of ScreenSync MCP is local data containment. All real-time MediaProjection display frames and ADB command buffers stream strictly across your local network between your Android hardware and your workstation hub. No screen pixels, file payloads, touch event streams, or device serial numbers are ever routed through EpsolDev servers.

However, engineering teams must recognize the data boundary when interacting with AI model providers:

  • Synthetic Test Documents: When Claude Code invokes get_latest_screenshot to verify a file preview, that specific visual frame is transmitted across the stdio transport to the AI model provider (e.g., Anthropic). Always ensure that test invoices, medical records, or user documents utilize synthetic dummy data rather than live production customer records.
  • Sanitizing Logcat Buffers: System logcat buffers occasionally capture query strings or file names. ScreenSync MCP allows filtering via the grep argument in get_logcat, ensuring only relevant exception tags (e.g., FileProvider, SecurityException, ActivityManager) are retrieved.
  • Verifying Cryptographic Storage: For applications handling encrypted file payloads on disk, combine your FileProvider validation with our deep dive on testing Android Keystore security with Claude Code and MCP.

FileProvider Pre-Release Verification Checklist

Before releasing an Android update to Google Play, verify your file sharing implementation against this production readiness checklist:

  • [ ] Eliminate Raw File URIs: Verify that zero instances of Uri.fromFile(file) are passed across Intent boundaries, preventing FileUriExposedException.
  • [ ] Provider Export Configuration: Ensure android:exported="false" is strictly declared on the <provider> element in AndroidManifest.xml to prevent unauthorized external access.
  • [ ] Grant Permissions Flag: Ensure android:grantUriPermissions="true" is declared on the <provider> element to permit runtime binder grants.
  • [ ] Granular Path Scoping: Avoid broad root declarations like <root-path path="." />. Scope directories tightly using <cache-path> or <files-path> with specific subdirectories.
  • [ ] Mandatory Intent Flags: Confirm that Intent.FLAG_GRANT_READ_URI_PERMISSION is attached to all ACTION_SEND and ACTION_VIEW intents.
  • [ ] ClipData Propagation: Explicitly assign intent.clipData = ClipData.newRawUri(label, contentUri) to guarantee reliable grant forwarding across Android 10+ system choosers.
  • [ ] Automated Cache Cleanup: Implement lifecycle hooks or WorkManager tasks to delete temporary export files from context.cacheDir after sharing completes, preventing disk bloat.

Conclusion

Validating Android FileProvider and secure inter-process file sharing with Claude Code and ScreenSync MCP eliminates the hidden permission bugs and runtime crashes that have long challenged mobile development teams. By combining hardware-accelerated MediaProjection screen perception with deterministic ADB control and real-time logcat telemetry, developers empower autonomous AI coding agents to stress-test intent handoffs, verify system share sheet rendering, and refactor leaking code on physical devices. For applications handling complex foreground tasks and large file generation, teams can further validate execution reliability by reviewing our guide on testing Android Foreground Services with Claude Code and MCP. To understand how AI agents leverage Model Context Protocol servers for complete mobile system automation, discover what an Android screen MCP server is. Additionally, to detect main thread bottlenecks during large file I/O operations, explore our comprehensive guide on testing Android StrictMode and ANR detection with Claude Code and MCP.

ScreenSync MCP provides developer tools including the ScreenSync MCP Android app, ScreenSync MCP desktop hub, and ScreenSync MCP browser extension to engineering teams worldwide. To accelerate your Android testing and performance workflows, install the free mobile application on Google Play (com.screensync.mcp). For technical inquiries or architecture support, contact [email protected] or visit screensyncmcp.tech.

FAQ

Questions, answered

Can Claude Code automatically test Android FileProvider file sharing on physical devices?

Claude Code tests Android FileProvider sharing on physical devices using ScreenSync MCP. The server streams real-time MediaProjection screen frames and ADB telemetry over stdio, allowing Claude Code to launch export flows, parse system share sheets via accessibility node trees, verify file preview rendering, and detect binder permission denials.

Why does Android throw FileUriExposedException when sharing files between apps?

Android throws FileUriExposedException on Android 7.0 and higher when an application exposes a raw file:// URI to another app. To enforce Linux user sandbox isolation, Android requires encapsulating private disk files behind content:// URIs using androidx.core.content.FileProvider with explicit, temporary binder permission grants.

What causes SecurityException: Permission Denial when a recipient app opens a shared file?

A SecurityException: Permission Denial occurs when the originating application fails to attach Intent.FLAG_GRANT_READ_URI_PERMISSION to the outgoing Intent. Without this flag, Android's ActivityManagerService does not create an ephemeral binder grant token, preventing the recipient application from resolving the content URI.

Why is ClipData required for FileProvider sharing in Android 10 and above?

ClipData is required in Android 10 and newer because Android's Intent.createChooser() architecture forwards URI permissions to ChooserActivity and target apps via the ClipData container. Omitting intent.clipData = ClipData.newRawUri(...) can cause third-party recipient apps to lose the temporary read grant.

Does ScreenSync MCP require root privileges to inspect the Android system share sheet?

ScreenSync MCP requires zero root privileges on Android devices. Screen capture runs natively via Android's MediaProjection API with runtime user authorization, while device interaction and share sheet inspection operate through standard Android Debug Bridge (ADB) protocols via USB or authenticated wireless debugging.

How does Claude Code detect missing storage roots in res/xml/file_paths.xml?

Claude Code detects missing storage roots by querying get_logcat after triggering a file export. If an unmapped directory is accessed, Android throws an IllegalArgumentException detailing the missing root path. Claude Code parses this trace and edits res/xml/file_paths.xml to add the corresponding path declaration.

Which Model Context Protocol clients support ScreenSync MCP for Android testing?

ScreenSync MCP supports any Model Context Protocol client operating over local standard input/output (stdio), including Claude Code, Claude Desktop, Cursor, and VS Code in agent mode. Browser-based AI interfaces like ChatGPT cannot connect directly because web clients require remote HTTPS relays rather than local stdio processes.

How many total MCP tools does ScreenSync MCP provide across mobile and browser environments?

ScreenSync MCP provides 226 total MCP tools across mobile and desktop environments. This suite includes 29 phone and desktop tools—comprising 12 control tools, 3 operating system tools, and 14 capture and telemetry tools—paired with 197 browser automation tools provided by the ScreenSync Manifest V3 extension.

Written by

ScreenSync MCP team

The ScreenSync MCP team at EpsolDev builds the Android app, the desktop MCP hub and the browser extension that let AI agents see and control a real phone. These guides come out of that work.