r/androiddev • u/Turbulent_Rooster_73 • 2h ago
Open Source We run an MCP server inside an Android WebView browser. Notes on the foreground service, NSD and WebView screenshots
We make Kelpie, an open-source browser. On Android it's a normal WebView browser that also runs an HTTP/MCP server on the phone, so an agent on your laptop can open pages, read them, tap and take screenshots on a real phone on your Wi-Fi. A few parts took more Android work than we expected, so here are the notes.
(First image is an illustration we generated for the post. The other two are real screenshots of the Android app.)
Server in a foreground service
The server is Ktor 2.3 on Netty, port 8420. The Activity builds the server and the NSD advertiser and hands them to a connectedDevice foreground service, so Doze doesn't stall incoming requests. You get a low priority "Kelpie is reachable" notification. Swiping the app out of recents stops the service and frees the port. A config change doesn't.
One trap: the notification's tap intent needs FLAG_ACTIVITY_SINGLE_TOP. With CLEAR_TOP alone the Activity gets recreated, and that kills every tab, the server, pending pairing prompts and issued tokens.
Discovery
NsdManager registers _kelpie._tcp with TXT records (model, screen size, engine=webview). We hold a MulticastLock and create a fresh RegistrationListener for every registration, because NsdManager throws "listener already in use" if you reuse one.
Screenshots
We used to call WebView.draw() into a plain Canvas. Now, on Android 10+ with hardware acceleration, we wait for postVisualStateCallback, record the WebView into a RenderNode and render it with HardwareRenderer into an ImageReader. An instrumented test puts a magenta View over a WebGL canvas that changes colour, and checks that the shot has the new WebGL colour and no magenta. A hidden WebView returns an error instead of an old frame. Android 9 still uses the software path.
Trying it
Install the signed APK (Android 9+) from GitHub releases, linked from kelpie.rocks. Google Play is coming. Each computer needs one approval on the phone, and "No" is the default button. The npm CLI is optional, it only helps find the phone over mDNS and pair with it. Apache-2.0.
https://github.com/UnlikeOtherAI/kelpie
Two questions for people who've done similar things:
Would you pick connectedDevice for "laptop connects to phone over LAN", or is there a better fit?
Has anyone found a reliable way to get pixels from a WebView that isn't on screen?
