ScreenSync MCP guide

Testing Android Custom Tabs and Auth Tab OAuth with Claude Code

Automate Android Auth Tab, Chrome Custom Tabs, and OAuth 2.0 PKCE redirect testing on physical devices with Claude Code and ScreenSync MCP.

3D architectural illustration of an Android smartphone displaying a glowing purple authentication padlock card linked by fiber-optic light arcs to a developer laptop showing security workflow nodes

Modern Android applications delegate OAuth 2.0 and OpenID Connect sign-in flows to external browser contexts—either through AndroidX Browser AuthTabIntent or traditional CustomTabsIntent—rather than embedding credentials inside an in-process WebView. That architectural shift satisfies RFC 8252 security guidelines and unlocks shared browser cookies, password managers, and hardware passkeys, yet it breaks conventional instrumentation tests the instant control leaves the host app process. Espresso throws NoActivityResumedException once Chrome takes foreground focus, UI Automator selectors splinter across OEM browser packages and Chrome channel variations, and emulators often lack verified Google Play services or Chrome builds capable of executing modern Auth Tab contracts. Operating over the Model Context Protocol (MCP), ScreenSync MCP gives Claude Code direct visibility and hardware control across both the native Android activity and the out-of-process browser tab. By pairing native Android MediaProjection screen capture (averaging ~94 ms median latency over LAN with zero root and zero ADB capture overhead) with ADB-driven touch gestures and Logcat telemetry, engineering teams can verify full OAuth 2.0 Proof Key for Code Exchange (PKCE) logins end to end on physical hardware.

Key Takeaways

  • Cross-Process Visibility Across Auth Boundaries: Espresso stops working when AuthTabIntent or CustomTabsIntent hands foreground focus to Chrome, whereas ScreenSync MCP inspects both native and browser surfaces through get_latest_screenshot and get_ui_hierarchy.
  • Capture vs. Control Separation: ScreenSync MCP captures live frames via Android's native MediaProjection API with no root and no ADB required, while control_tap, control_type, and control_swipe execute through ADB over USB or wireless debugging.
  • Sub-100ms Visual Loop for OAuth Redirects: With ~94 ms median local network mirroring latency, Claude Code observes Ephemeral Chrome Auth Tab renders, consent prompts, and redirect transitions in real time without adb screencap bottlenecks.
  • End-to-End PKCE & State Validation: Combine live UI interactions with get_logcat filtering (AuthTab, CustomTabs, AppAuth, IntentResolver) to assert code_challenge generation, state matching, and token exchange completion.
  • 226 Unified Mobile and Desktop Browser Tools: ScreenSync MCP exposes 29 phone and desktop tools (12 control_*, 3 os_*, and 14 capture/hub tools) plus 197 web_* browser tools through a local Node.js 18+ stdio hub.
  • Zero Cloud Relay Exposure: Device frames flow over your local network from phone to workstation hub and never touch EpsolDev servers; only screenshots explicitly requested by the AI agent are sent to that agent's model provider.

Why Android Auth Tab and Custom Tabs Break Traditional UI Automation

Android AuthTabIntent and CustomTabsIntent break Espresso and UI Automator suites because authentication executes inside a separate browser process owned by Chrome or another default browser package. Traditional instrumentation runners cannot access cross-process view hierarchies, while stubbed redirect intents skip PKCE cookie state, App Links verification, and real browser consent rendering.

To understand why OAuth testing remains one of the flakiest stages in Android CI pipelines, consider what happens inside Android's Activity Manager when an app launches an external user agent. Unlike an embedded WebView—whose DOM and WebViewClient callbacks live inside your app's UID and process boundary, as covered in our guide to testing Android WebViews and hybrid apps with Claude Code—both Chrome Custom Tabs and the newer AndroidX AuthTabIntent intentionally isolate the login session inside the user's installed browser.

This isolation enforces three security invariants defined by RFC 8252 (OAuth 2.0 for Native Apps):

  1. Credential Isolation: The host Android application never observes raw keystrokes, passwords, or third-party session cookies entered on the identity provider's login page.
  2. Shared Identity State: Users who are already signed into Google, GitHub, Okta, or Microsoft Entra ID inside Chrome can complete SSO without re-typing multi-factor codes.
  3. Hardened TLS & Anti-Phishing Chrome: The browser renders the verified origin bar, enforces Certificate Transparency, and integrates natively with Android Autofill and Credential Manager.

However, every security boundary that protects end users creates a blind spot for legacy automated test tools:

  • Espresso (onView) Process Boundary: Espresso hooks into InstrumentationRegistry inside the app-under-test process. The moment authTabIntent.launch(...) or customTabsIntent.launchUrl(...) brings com.android.chrome to the foreground, Espresso loses the resumed activity and fails with androidx.test.espresso.NoActivityResumedException.
  • Espresso-Intents Stubbing Blindness: Many teams respond by calling Intents.intending(...) to intercept the outgoing browser Intent and inject a synthetic Activity.RESULT_OK payload. While useful for fast unit-style UI tests, intent stubbing completely skips testing whether your redirect_uri scheme matches the manifest, whether Chrome actually closes on redirect, whether AssetLinks App Links resolve cleanly, and whether your identity provider's staging form breaks on mobile viewports.
  • UI Automator Selector Drift: Writing raw UiDevice selectors for Chrome UI widgets breaks across Chrome versions, Samsung Internet fallbacks, custom tabs toolbar buttons, and localized "Accept & Continue" first-run experience (FRE) dialogs.
  • Emulators Without Realistic Browser State: Headless CI emulator images frequently ship outdated WebView/Chrome APKs, lack hardware-backed Keystore attestation, or trigger bot-detection challenges when automated WebDriver frameworks attempt to drive sign-in forms.

ScreenSync MCP removes this cross-process wall. Because MediaProjection captures the composited Android display buffer at the SurfaceFlinger level and get_ui_hierarchy queries system-wide accessibility windows, Claude Code sees both your app's native Compose/View screens and Chrome's Auth Tab or Custom Tab surfaces seamlessly in one continuous loop.

Testing Approach Cross-Process Chrome Visibility Real PKCE & Redirect Verification Setup & Maintenance Overhead Resilience to Chrome UI Updates Hardware / Real Browser Fidelity
Espresso + Intents Stubbing None; mocks the browser boundary None; skips actual IdP and redirect parsing Low initial setup, high blind-spot risk High (because browser is never launched) Synthetic; misses real OAuth and cookie failures
UI Automator (Static Selectors) Partial; brittle across Chrome channels Partial; struggles with FRE dialogs and redirects High; requires hardcoded resource IDs per OEM Low; breaks on Chrome toolbar or DOM shifts Medium on emulators; fragile across OEMs
Appium UiAutomator2 + Chromedriver Requires context switching & Chromedriver sync Yes, when Chromedriver matches Chrome APK Heavy; requires Appium server and version matching Medium; breaks when Chrome updates ahead of driver High, but slow session startup and high latency
ScreenSync MCP + Claude Code Full composited screen + system accessibility tree End-to-end: PKCE URL, IdP login, redirect, token exchange Lightweight local Node.js 18+ hub + free Play app High; semantic LLM inspection adapts to UI shifts Authentic Android 7.0+ hardware and real Chrome

AuthTabIntent vs. CustomTabsIntent: AndroidX Browser Architecture

AndroidX Browser AuthTabIntent streamlines OAuth 2.0 flows by returning redirect URIs directly through an ActivityResultLauncher contract (AuthenticateUserResultContract) instead of requiring a dedicated manifest <intent-filter> receiver activity. Traditional CustomTabsIntent relies on custom URI schemes or verified App Links to route callbacks back through onNewIntent, leaving intermediate browser tasks vulnerable to backstack leaks.

Before automating OAuth flows with Claude Code, engineers should understand the architectural differences between legacy CustomTabsIntent implementations (including wrappers like AppAuth-Android) and modern AuthTabIntent introduced in androidx.browser:browser:1.9.0+.

How Legacy CustomTabsIntent OAuth Flows Work

In a classic CustomTabsIntent integration, the app builds a Custom Tab, attaches a CustomTabsSession if warm-up is configured, and launches the authorization URL. Because CustomTabsIntent is a general-purpose in-app browser sheet, it has no built-in knowledge that the session is an authentication handshake. When the identity provider finishes login and redirects to myapp://oauth/callback?code=...&state=... or https://auth.example.com/callback?...:

  1. Chrome intercepts the navigation and fires an ACTION_VIEW Intent matching the redirect URI.
  2. Android resolves your declared <intent-filter> on a RedirectReceiverActivity (often configured with launchMode="singleTask").
  3. Your RedirectReceiverActivity extracts the Uri, forwards it to your AuthActivity or ViewModel, and calls finish() so the user does not remain trapped on the Custom Tab when pressing Back.

Common failure modes in CustomTabsIntent include:

  • Orphaned Custom Tab Backstack: Pressing the Android Back button after login returns the user to the completed OAuth consent page instead of your app home screen.
  • Browser Fallback Mismatch: On devices where the user's default browser does not support Auth Tab or Custom Tabs properly, the redirect launches an external browser tab that never closes automatically.
  • Custom Scheme Hijacking: Unverified custom URI schemes (myapp://callback) can trigger disambiguation chooser dialogs if two builds (e.g., debug and staging) declare the same scheme on one phone.

How AndroidX AuthTabIntent Modernizes Native OAuth

AuthTabIntent solves these lifecycle bugs by treating authentication as a structured Activity Result contract:

  1. Your activity or composable registers AuthTabIntent.AuthenticateUserResultContract().
  2. You invoke authTabIntent.launch(launcher, authUri, redirectScheme) (for custom schemes) or pass HTTPS App Link host/path parameters for HTTPS callbacks.
  3. Chrome opens a specialized Auth Tab UI—visually stripped down without share sheets, bookmarks, or distracting address-bar chrome—and listens specifically for the registered redirect scheme or HTTPS callback.
  4. Once the IdP redirects to the matching URI, Chrome closes the Auth Tab automatically and returns Activity.RESULT_OK with the callback Uri directly in the contract callback, or AuthTabIntent.RESULT_CANCELED / error codes if the user dismissed the sheet.

Production Kotlin Implementation: AuthTabIntent with PKCE

Below is a production-ready Kotlin reference implementing RFC 7636 PKCE generation alongside AuthTabIntent and AuthenticateUserResultContract (using androidx.browser:browser:1.9.0+), including structured logging tags that Claude Code can inspect via get_logcat:

package com.example.screensync.auth

import android.app.Activity
import android.net.Uri
import android.os.Bundle
import android.util.Base64
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.browser.auth.AuthTabIntent
import androidx.browser.auth.AuthTabIntent.AuthenticateUserResultContract
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import java.security.MessageDigest
import java.security.SecureRandom

class OAuthLoginActivity : ComponentActivity() {

    companion object {
        private const val TAG = "OAuthAuthTab"
        private const val CLIENT_ID = "screensync-mobile-client"
        private const val REDIRECT_SCHEME = "com.example.screensync.auth"
        private const val REDIRECT_URI = "$REDIRECT_SCHEME://callback"
        private const val AUTH_ENDPOINT = "https://auth.staging.example.com/oauth2/authorize"
    }

    private var authStatus by mutableStateOf("Signed Out")
    private var pendingCodeVerifier: String? = null
    private var pendingState: String? = null

    private val authLauncher = registerForActivityResult(
        AuthenticateUserResultContract()
    ) { result ->
        when (result.resultCode) {
            AuthTabIntent.RESULT_OK, Activity.RESULT_OK -> {
                val callbackUri = result.resultData?.data
                handleOAuthCallback(callbackUri)
            }
            AuthTabIntent.RESULT_CANCELED, Activity.RESULT_CANCELED -> {
                Log.w(TAG, "AuthTab cancelled by user")
                authStatus = "Auth Cancelled"
            }
            else -> {
                Log.e(TAG, "AuthTab failed with resultCode=${result.resultCode}")
                authStatus = "Auth Failed (${result.resultCode})"
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MaterialTheme {
                Surface(modifier = Modifier.fillMaxSize()) {
                    Column(
                        modifier = Modifier
                            .fillMaxSize()
                            .padding(24.dp),
                        verticalArrangement = Arrangement.Center,
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        Text(
                            text = "Status: $authStatus",
                            style = MaterialTheme.typography.titleMedium
                        )
                        Spacer(modifier = Modifier.height(16.dp))
                        Button(onClick = { launchAuthTabFlow() }) {
                            Text("Sign In with OAuth")
                        }
                    }
                }
            }
        }
    }

    private fun launchAuthTabFlow() {
        val codeVerifier = generateCodeVerifier()
        val codeChallenge = generateCodeChallenge(codeVerifier)
        val state = generateRandomToken(24)

        pendingCodeVerifier = codeVerifier
        pendingState = state

        val authUri = Uri.parse(AUTH_ENDPOINT).buildUpon()
            .appendQueryParameter("response_type", "code")
            .appendQueryParameter("client_id", CLIENT_ID)
            .appendQueryParameter("redirect_uri", REDIRECT_URI)
            .appendQueryParameter("scope", "openid profile email")
            .appendQueryParameter("state", state)
            .appendQueryParameter("code_challenge", codeChallenge)
            .appendQueryParameter("code_challenge_method", "S256")
            .build()

        Log.i(TAG, "Launching AuthTabIntent state=$state challengeMethod=S256")
        authStatus = "Authorizing..."

        val authTabIntent = AuthTabIntent.Builder().build()
        authTabIntent.launch(authLauncher, authUri, REDIRECT_SCHEME)
    }

    private fun handleOAuthCallback(callbackUri: Uri?) {
        if (callbackUri == null) {
            Log.e(TAG, "Callback URI missing from AuthTab result")
            authStatus = "Error: Empty Callback"
            return
        }

        val returnedState = callbackUri.getQueryParameter("state")
        val authCode = callbackUri.getQueryParameter("code")
        val error = callbackUri.getQueryParameter("error")

        if (error != null) {
            Log.e(TAG, "IdP returned OAuth error=$error")
            authStatus = "OAuth Error: $error"
            return
        }

        if (returnedState == null || returnedState != pendingState) {
            Log.e(TAG, "CSRF state mismatch expected=$pendingState actual=$returnedState")
            authStatus = "Error: State Mismatch"
            return
        }

        if (authCode.isNullOrBlank() || pendingCodeVerifier == null) {
            Log.e(TAG, "Missing authorization code or code_verifier")
            authStatus = "Error: Missing Auth Code"
            return
        }

        Log.i(TAG, "PKCE state verified; authorization code received; starting token exchange")
        // Exchange authCode + pendingCodeVerifier at /oauth2/token on background coroutine
        authStatus = "Signed In (PKCE Verified)"
    }

    private fun generateCodeVerifier(): String = generateRandomToken(64)

    private fun generateRandomToken(byteCount: Int): String {
        val bytes = ByteArray(byteCount)
        SecureRandom().nextBytes(bytes)
        return Base64.encodeToString(bytes, Base64.URL_SAFE or Base64.NO_WRAP or Base64.NO_PADDING)
    }

    private fun generateCodeChallenge(verifier: String): String {
        val digest = MessageDigest.getInstance("SHA-256").digest(verifier.toByteArray(Charsets.US_ASCII))
        return Base64.encodeToString(digest, Base64.URL_SAFE or Base64.NO_WRAP or Base64.NO_PADDING)
    }
}

Handling Legacy CustomTabsIntent and Browser Fallback Manifests

When supporting devices whose default browser does not yet implement Auth Tab—or when testing older CustomTabsIntent codebases—developers declare an explicit RedirectReceiverActivity in AndroidManifest.xml using https App Links or a custom scheme. For App Links verification nuances (assetlinks.json, autoVerify timeouts, and intent disambiguation), see our companion guide on testing Android deep links and App Links with Claude Code.

<activity
    android:name=".auth.RedirectReceiverActivity"
    android:exported="true"
    android:launchMode="singleTask">
    <intent-filter android:autoVerify="true">
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data
            android:scheme="https"
            android:host="auth.staging.example.com"
            android:pathPrefix="/oauth2/callback" />
    </intent-filter>
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data
            android:scheme="com.example.screensync.auth"
            android:host="callback" />
    </intent-filter>
</activity>
Auth Mechanism Minimum AndroidX / Browser Requirement Redirect Delivery Path Backstack & Task Risk Primary ScreenSync MCP Verification
AuthTabIntent androidx.browser:browser:1.9.0+ and supported Chrome build AuthenticateUserResultContract returns callback Uri directly Minimal; browser closes tab automatically on scheme/HTTPS match get_ui_hierarchy across Chrome Auth Tab + get_logcat (OAuthAuthTab)
CustomTabsIntent (Custom Scheme) androidx.browser:browser:1.0.0+ ACTION_VIEW intent delivered to RedirectReceiverActivity High risk of orphaned browser sheet or scheme collision get_latest_screenshot + adb shell dumpsys activity activities
CustomTabsIntent (HTTPS App Link) Verified /.well-known/assetlinks.json + autoVerify="true" OS routes HTTPS callback directly to app without chooser Chooser popup if assetlinks.json signature fails adb shell pm get-app-links + get_ui_hierarchy disambiguation check
External Browser Fallback Any installed system browser New tab in full browser fires ACTION_VIEW redirect Browser tab remains in recents; session state leaks across tests control_tap + get_latest_screenshot + adb shell pm clear cleanup

Setting Up ScreenSync MCP with Claude Code for OAuth Testing

Setting up ScreenSync MCP for Android OAuth testing requires launching the Node.js 18+ desktop hub on port 3000, registering the stdio server in Claude Code, and pairing the free ScreenSync MCP Android app (com.screensync.mcp) over your local network with USB or wireless ADB debugging enabled.

ScreenSync MCP is an Android and browser Model Context Protocol (MCP) server created by EpsolDev. Unlike cloud device farms that stream compressed video over WAN links, ScreenSync MCP keeps frame traffic on your local network: frames travel directly from your Android 7.0+ smartphone to the workstation hub and never pass through EpsolDev servers. (Be aware of your agent's privacy boundary: screenshots that Claude Code or another AI agent explicitly requests are sent to that agent's model provider for vision reasoning).

1. Prerequisites and Hub Startup

Verify that your workstation runs Node.js 18 or higher and has Android Platform Tools (adb) available in your PATH. Download the free ScreenSync MCP desktop hub (version 1.14.4 as of October 2026) and extract the archive, then launch the hub:

# On macOS or Linux
cd /path/to/hub
chmod +x start-hub.sh
./start-hub.sh

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

The hub starts an HTTP listener on port 3000 for incoming local MediaProjection frames and exposes its MCP interface over stdio, printing your pairing QR code and SCREEN_SYNC_TOKEN. Full installation details are documented in the ScreenSync MCP setup guide.

2. Registering ScreenSync MCP in Your Coding Agent

Add the hub to Claude Code from your project workspace:

claude mcp add screensync node "/path/to/hub/screensync-hub.js"

If you use Claude Desktop, add the server entry to claude_desktop_config.json (Settings > Developer):

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

ScreenSync MCP also works with Cursor and VS Code agent mode via local stdio MCP configurations (consult each editor's MCP configuration documentation for file paths). Note that ChatGPT's web app requires remote HTTPS MCP servers and is not supported by the local stdio hub.

3. Pairing the Android Device and Separating Capture from Control

  1. Install the free ScreenSync MCP app (com.screensync.mcp, version 2.5.7+) from Google Play on any device running Android 7.0 or later.
  2. Open the app and pair with the hub via mDNS auto-discovery on the same LAN or by scanning the hub's QR code. Requests authenticate with your SCREEN_SYNC_TOKEN bearer token.
  3. Grant Android's native MediaProjection screen capture consent prompt when prompted. Screen capture uses MediaProjection and requires no root and no ADB.
  4. Enable USB Debugging or Wireless Debugging in Android Developer Options so the desktop hub can execute ADB-backed control tools (control_tap, control_type, control_swipe). If you want a cable-free desk setup, follow our walkthrough on pairing Android wireless debugging to an MCP hub without USB.
  5. Confirm ADB sees your device:
adb devices -l

Five End-to-End OAuth & Auth Tab QA Workflows with Claude Code

Claude Code automates Android OAuth validation across five distinct test phases: cold-launch Auth Tab rendering, Chrome First-Run Experience (FRE) and PKCE parameter inspection, credential entry and MFA bypass in staging, deep-link or ActivityResult callback verification, and cancellation/back-button edge cases. Each workflow combines get_ui_hierarchy, get_latest_screenshot, control_* inputs, and get_logcat assertions.

Workflow 1: Verifying Chrome Auth Tab Launch and PKCE Query Parameters

Before typing credentials, verify that tapping the sign-in button launches AuthTabIntent (or CustomTabsIntent) with valid code_challenge, code_challenge_method=S256, state, and redirect_uri parameters—and does not silently fall back to an insecure embedded WebView.

Developer Prompt to Claude Code:

"Launch com.example.screensync.auth/.OAuthLoginActivity on the connected Android phone. Tap 'Sign In with OAuth', verify via get_ui_hierarchy and get_latest_screenshot that Chrome Auth Tab opens outside the app process, and inspect get_logcat for OAuthAuthTab to confirm S256 PKCE parameters were generated."

Execution Sequence:

  1. Claude Code launches the activity (adb shell am start -n com.example.screensync.auth/.OAuthLoginActivity) and calls get_ui_hierarchy to confirm "Status: Signed Out" and the "Sign In with OAuth" button bounds.
  2. Claude Code calls control_tap on the button coordinates.
  3. Within ~100 ms of the transition, Claude Code calls get_latest_screenshot and get_ui_hierarchy. In the returned XML hierarchy, the root package attribute transitions from com.example.screensync.auth to com.android.chrome:
<hierarchy rotation="0">
  <node index="0" package="com.android.chrome" class="android.widget.FrameLayout">
    <node index="0" resource-id="com.android.chrome:id/toolbar" class="android.widget.FrameLayout">
      <node index="0" resource-id="com.android.chrome:id/close_button" content-desc="Close tab" clickable="true" />
      <node index="1" resource-id="com.android.chrome:id/url_bar" text="auth.staging.example.com" />
    </node>
    <node index="1" class="android.webkit.WebView" package="com.android.chrome">
      <node index="0" class="android.widget.EditText" hint="Email" clickable="true" />
      <node index="1" class="android.widget.EditText" hint="Password" password="true" clickable="true" />
      <node index="2" class="android.widget.Button" text="Continue" clickable="true" />
    </node>
  </node>
</hierarchy>
  1. Notice how get_ui_hierarchy exposes the web form accessibility nodes (EditText for Email/Password and Button "Continue") directly inside com.android.chrome without needing Chromedriver! Meanwhile, Claude Code calls get_logcat to verify:
I OAuthAuthTab: Launching AuthTabIntent state=k9xP... challengeMethod=S256

Workflow 2: Driving IdP Login, Consent Screens, and Autofill Suppression

In real test runs, Chrome may show an "Account chooser", a Google Password Manager bottom sheet, or a first-run prompt on clean CI devices. Because Claude Code reads get_latest_screenshot alongside get_ui_hierarchy, it adapts immediately instead of timing out on an unexpected modal.

Execution Sequence:

  1. Claude Code inspects get_ui_hierarchy to locate the Email EditText, calls control_tap to focus it, and calls control_type with the staging test account email.
  2. If an Android Credential Manager or Autofill bottom sheet occludes the Password field, Claude Code spots the overlay in get_latest_screenshot or get_ui_hierarchy and dismisses it via back navigation or tapping outside the sheet before entering the staging password.
  3. Claude Code taps "Continue", waits for the consent screen ("Authorize screensync-mobile-client?"), inspects the requested scopes (openid, profile, email) visually in get_latest_screenshot, and calls control_tap on "Allow".

(Security note: Never embed production credentials in prompts. Use ephemeral staging accounts or sandbox IdP test users, and consider pairing flows with hardware passkey validation as described in our guide to testing Android Passkeys with Claude Code).

Workflow 3: Asserting Redirect Closure, Backstack Cleanliness, and Token Exchange

The most subtle bugs in Android OAuth happen on the return trip from Chrome back into the app. Claude Code verifies three conditions immediately after tapping "Allow":

  1. Browser Dismissal: get_ui_hierarchy confirms package="com.example.screensync.auth" is back in the foreground—not com.android.chrome and not an Android intent chooser dialog (com.android.internal.app.ResolverActivity).
  2. Telemetry Verification: get_logcat records "PKCE state verified; authorization code received; starting token exchange" with zero CSRF state mismatch or Missing Auth Code errors.
  3. UI State & Backstack Integrity: get_ui_hierarchy confirms "Status: Signed In (PKCE Verified)", and after a hardware Back key check, adb shell dumpsys activity activities confirms no orphaned CustomTabActivity remains stacked behind OAuthLoginActivity.

Workflow 4: Testing User Cancellation, Network Drops, and state Mismatch Attacks

Auth robustness requires testing failure paths just as rigorously as happy paths:

  • User Cancellation (RESULT_CANCELED): Claude Code taps Chrome's close_button (content-desc="Close tab") mid-login and asserts via get_ui_hierarchy and get_logcat that OAuthLoginActivity transitions gracefully to "Status: Auth Cancelled" without crashing or leaving a spinner stuck forever.
  • CSRF state Tampering Check: Claude Code can dispatch a forged callback intent via ADB (adb shell am start -a android.intent.action.VIEW -d "com.example.screensync.auth://callback?code=fake&state=tampered") against a CustomTabsIntent receiver and assert via get_logcat that the app rejects the forged state parameter (CSRF state mismatch) rather than exchanging the code.
  • Record Evidence: For flaky CI regressions, Claude Code can invoke record_screen to capture an MP4 video of the full cross-app transition alongside the exact Logcat slice.

Workflow 5: Dual-Surface Verification with the Browser Extension (web_* Tools)

Enterprise SaaS teams often need to verify that an Android OAuth login provisions a session or audit event visible immediately in a web admin dashboard. Beyond its 29 phone and desktop tools, ScreenSync MCP provides 197 web_* browser tools powered by an MV3 Chrome/Edge extension that runs in your real logged-in desktop browser tab with a human approval prompt for risky actions. Claude Code can complete the OAuth sign-in on the physical Android phone, then inspect the resulting session entry in your web console in the same session—a pattern detailed in building cross-platform AI workflows across mobile and browser MCP and on the ScreenSync MCP browser extension page.

OAuth / Auth Tab Failure Mode Root Cause in Android Code or Manifest ScreenSync MCP Detection Tool Concrete Assertion / Fix Signal
Intent Chooser Pops Up on Redirect Multiple apps or build flavors claim the same custom scheme get_ui_hierarchy (ResolverActivity) Switch to HTTPS App Links (autoVerify="true") or unique applicationId scheme
Auth Tab Never Closes After Login redirectScheme argument in launch() mismatches IdP redirect_uri get_latest_screenshot + get_logcat Align AuthTabIntent.launch(launcher, uri, scheme) with exact IdP callback
AuthTabIntent Falls Back to Browser Sheet Device default browser lacks Auth Tab support adb shell pm resolve-activity + get_latest_screenshot Verify CustomTabsIntent fallback path and RedirectReceiverActivity
Token Exchange Fails with invalid_grant code_verifier lost across process death while Chrome was foregrounded get_logcat (OAuthAuthTab / OkHttp) Persist code_verifier and state in SavedStateHandle or encrypted DataStore
Password Manager Sheet Blocks IdP Form Autofill or Credential Manager overlay covers Chrome WebView get_latest_screenshot + get_ui_hierarchy Agent dismisses sheet or tests Autofill path explicitly
Orphaned Custom Tab on Back Press RedirectReceiverActivity missing singleTask or finish() control_key (Back) + adb shell dumpsys activity Set launchMode="singleTask" and call finish() after forwarding URI

Triaging OAuth Process Death, App Links Failures, and Browser Channel Quirks

On memory-constrained Android devices, switching to Chrome for OAuth can trigger background process death of your host app, wiping in-memory code_verifier fields before the callback returns. Validating clean-slate cookie isolation, App Links verification, and SavedStateHandle persistence via ADB ensures OAuth passes reliably across physical hardware.

1. Reproducing Process Death While Chrome Holds Foreground Focus

Look closely at the Kotlin example earlier: pendingCodeVerifier and pendingState were stored as plain activity fields (private var pendingCodeVerifier: String? = null). On a mid-range Android phone with 4 GB RAM, opening Chrome inside AuthTabIntent can cause the OS lmkd (Low Memory Killer Daemon) to terminate your backgrounded app process while the user completes two-factor authentication. When Chrome redirects back, Android recreates OAuthLoginActivity from scratch—and pendingState is now null, causing a false CSRF state mismatch!

Claude Code can test this failure deterministically on a physical device:

  1. Launch OAuthLoginActivity and tap "Sign In with OAuth" so Chrome Auth Tab opens.
  2. Simulate background process kill using ADB while Chrome remains foregrounded:
adb shell am kill com.example.screensync.auth
  1. Complete the IdP login inside Chrome via control_tap and control_type.
  2. Watch get_logcat and get_ui_hierarchy: if "Error: State Mismatch" appears, Claude Code immediately diagnoses missing SavedStateHandle / onSaveInstanceState / EncryptedSharedPreferences persistence for pendingCodeVerifier and pendingState, patches the Kotlin code, rebuilds, and re-runs the exact sequence.

2. Verifying App Links (assetlinks.json) Before Running HTTPS Redirect Tests

If your AuthTabIntent or CustomTabsIntent uses an HTTPS redirect_uri (recommended over custom schemes to prevent scheme-squatting attacks), verify that Android actually verified your domain before running UI tests:

adb shell pm get-app-links com.example.screensync.auth

Look for verified next to auth.staging.example.com. If it reports none or 1024 (network/signature verification failure), force re-verification or inspect adb shell dumpsys package domain-preferred-apps and get_logcat for SingleHostAsyncVerifier errors.

3. Resetting Chrome Cookies and Test State Between Runs

Because Chrome Custom Tabs and Auth Tab share Chrome's cookie jar, a second test run may auto-approve SSO silently instead of exercising the login form. Between test iterations, isolate state cleanly—either by launching an ephemeral Auth Tab / incognito configuration when supported in debug builds, or by resetting the test browser/app state via ADB when running on dedicated QA hardware:

# Clear app-under-test state before a fresh OAuth test
adb shell pm clear com.example.screensync.auth

(Caution: Only run pm clear com.android.chrome on dedicated QA test devices, as clearing Chrome wipes all local browser profiles and bookmarks on personal phones.)

4. Comparing ScreenSync MCP Against Other Android MCP Tools

Developers evaluating the broader Model Context Protocol ecosystem will encounter alternatives such as ScreenMCP, mobile-mcp, Android-MCP, and scrcpy-mcp. While those projects focus primarily on ADB shell wrappers or standalone screen streaming, ScreenSync MCP unifies zero-root MediaProjection capture (~94 ms median LAN latency), ADB hardware control, Logcat/UI hierarchy inspection, and 197 web_* desktop browser extension tools in a single local stdio server—meaning one agent session can test both the mobile app's Auth Tab flow and the identity provider's web admin configuration side by side. Explore how these servers compare on the Android MCP servers comparison page.

Implementation Verification Checklist for Android OAuth & Auth Tab QA

A repeatable Android OAuth test pipeline verifies AndroidX Browser dependencies, PKCE state survival across process death, verified App Links manifests, and local ScreenSync MCP connectivity. Following this engineering checklist ensures Claude Code validates every boundary transition between your native app and Chrome deterministically.

  • [ ] Upgrade androidx.browser:browser to 1.9.0 or newer when adopting AuthTabIntent and AuthenticateUserResultContract, and retain a verified CustomTabsIntent fallback if targeting older browsers.
  • [ ] Persist PKCE code_verifier and state in SavedStateHandle or encrypted local storage so background process death during Chrome login does not cause state mismatches.
  • [ ] Confirm AndroidManifest.xml declares autoVerify="true" for HTTPS App Links redirects and verify status via adb shell pm get-app-links.
  • [ ] Start the ScreenSync MCP desktop hub (start-hub.bat or start-hub.sh) on Node.js 18+ and register it with Claude Code via claude mcp add screensync node "/path/to/hub/screensync-hub.js".
  • [ ] Install ScreenSync MCP (com.screensync.mcp) on an Android 7.0+ device, approve MediaProjection capture (no root, no ADB required), and connect USB or wireless ADB for control_* tools.
  • [ ] Assert in get_ui_hierarchy that tapping Sign In transitions foreground package from your app to com.android.chrome (confirming out-of-process Auth Tab, not an embedded WebView).
  • [ ] Execute happy-path login, user cancellation (close_button), and background adb shell am kill process-death tests, verifying get_logcat PKCE assertions and clean backstack return.
Verification Stage Primary Command or MCP Tool Target Signal / File Pass Criteria
Hub & Agent Handshake claude mcp list Local stdio process on Node.js 18+ screensync server reports connected with 226 tools (29 phone/desktop, 197 web_*)
Capture & Control Readiness get_latest_screenshot + adb devices LAN MediaProjection + ADB daemon ~94 ms median screenshot latency; device state shows device
Auth Tab Boundary Shift control_tap + get_ui_hierarchy Accessibility root package attribute Foreground package switches from app package to com.android.chrome
PKCE & State Generation get_logcat OAuthAuthTab tag Logs confirm challengeMethod=S256 and non-empty state token
Redirect & Token Handshake control_type + control_tap + get_logcat Callback Uri + UI status text Browser closes cleanly; UI displays "Signed In (PKCE Verified)"
Process-Death Resilience adb shell am kill <pkg> + get_logcat SavedStateHandle / state check Zero CSRF state mismatch errors when Chrome redirects back to recreated activity
Cancel & Backstack Hygiene control_tap (close_button) + dumpsys Activity task stack App displays "Auth Cancelled" and Back button exits cleanly without orphaned tabs

Next steps

FAQ

Questions, answered

Why does Espresso fail when testing Android Chrome Custom Tabs or Auth Tab OAuth?

Espresso executes inside your app's instrumentation process and requires a resumed app activity. When AuthTabIntent or CustomTabsIntent launches Chrome, foreground focus moves to com.android.chrome, causing Espresso to throw NoActivityResumedException. ScreenSync MCP inspects the composited display and system accessibility tree across both processes.

What is the difference between AuthTabIntent and CustomTabsIntent for Android OAuth?

AuthTabIntent in AndroidX Browser 1.9.0+ is built specifically for authentication and returns the redirect URI via AuthenticateUserResultContract without manual manifest receiver activities. CustomTabsIntent is a general browser sheet that relies on custom URI schemes or App Links intent filters to return OAuth callbacks.

Does ScreenSync MCP require root access to test Chrome Auth Tab on Android?

No. ScreenSync MCP captures the physical Android screen through Android's native MediaProjection API after one-time session consent, requiring zero root and zero ADB overhead for capture. Control gestures such as control_tap and control_type run over standard USB or wireless ADB debugging.

How can Claude Code verify OAuth PKCE parameters and state matching during a test?

Claude Code combines live visual and UI hierarchy assertions with real-time Logcat telemetry via get_logcat. By logging the S256 code_challenge launch, state validation, and callback handling under a dedicated tag, the agent confirms PKCE verification without exposing raw secrets in UI text.

How do you test background process death during an Android OAuth login flow?

Have Claude Code launch AuthTabIntent so Chrome takes the foreground, then run adb shell am kill against your app package while Chrome remains open. Complete the staging login inside Chrome and verify via get_logcat that SavedStateHandle preserves code_verifier and state across activity recreation.

Can ScreenSync MCP handle Google Password Manager or Autofill sheets inside Chrome Custom Tabs?

Yes. Because get_latest_screenshot captures the composited SurfaceFlinger display and get_ui_hierarchy inspects system-wide accessibility windows across processes, Claude Code detects Google Password Manager, Autofill, or Credential Manager bottom sheets immediately and dismisses or interacts with them before typing test account credentials.

Is ScreenSync MCP safe to use with sensitive OAuth login flows and staging credentials?

Screen frames stream directly from the Android app to your local desktop hub over your own network and never pass through EpsolDev servers. However, any screenshot an AI agent requests is transmitted to that agent's model provider, so teams should always test with non-production staging accounts.

Which AI coding tools work with ScreenSync MCP for Android OAuth QA?

ScreenSync MCP runs as a local stdio MCP server on Node.js 18+ and integrates with Claude Code, Claude Desktop, Cursor, and VS Code agent mode. ChatGPT's web application requires remote HTTPS MCP endpoints and is not supported by the local stdio hub.

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.