ScreenSync MCP guide

Testing Android Keystore Security with Claude Code and MCP

Test Android Keystore cryptography, EncryptedSharedPreferences, hardware TEE keys, and biometric authentication fallbacks on real devices with Claude Code and ScreenSync MCP.

Testing Android Keystore Security with Claude Code and MCP

Testing hardware-backed cryptographic operations and secure secret storage on Android has historically been one of the most fraught challenges in mobile quality engineering. While software-level unit tests can easily verify that an AES cipher encodes and decodes sample byte arrays in memory, validating real hardware security guarantees requires running on physical silicon. The Android Keystore system does not operate like a conventional desktop software keychain; it delegates cryptographic key generation, asymmetric signing, and symmetric payload decryption directly to dedicated hardware modules such as ARM TrustZone Trusted Execution Environments (TEE) and discrete StrongBox Keymaster secure elements. When testing how mobile applications handle cryptographic edge cases—such as sudden key invalidations after biometric enrollment changes, hardware-enforced authentication timeouts, or EncryptedSharedPreferences corruption—traditional headless JVM tests fail silently because synthetic mocks cannot replicate real hardware security boundaries. The Model Context Protocol (MCP) radically transforms this testing landscape. By connecting autonomous terminal-based AI coding agents like Claude Code, Cursor, and VS Code directly to physical Android devices via ScreenSync MCP, engineering teams can turn their coding assistants into proactive security QA specialists capable of exercising cryptographic workflows, inspecting accessibility hierarchies, and diagnosing system Keymaster events in real time on real devices.

Key Takeaways

  • Hardware-Isolated Cryptography: ScreenSync MCP bridges Claude Code to physical Android devices equipped with ARM TrustZone Trusted Execution Environments (TEE) and dedicated StrongBox Keymaster security chips, enabling deterministic validation of non-exportable hardware keys.
  • Non-Invasive Visual Verification: Mobile display frames stream through Android's native MediaProjection API directly to the local desktop hub without requiring device root privileges or ADB screen-capture latency, delivering a median visual mirror latency of approximately 94 ms over local Wi-Fi.
  • Deterministic Hardware Input: Low-level touch, swipe, keyboard input, and intent dispatches execute reliably via Android Debug Bridge (ADB) over USB or authenticated wireless debugging, bypassing sandboxed view restrictions.
  • Cryptographic Invalidation Triage: The AI agent monitors system-level Keymaster, Keystore, and Gatekeeper daemon events in real time using get_logcat, diagnosing KeyPermanentlyInvalidatedException errors and verifying automated secret re-encryption workflows.
  • Dual-Layer Hierarchy and Vision Inspection: Claude Code resolves UI ambiguities during biometric authentication and PIN entry by querying semantic nodes via get_ui_hierarchy and verifying visual layout states through get_latest_screenshot.
  • Unified Cross-Surface Workflows: When encrypted tokens or session secrets transition from native Android Keystore storage into web-based OAuth portals or cloud APIs, ScreenSync MCP bridges native mobile screens to desktop browsers across 226 total MCP tools (29 mobile/desktop tools and 197 browser tools).

Why Testing Android Keystore Security Requires Physical Silicon and Agentic AI

Testing Android Keystore security requires physical hardware because cryptographic master keys, hardware security modules, and biometric bindings cannot be accurately simulated in headless JVM environments or synthetic emulators. Physical silicon enforces hardware-backed key isolation inside Trusted Execution Environments and StrongBox chips, ensuring that encryption keys cannot be extracted even if the operating system kernel is compromised.

In standard Android application development, security architectures frequently mandate that sensitive artifacts—such as OAuth refresh tokens, payment credentials, personal health information, and database encryption master keys—must never be stored in plaintext within private app storage. The Android Keystore provider addresses this requirement by creating cryptographic keys that are mathematically bound to the device hardware. The raw key material is never exposed inside the application's process memory space. Instead, when an application invokes Cipher.init() and Cipher.doFinal(), the Android operating system marshals the ciphertext or plaintext across Binder IPC to the keystore2 system daemon, which in turn calls into the Hardware Abstraction Layer (HAL) to perform the cryptographic math inside the secure world.

When development teams attempt to automate tests for these cryptographic workflows, conventional testing strategies encounter severe limitations:

  1. The Robolectric and JVM Mocking Trap: Robolectric executes Android code inside a desktop JVM by substituting Android framework classes with software "shadows". For cryptographic APIs, Robolectric falls back to Java's default BouncyCastle or SunJCE software providers. These software fallbacks generate standard software keys stored in heap memory. They completely bypass the Android Keystore SPI, ignore hardware-backed key attestation certificates, and cannot reproduce hardware-enforced user authentication requirements. A test suite that passes flawlessly in Robolectric can catastrophically crash in production when executed against real silicon.
  2. Emulated Keymaster Discrepancies: Standard Android Virtual Devices (AVD emulators) running on x86 developer workstations utilize an emulated software Keymaster HAL implementation. While this emulated service implements the Keystore AIDL interface, it lacks physical tamper-resistance features. It cannot reproduce OEM-specific timing discrepancies, hardware thermal throttling during sustained cryptographic loops, or chip-level entropy depletion in hardware random number generators (TRNG).
  3. Complex User Presence Invalidation: Security-conscious applications routinely configure keys with .setUserAuthenticationRequired(true) and .setInvalidatedByBiometricEnrollment(true). Testing what happens when a user updates their device PIN or registers a new fingerprint requires real operating system Gatekeeper state transitions. Validating that the application catches KeyPermanentlyInvalidatedException, purges orphaned ciphertext, and prompts the user to re-authenticate without corrupting persistent storage requires full end-to-end device orchestration.

This is where agentic AI coding assistants like Claude Code introduce an entirely new dimension to mobile security engineering. Rather than writing brittle procedural test scripts that break whenever biometric dialog layout parameters change, developers can dispatch Claude Code to execute high-level security verification tasks. Claude Code analyzes the application source code in your local repository, identifies which composables or activities interact with the cryptographic subsystem, executes the application build, deploys it to a physical Android device, and monitors hardware responses in real time. To understand how giving language models programmatic screen access enables autonomous device verification, review our architectural guide on how to give an AI agent a screen using MCP.

Architectural Pipeline: Decoupling Display Perception from Hardware-Backed Control

ScreenSync MCP decouples visual display perception from deterministic device control by streaming hardware-accelerated graphics frames through Android's native MediaProjection API while routing input commands through Android Debug Bridge. This architecture delivers sub-100 millisecond frame latency without requiring device root privileges, allowing AI agents to inspect cryptographic UI dialogs and dispatch authenticated interactions seamlessly.

Understanding how ScreenSync MCP operates requires analyzing its bifurcated communication architecture. Mobile security testing imposes strict performance and security constraints. If an automation framework attempts to capture display frames by repeatedly executing adb exec-out screencap -p over a USB or TCP connection, the system incurs massive overhead—often consuming between 800 ms and 2500 ms per captured frame. In an interactive AI agent loop where Claude Code must evaluate screen state after entering each digit of an authentication PIN or responding to a biometric prompt, such latency turns a routine 10-second security check into an unbearable multi-minute ordeal.

+-----------------------------------------------------------------------------------+
|                         LOCAL DESKTOP WORKSTATION                                 |
|                                                                                   |
|  +--------------------+         stdio JSON-RPC        +------------------------+  |
|  |    Claude Code     | <===========================> |     ScreenSync MCP     |  |
|  |   (CLI / Cursor)   |                               |       Desktop Hub      |  |
|  +--------------------+                               |      (Port 3000)       |  |
+-------------------------------------------------------+---------------------------+
                                                                     |
                                      +------------------------------+
                                      |
             Local Wi-Fi / LAN        |        ADB Daemon (USB / Wireless)
            MediaProjection Stream    |        Deterministic Input & Logs
           (Sub-100ms Screen Frames)  |       (control_tap, get_logcat)
                                      v                      v
             +-------------------------------------------------------+
             |                 PHYSICAL ANDROID DEVICE               |
             |                                                       |
             |   +-----------------------------------------------+   |
             |   |        ScreenSync MCP (com.screensync.mcp)    |   |
             |   |      MediaProjection Service (No Root/No ADB) |   |
             |   +-----------------------------------------------+   |
             |   |            Target Android Application         |   |
             |   |    KeyGenParameterSpec -> AndroidKeyStore     |   |
             |   +-----------------------------------------------+   |
             |   |        Hardware Security Modules (TEE/StrongBox)  |
             |   +-----------------------------------------------+   |
             +-------------------------------------------------------+

ScreenSync MCP resolves this bottleneck through a clean separation of concerns:

  • Hardware-Accelerated Frame Capture via MediaProjection: The ScreenSync MCP companion application (package com.screensync.mcp, compatible with Android 7.0 and later) runs directly on the test device. Upon user consent during initial pairing, the app uses Android's native MediaProjection API to capture display buffers straight from the hardware graphics pipeline. The application encodes these frames and streams them over the local area network (LAN) to the desktop hub running on Node.js 18+. In real-world local Wi-Fi benchmarks, this direct pipeline consistently achieves a median visual mirror latency of approximately 94 ms. Crucially, MediaProjection requires no device root access and consumes zero ADB bandwidth.
  • Deterministic Input Injection via ADB: While frame capture runs over high-speed local sockets, input control requires elevated system capabilities to interact with system dialogs such as the Android BiometricPrompt, PIN keyguards, and permission dialogs. ScreenSync MCP dispatches commands like control_tap, control_type, and control_launch_app through the local ADB daemon over USB or authenticated wireless debugging. This dual-path architecture ensures that sensitive cryptographic screens are observed with ultra-low latency while touch interactions execute with pinpoint precision. For an exhaustive analysis of display transmission mechanics across Android MCP architectures, read our technical breakdown on how screen MCP servers capture mobile displays. To configure cable-free developer testing environments, review our tutorial on Android wireless debugging for MCP servers.
Cryptographic Storage Architecture Security Boundary Key Extraction Risk Cryptographic Hardware Module Biometric Binding (setUserAuth) Production Suitability
StrongBox Keymaster (Hardware) Dedicated Security Chip (SE) Near Zero (Physical tamper resistance) Dedicated Microcontroller + TRNG Hardware-enforced (Gatekeeper / TEE) Mission-critical fintech, banking, auth tokens
TEE Keystore (TrustZone) Isolated CPU execution domain Low (Requires hypervisor exploit) ARM TrustZone / Secure World Hardware-enforced (TEE HAL) High-security enterprise apps, passkeys
Software Keystore (Software Fallback) Android OS Linux Kernel Sandbox Moderate (Vulnerable to kernel root/exploit) Software crypto library (BoringSSL) Software-emulated auth checks Deprecated / low-tier devices without TEE
EncryptedSharedPreferences (Jetpack) Hardware MasterKey + Sandboxed XML Low (When backed by AndroidKeyStore) TEE or StrongBox for MasterKey Supported via MasterKey specs Standard app preferences, cached tokens
Raw SharedPreferences / SQLite Application Sandbox UID only High (Readable on rooted devices or backup) None (Plaintext filesystem storage) None Non-sensitive UI state only

Core Cryptographic Architecture: KeyGenParameterSpec, MasterKey, and EncryptedSharedPreferences

Android Keystore cryptographic architecture relies on KeyGenParameterSpec and Jetpack Security's MasterKey to generate AES-256 GCM encryption keys inside secure hardware. Configuring parameters such as setUserAuthenticationRequired(true) and setInvalidatedByBiometricEnrollment(true) binds cryptographic operations to valid user presence, ensuring keys permanently invalidate if biometric credentials or device locks change.

To architect secure local storage on modern Android devices, engineering teams utilize Google's Jetpack Security library (androidx.security.crypto) in conjunction with low-level AndroidKeyStore APIs. At the foundation of this architecture is the MasterKey, which resides strictly inside hardware-backed storage. The MasterKey is responsible for encrypting sub-keys or wrapping data encryption keys (DEK) used to secure files and preference files.

When configuring key generation specifications, developers must tune hardware properties using KeyGenParameterSpec.Builder:

package com.screensync.security.crypto

import android.content.Context
import android.content.SharedPreferences
import android.os.Build
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyPermanentlyInvalidatedException
import android.security.keystore.KeyProperties
import android.util.Log
import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKey
import java.security.KeyStore
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec

class SecureKeystoreManager(private val context: Context) {

    companion object {
        private const val TAG = "SecureKeystoreManager"
        private const val ANDROID_KEYSTORE_PROVIDER = "AndroidKeyStore"
        private const val MASTER_KEY_ALIAS = "com.screensync.security.master_vault_key"
        private const val PREFS_FILE_NAME = "secure_device_vault_prefs"
        private const val AES_GCM_TRANSFORMATION = "AES/GCM/NoPadding"
        private const val GCM_TAG_LENGTH_BITS = 128
    }

    private val keyStore: KeyStore = KeyStore.getInstance(ANDROID_KEYSTORE_PROVIDER).apply {
        load(null)
    }

    /**
     * Initializes or retrieves the hardware-backed MasterKey using Jetpack Security.
     * Enforces StrongBox Keymaster backing when available on hardware.
     */
    fun getOrCreateMasterKey(requireBiometricAuth: Boolean = false): MasterKey {
        val specBuilder = KeyGenParameterSpec.Builder(
            MASTER_KEY_ALIAS,
            KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
        ).apply {
            setBlockModes(KeyProperties.BLOCK_MODE_GCM)
            setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
            setKeySize(256)

            if (requireBiometricAuth) {
                setUserAuthenticationRequired(true)
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    setUserAuthenticationParameters(
                        15, // Valid for 15 seconds after authentication
                        KeyProperties.AUTH_BIOMETRIC_STRONG or KeyProperties.AUTH_DEVICE_CREDENTIAL
                    )
                }
                setInvalidatedByBiometricEnrollment(true)
            }

            // Prefer StrongBox discrete security chip if present on silicon
            if (context.packageManager.hasSystemFeature("android.hardware.strongbox_keystore")) {
                setIsStrongBoxBacked(true)
            }
        }

        return MasterKey.Builder(context, MASTER_KEY_ALIAS)
            .setKeyGenParameterSpec(specBuilder.build())
            .build()
    }

    /**
     * Instantiates EncryptedSharedPreferences backed by the hardware MasterKey.
     * Catches cryptographic invalidation and recovers gracefully.
     */
    fun getEncryptedPreferences(): SharedPreferences {
        return try {
            val masterKey = getOrCreateMasterKey(requireBiometricAuth = false)
            EncryptedSharedPreferences.create(
                context,
                PREFS_FILE_NAME,
                masterKey,
                EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
                EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
            )
        } catch (e: Exception) {
            Log.w(TAG, "EncryptedSharedPreferences initialization failed: ${e.message}. Purging corrupted vault.")
            purgeInvalidatedVault()
            val freshMasterKey = getOrCreateMasterKey(requireBiometricAuth = false)
            EncryptedSharedPreferences.create(
                context,
                PREFS_FILE_NAME,
                freshMasterKey,
                EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
                EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
            )
        }
    }

    /**
     * Encrypts arbitrary binary payload using raw AndroidKeyStore AES-256 GCM cipher.
     */
    fun encryptPayload(plaintext: ByteArray): Pair<ByteArray, ByteArray> {
        val secretKey = getOrCreateRawSecretKey()
        val cipher = Cipher.getInstance(AES_GCM_TRANSFORMATION)
        cipher.init(Cipher.ENCRYPT_MODE, secretKey)
        val iv = cipher.iv
        val ciphertext = cipher.doFinal(plaintext)
        return Pair(iv, ciphertext)
    }

    /**
     * Decrypts binary payload, catching hardware invalidation exceptions.
     */
    fun decryptPayload(iv: ByteArray, ciphertext: ByteArray): ByteArray {
        val secretKey = getOrCreateRawSecretKey()
        val cipher = Cipher.getInstance(AES_GCM_TRANSFORMATION)
        val spec = GCMParameterSpec(GCM_TAG_LENGTH_BITS, iv)

        return try {
            cipher.init(Cipher.DECRYPT_MODE, secretKey, spec)
            cipher.doFinal(ciphertext)
        } catch (e: KeyPermanentlyInvalidatedException) {
            Log.e(TAG, "CRITICAL: Key permanently invalidated by security module: ${e.message}")
            keyStore.deleteEntry(MASTER_KEY_ALIAS)
            throw e
        }
    }

    private fun getOrCreateRawSecretKey(): SecretKey {
        if (!keyStore.containsAlias(MASTER_KEY_ALIAS)) {
            val keyGenerator = KeyGenerator.getInstance(
                KeyProperties.KEY_ALGORITHM_AES,
                ANDROID_KEYSTORE_PROVIDER
            )
            val spec = KeyGenParameterSpec.Builder(
                MASTER_KEY_ALIAS,
                KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
            )
                .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
                .setKeySize(256)
                .setRandomizedEncryptionRequired(true)
                .build()

            keyGenerator.init(spec)
            keyGenerator.generateKey()
        }
        return (keyStore.getEntry(MASTER_KEY_ALIAS, null) as KeyStore.SecretKeyEntry).secretKey
    }

    private fun purgeInvalidatedVault() {
        try {
            if (keyStore.containsAlias(MASTER_KEY_ALIAS)) {
                keyStore.deleteEntry(MASTER_KEY_ALIAS)
            }
            context.getSharedPreferences(PREFS_FILE_NAME, Context.MODE_PRIVATE).edit().clear().commit()
            Log.i(TAG, "Successfully purged invalidated MasterKey and cleartext shared preference backing.")
        } catch (e: Exception) {
            Log.e(TAG, "Failed to purge vault: ${e.message}")
        }
    }
}

In the architecture above, notice the critical handling of KeyPermanentlyInvalidatedException. When an application marks a key as invalidated by biometric enrollment, any subsequent modification of the device's enrolled fingerprints or lock screen credentials causes Android's Gatekeeper daemon to mark the cryptographic key state as revoked within the hardware module. When an agent like Claude Code tests this application, it must verify that the app does not enter an unrecoverable crash loop when accessing corrupted preferences. For additional security testing patterns across device authentication, see our dedicated guide on testing Android biometrics with Claude Code and MCP. When working with sandboxed app files, pair this architecture with our guide on testing Android scoped storage with Claude Code and MCP and SQLite encryption validation in testing Android Room database migrations with Claude Code and MCP.

Step-by-Step Configuration: Setting Up Claude Code with ScreenSync MCP

Configuring Claude Code with ScreenSync MCP requires launching the desktop hub on Node.js 18+, registering the stdio server path in the Claude Code command-line interface, installing the free Android application from Google Play, and pairing over local Wi-Fi. This establishes a private, local-first bridge capable of inspecting Android screens and dispatching testing commands.

Step 1: Verify Hardware and Workstation Prerequisites

Before initiating the connection, verify that your test environment satisfies the following baseline requirements:

  1. Host Workstation: Windows 10/11, macOS, or Linux with Node.js 18 or newer installed and accessible on your environment PATH.
  2. Physical Android Device: A physical Android smartphone or tablet running Android 7.0 (Nougat, API 24) or newer. The device should feature hardware-backed Keystore capabilities (standard TEE or StrongBox).
  3. Android Platform Tools: Android Debug Bridge (adb) installed and configured in your workstation shell.
  4. Local Subnet Connectivity: Your workstation and Android device must be connected to the same local Wi-Fi network to enable high-throughput MediaProjection frame streaming and mDNS auto-discovery.

Step 2: Extract and Launch the ScreenSync MCP Desktop Hub

Download the ScreenSync MCP desktop hub package from screensyncmcp.tech. Unpack the hub archive into a dedicated directory on your computer, such as C: ools\screensync-hub on Windows or ~/tools/screensync-hub on macOS and Linux.

Start the desktop hub using the included shell 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

Upon launching, the desktop hub starts a local HTTP server on port 3000 to ingest mobile video streams and exposes standard Model Context Protocol endpoints over stdio. The console output displays your session authentication bearer token (SCREEN_SYNC_TOKEN) and renders an ASCII QR code for fast mobile pairing.

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

To connect Claude Code CLI to ScreenSync MCP, open your terminal and register the server using the native MCP 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, located via Settings > Developer > Edit Config) and add the server definition:

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

Note: The ChatGPT web client relies exclusively on remote HTTPS-based MCP endpoints and cannot interface with local stdio servers. ScreenSync MCP is engineered specifically for local developer environments including Claude Desktop, Claude Code, Cursor, and VS Code.

Step 4: Install the Android App and Pair the Device

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

  1. Launch the ScreenSync MCP application on your phone.
  2. The application automatically discovers your running desktop hub via mDNS. If your router blocks multicast traffic, tap the QR scanner icon inside the mobile app and scan the QR code rendered in your workstation terminal.
  3. Tap Start Projection. Android displays a system security prompt asking for permission to capture the screen via MediaProjection. Tap Start Now.
  4. Enable Developer Options on your phone (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 cable or configure wireless pairing by following our comprehensive guide on Android wireless debugging for MCP servers. Verify that your device is recognized by running adb devices in your terminal. For complete setup troubleshooting, consult the official ScreenSync MCP setup guide and our directory of Android MCP servers.

Autonomous Agent QA Workflows: Triage Key Invalidation, Hardware Timeouts, and Logcat

Autonomous agent QA workflows with Claude Code execute end-to-end cryptographic verifications on physical Android hardware. Claude Code navigates security setup screens, handles biometric authentication prompts, triggers key invalidation events through credential resets, and reads system Logcat output in real time to triage Keymaster and Gatekeeper exceptions.

Workflow 1: End-to-End Cryptographic Secret Storage and Vault Unlock

In this scenario, an engineering team must verify that their banking application correctly initializes an AES-256 GCM key inside the Android Keystore, encrypts a sensitive authentication bearer token, and requires valid device authentication before displaying the decrypted token on screen.

Developer Prompt:
"Claude, launch our banking application build, navigate to the Secure Vault screen, generate a new hardware-backed encryption key, input the test secret 'API_SECRET_KEY_9921' into the vault, lock the screen, unlock via PIN entry, and verify that the decrypted secret renders properly without leaking into accessibility node attributes."

Upon receiving this instruction, Claude Code initiates a structured series of MCP tool calls:

{
  "name": "control_launch_app",
  "arguments": {
    "packageName": "com.screensync.security.vault",
    "activity": "com.screensync.security.vault.MainActivity"
  }
}

Once the application activity loads, Claude Code queries the structural accessibility tree to locate the interactive elements:

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

The returned accessibility tree reveals an input text field with resource-id="com.screensync.security.vault:id/input_secret_token" located at coordinates [120, 680, 960, 800]. Claude Code focuses the field and inputs the sensitive token:

{
  "name": "control_tap",
  "arguments": {
    "x": 540,
    "y": 740
  }
}
{
  "name": "control_type",
  "arguments": {
    "text": "API_SECRET_KEY_9921"
  }
}

Next, Claude Code taps btn_save_and_encrypt. To verify that the cryptographic key was properly generated and the data was stored inside EncryptedSharedPreferences, Claude Code locks the vault by tapping btn_lock_vault, which triggers the app's BiometricPrompt dialog.

Claude Code checks the active screen hierarchy:

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

The node inspector identifies the system dialog com.android.systemui:id/biometric_prompt. Claude Code enters the fallback device PIN using control_type, taps confirm, and queries get_ui_hierarchy again.

Crucial Security Verification: Claude Code inspects all text fields in the decrypted view hierarchy. It verifies that while the decrypted string API_SECRET_KEY_9921 is rendered visually on screen (confirmed by calling get_latest_screenshot), the view has been marked with android:importantForAccessibility="no" or masked with password transformation methods, ensuring that third-party accessibility scrapers cannot harvest sensitive cryptographic secrets. For an in-depth breakdown of how accessibility node parsing compares to raw visual evaluation, see Android UI hierarchy vs computer vision: why LLMs need structural node trees to prevent drift.

Workflow 2: Triaging KeyPermanentlyInvalidatedException via System Logcat

One of the most catastrophic bugs in mobile security engineering occurs when an application fails to handle KeyPermanentlyInvalidatedException. When a user updates their device lock screen pattern or registers a new fingerprint, Android's Keymaster permanently revokes access to keys created with setInvalidatedByBiometricEnrollment(true). If the app does not catch this exception, attempts to initialize the decryption cipher crash the process immediately upon startup.

Developer Prompt:
"Simulate a cryptographic key invalidation event on the connected phone by resetting device credentials. Open our application, attempt to read the secure vault, and inspect logcat to verify that the app gracefully purges the revoked key and prompts for re-enrollment instead of crashing."

Claude Code triggers the credential update, then opens the application and calls get_logcat:

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

The MCP tool streams the latest 150 lines from the ADB log buffer. Claude Code triages the Keymaster and Keystore daemon outputs:

W KeyStore: Keymaster operation failed: -26 (KM_ERROR_KEY_PERMANENTLY_INVALIDATED)
E AndroidKeyStore: Failed to initialize cipher: android.security.keystore.KeyPermanentlyInvalidatedException: Key permanently invalidated
W SecureKeystoreManager: Caught KeyPermanentlyInvalidatedException. Purging invalidated MasterKey and re-authenticating user.
I SecureKeystoreManager: Successfully purged invalidated MasterKey and cleartext shared preference backing.
I ActivityTaskManager: Displayed com.screensync.security.vault/.ReEnrollmentActivity: +210ms

Claude Code confirms from the logcat stream that:

  1. Keymaster threw hardware error code -26 (KM_ERROR_KEY_PERMANENTLY_INVALIDATED).
  2. The application's SecureKeystoreManager caught the exception cleanly.
  3. The app purged the dead key entry via keyStore.deleteEntry().
  4. The user was transitioned to ReEnrollmentActivity without an unhandled crash or ANR dialog.

To explore how AI agents structure comprehensive testing scripts, see our guide on autonomous mobile app testing with Claude Code. For an exhaustive reference of all 29 mobile tools, explore our complete Android MCP tool reference deep dive. To verify state survival when the operating system abruptly reclaims memory, see our tutorial on testing Android process death with Claude Code and MCP.

Cryptographic QA Action MCP Tool Executed Underlying Android OS / Hardware API Typical Latency Range Expected Verification Output
Inspect Auth Dialog get_ui_hierarchy AccessibilityNodeProvider (BiometricPrompt) 110–250 ms Structural node bounds for PIN/Fingerprint UI
Capture Auth Screen get_latest_screenshot MediaProjection Buffer 80–110 ms Base64 visual verification of prompt status
Enter Device PIN control_type ADB Shell Input Keyevent 60–140 ms Keystroke echo to secure input field
Tap Authenticate Button control_tap ADB Shell Input Tap 45–90 ms Execution confirmation & coordinate hit
Triage Keymaster Logcat get_logcat ADB Logcat Pipe (grep -E "KeyStore|Keymaster") 85–210 ms Filtered plaintext log buffer with error codes
Record Crypto Test Run record_screen MediaProjection Video Stream Configurable (1–15 s) MP4 video artifact of authentication flow
Trigger Background Lock control_launch_app ActivityManager / Intent Dispatch 120–280 ms Lifecycle transition to onStop / lock state
Validate Fallback Intent control_open_url Android Intent Resolver 100–240 ms Verification of deep link auth redirection

Cross-Surface Security Verification: Validating Token Exchanges Across Native and Browser Portals

Cross-surface security verification tests the integrity of authentication tokens as user workflows move between native Android apps and web browsers. ScreenSync MCP unifies 29 mobile tools and 197 browser tools under a single server, enabling Claude Code to validate OAuth2 redirects, PKCE exchanges, and encrypted session cookies end to end.

In modern enterprise architectures, mobile applications rarely isolate their cryptographic keys completely from web infrastructure. Common real-world architectures require bridging native Keystore secrets with browser-based surfaces:

  1. OAuth2 Authorization Code with PKCE: When an Android application authenticates a user, it generates a cryptographically random code verifier inside the Android Keystore, computes the SHA-256 code challenge, and opens a Chrome Custom Tab to authenticate the user against an enterprise identity provider (such as Okta or Auth0). Once the web authentication succeeds, the browser redirects back to the native app via an Android App Link, where the native app exchanges the code verifier for an encrypted refresh token.
  2. WebAuthn and Passkey Synchronization: Applications increasingly integrate FIDO2 WebAuthn credentials that bridge native mobile biometric authentication with cloud authentication servers. Testing how passkeys sync across native apps and Chrome tabs requires cross-surface agent control. To review passkey testing patterns, see our guide on testing Android passkeys with Claude Code and MCP.
  3. Third-Party Payment Handoffs: Mobile commerce checkouts often originate in native Android composables before handing off to Stripe or Google Pay webviews. Validating that session tokens are not intercepted during this transition is critical. For payment testing flows, see our guide on end-to-end mobile payment testing with AI. For validating hardware-level contactless cards and smart chip protocols, explore our guide on testing Android NFC and HCE with Claude Code and MCP.

Traditional mobile testing tools like Appium or Espresso cannot span this boundary; Appium requires switching driver sessions between mobile and browser, often causing session drops and timing timeouts.

ScreenSync MCP solves this challenge by packaging 226 total MCP tools under a single unified server instance. Alongside the 29 phone and desktop tools, ScreenSync MCP integrates a Manifest V3 browser extension for Google Chrome and Microsoft Edge that exposes 197 web_* browser automation tools.

When a native Android application launches an external OAuth authentication flow, Claude Code uses control_tap on the mobile device to initiate the request. As the browser opens on your desktop workstation or test browser, Claude Code seamlessly transitions to the browser toolset:

{
  "name": "web_navigate",
  "arguments": {
    "url": "https://auth.enterprise-vault.com/login?client_id=screensync_mobile&code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
  }
}

The agent uses web_fill to enter test staging credentials, clicks authenticate via web_click, and verifies that the browser issues a redirect to app://oauth2/callback?code=AUTH_CODE_7719. Once Android catches the deep link and regains foreground focus on the physical phone, Claude Code switches back to get_logcat and get_latest_screenshot to confirm that the native app stored the returned session token inside EncryptedSharedPreferences.

To ensure total safety during cross-surface execution, the ScreenSync MCP browser extension includes a built-in human approval prompt for sensitive operations, ensuring that AI agents cannot execute unintended financial or administrative actions without developer confirmation. Learn more about extension capabilities on our extension overview page.

Production Hardening Best Practices for Mobile Cryptography QA Pipelines

Hardening mobile cryptographic testing pipelines requires enforcing local network boundaries, isolating cryptographic test credentials, and utilizing dedicated physical hardware. By streaming MediaProjection frames locally and avoiding cloud relays, development teams ensure that proprietary encryption keys, certificates, and authentication tokens never leave the secure corporate intranet.

When integrating autonomous AI coding assistants into mobile security testing pipelines, teams must implement rigorous operational safeguards:

1. Local Network Data Sovereignty vs Cloud Relays

One of the most dangerous vulnerabilities in mobile automation is routing screen frames, accessibility dumps, and device telemetry through third-party cloud device farms. Mobile screens during security testing inevitably display sensitive staging tokens, private employee emails, and biometric prompt metadata.

ScreenSync MCP enforces strict local data sovereignty:

  • Display frames stream directly from the Android phone to the desktop hub over your local Wi-Fi or USB connection. Frames are never uploaded to EpsolDev servers or external hosting providers.
  • Device control commands execute locally over ADB without intermediate cloud proxies.
  • The only data sent to external AI providers (such as Anthropic for Claude Code) are the discrete screenshots and structural node trees explicitly requested by the AI agent during turn-by-turn reasoning.

2. Dedicated Physical Testbed Silicon

Never rely on synthetic emulators or rooted test devices for cryptographic release gating:

  • Emulators frequently utilize software-emulated key stores that fail to catch hardware timing leaks or Keymaster race conditions.
  • Rooted devices compromise Android's verified boot chain (dm-verity) and tamper with hardware Keymaster attestation, creating false positives or masking real security failures.
  • Maintain dedicated physical test devices running clean, unrooted factory Android builds (Android 7.0 through Android 15+) with hardware TEE and StrongBox capabilities enabled.

3. Ephemeral Session Tokens and Safe Credential Management

When launching the ScreenSync MCP desktop hub, the system automatically generates an ephemeral bearer token (SCREEN_SYNC_TOKEN). Always ensure that:

  • The SCREEN_SYNC_TOKEN is passed via local environment variables or configuration files (claude_desktop_config.json) and never committed to public git repositories.
  • Test cryptographic keys use dedicated staging aliases (com.app.test_vault_key) distinct from production release keys.
  • Continuous integration scripts employ automated teardown hooks to clear test keystores and purge application data (adb shell pm clear <package>) between test runs. For runtime security guidelines, review our analysis on testing Android runtime permissions with Claude Code and MCP and offline security in testing Android offline mode and sync with Claude Code and MCP.

Conclusion & Next Steps

Validating Android Keystore security, hardware-backed master keys, and biometric authentication fallbacks no longer requires cumbersome manual testing or fragile instrumentation scripts. By unifying Anthropic's Claude Code with ScreenSync MCP's low-latency MediaProjection streaming, deterministic ADB input injection, and real-time Logcat telemetry, mobile engineering teams can establish autonomous, continuous security testing pipelines that catch hardware-level regressions before shipping to production.

Whether triaging KeyPermanentlyInvalidatedException errors after credential changes, verifying that sensitive tokens do not leak into accessibility trees, or automating cross-surface OAuth token handoffs across native apps and Chrome extensions, ScreenSync MCP provides the comprehensive tooling required for modern agentic mobile quality assurance.

Empower your mobile engineering and security testing today:

FAQ

Questions, answered

Does ScreenSync MCP require root privileges to test Android Keystore operations?

No. ScreenSync MCP uses Android's native MediaProjection API for display capture and standard Android Debug Bridge (ADB) commands for input injection. Neither requires rooting the test device, ensuring full compatibility with production hardware security modules.

How does Claude Code verify that a cryptographic key is hardware-backed?

Claude Code verifies hardware-backed keys by inspecting key properties via `KeyInfo.isInsideSecureHardware()` and checking system logcat output via `get_logcat`. The agent inspects Keymaster and TEE HAL initialization events to confirm hardware isolation.

Can Claude Code automate BiometricPrompt authentication when user authentication is required?

Yes. When `setUserAuthenticationRequired(true)` triggers a BiometricPrompt dialog, Claude Code inspects the system prompt bounds via `get_ui_hierarchy` and inputs the device PIN or password via `control_type`, confirming successful biometric authorization.

How does ScreenSync MCP handle KeyPermanentlyInvalidatedException during test runs?

When device lock credentials change, Android's Gatekeeper revokes biometric-bound keys. Claude Code monitors `get_logcat` to catch `KeyPermanentlyInvalidatedException`, confirming that the app purges invalidated keys and prompts for re-enrollment without crashing.

Why can't Android Keystore testing be conducted purely inside Robolectric or JVM unit tests?

Robolectric substitutes Android framework APIs with desktop JVM software mocks, storing keys in standard software memory. It cannot simulate hardware TEE boundaries, StrongBox Keymaster tamper resistance, or real-world biometric invalidation triggers.

Does ScreenSync MCP transmit sensitive cryptographic keys or decrypted payloads to external servers?

No. ScreenSync MCP streams display frames and control commands strictly across your local network between the mobile device and desktop hub. Raw cryptographic keys never leave the phone's secure hardware modules.

How does Claude Code triage Keymaster and Gatekeeper errors in real time?

Claude Code invokes the `get_logcat` MCP tool with targeted tag filters for `KeyStore`, `Keymaster`, and `Gatekeeper`. The agent parses low-level error codes such as `KM_ERROR_KEY_PERMANENTLY_INVALIDATED` to identify cryptographic failures.

Can ScreenSync MCP test cryptographic token exchanges between native Android apps and browsers?

Yes. ScreenSync MCP unifies 29 mobile tools with 197 browser automation tools. Claude Code can initiate an OAuth flow in a native Android app, navigate the browser login portal, and verify token handoff.

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.