Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.
fix(mcp): never follow redirects, and cap replies as bytes arrive
Durganshu916e2ecb9a03
diff --git a/app/src/main/java/com/gotcha/connectors/mcp/McpHttpClient.kt b/app/src/main/java/com/gotcha/connectors/mcp/McpHttpClient.ktindex e05a71c..efb2032 100644--- a/app/src/main/java/com/gotcha/connectors/mcp/McpHttpClient.kt+++ b/app/src/main/java/com/gotcha/connectors/mcp/McpHttpClient.kt@@ -21,7 +21,11 @@ import okhttp3.OkHttpClientimport okhttp3.Requestimport okhttp3.RequestBody.Companion.toRequestBodyimport okhttp3.Response+import okio.Bufferimport okio.BufferedSource+import okio.ForwardingSource+import okio.Source+import okio.bufferimport java.io.IOExceptionimport java.util.concurrent.TimeUnitimport java.util.concurrent.atomic.AtomicLong@@ -98,19 +102,24 @@ data class McpEndpoint(val url: String, val headers: Map<String, String> = empty* - reads a `text/event-stream` reply event by event and stops at the* response whose id matches, skipping the server's own notifications and* requests, so a stream the server keeps open cannot hang the call;- * - caps how much of a reply it reads.+ * - caps how much of a reply it reads, counted as bytes arrive;+ * - never follows a redirect, since the token and headers would go with it+ * to a URL [validateMcpServer] never saw, perhaps over plain http.** Stdio servers and the older HTTP+SSE transport are out of scope; the latter* is recognised and reported as [McpFailure.OLD_TRANSPORT].*/class McpHttpClient(- private val client: OkHttpClient = OkHttpClient.Builder()+ client: OkHttpClient = OkHttpClient.Builder().connectTimeout(15, TimeUnit.SECONDS).readTimeout(60, TimeUnit.SECONDS).callTimeout(90, TimeUnit.SECONDS).build()) {+ /** Whatever client is passed in, redirects are off: a 3xx fails as [McpFailure.HTTP] instead. */+ private val client = client.newBuilder().followRedirects(false).followSslRedirects(false).build()+/** One server's session. Requests on it are serialized, which also keeps re-initialising race-free. */inner class Session internal constructor(val endpoint: McpEndpoint) {private val mutex = Mutex()@@ -290,7 +299,9 @@ class McpHttpClient(e as? McpException ?: McpException(McpFailure.NETWORK, e.message ?: e.javaClass.simpleName, cause = e)private fun httpFailure(session: Session, r: Response, firstRequest: Boolean): McpException {- val detail = runCatching { r.peekBody(ERROR_BODY_CHARS.toLong()).string() }.getOrDefault("").trim()+ // For a redirect, where it points is the useful part: the user can enter that URL instead.+ val detail = r.header("Location").takeIf { r.isRedirect }+ ?: runCatching { r.peekBody(ERROR_BODY_CHARS.toLong()).string() }.getOrDefault("").trim()return when (r.code) {401, 403 -> McpException(McpFailure.AUTH, detail, r.code)// The old transport answers POSTs on its SSE URL with 404/405 and@@ -317,11 +328,12 @@ class McpHttpClient(private fun readResponse(r: Response, id: Long): JsonObject {val body = r.body ?: notMcp("empty body")+ val source = CappedSource(body.source(), MAX_REPLY_BYTES).buffer()val type = r.header("Content-Type").orEmpty()return if (type.startsWith("text/event-stream")) {- readEventStream(body.source(), id)+ readEventStream(source, id)} else {- val text = body.source().readCapped()+ val text = source.readUtf8()val element = parseJson(text) ?: notMcp(text.take(ERROR_BODY_CHARS))matching(element, id) ?: notMcp("no response with id $id")}@@ -334,11 +346,8 @@ class McpHttpClient(*/private fun readEventStream(source: BufferedSource, id: Long): JsonObject {val data = StringBuilder()- var read = 0Lwhile (true) {val line = source.readUtf8Line() ?: break- read += line.length + 1- if (read > MAX_REPLY_BYTES) notMcp("reply larger than $MAX_REPLY_BYTES bytes")when {line.isEmpty() -> {if (data.isNotEmpty()) {@@ -356,9 +365,20 @@ class McpHttpClient(notMcp("event stream ended without a response")}- private fun BufferedSource.readCapped(): String {- if (!request(MAX_REPLY_BYTES + 1)) return readUtf8()- notMcp("reply larger than $MAX_REPLY_BYTES bytes")+ /**+ * Fails once more than [cap] bytes have come off the network. It sits under+ * the buffer, so it also bounds a line that never ends: `readUtf8Line`+ * would otherwise buffer all of it before anyone could count.+ */+ private class CappedSource(delegate: Source, private val cap: Long) : ForwardingSource(delegate) {+ private var total = 0L++ override fun read(sink: Buffer, byteCount: Long): Long {+ val n = super.read(sink, minOf(byteCount, cap - total + 1))+ if (n > 0) total += n+ if (total > cap) notMcp("reply larger than $cap bytes")+ return n+ }}private fun parseJson(text: String): JsonElement? =diff --git a/app/src/test/java/com/gotcha/connectors/mcp/McpHttpClientTest.kt b/app/src/test/java/com/gotcha/connectors/mcp/McpHttpClientTest.ktindex 9495b2a..5acadf0 100644--- a/app/src/test/java/com/gotcha/connectors/mcp/McpHttpClientTest.kt+++ b/app/src/test/java/com/gotcha/connectors/mcp/McpHttpClientTest.kt@@ -228,4 +228,57 @@ class McpHttpClientTest {closed.shutdown()assertEquals(McpFailure.NETWORK, failureOf { client.session(McpEndpoint(url)).initialize() }.kind)}++ @Test+ fun `a redirect is not followed, so the secret header stays put`() = runTest {+ val elsewhere = MockWebServer().apply { start() }+ val redirecting = MockWebServer().apply {+ dispatcher = object : Dispatcher() {+ override fun dispatch(request: RecordedRequest) = MockResponse()+ .setResponseCode(307)+ .setHeader("Location", elsewhere.url("/mcp").toString())+ }+ start()+ }+ // Even a client built to follow redirects is made not to.+ val following = McpHttpClient(OkHttpClient.Builder().followRedirects(true).followSslRedirects(true).build())+ try {+ val e = failureOf {+ following.session(+ McpEndpoint(redirecting.url("/mcp").toString(), mapOf("X-API-Key" to "secret"))+ ).initialize()+ }+ assertEquals(McpFailure.HTTP, e.kind)+ assertEquals(307, e.httpCode)+ assertEquals(elsewhere.url("/mcp").toString(), e.detail)+ assertEquals(0, elsewhere.requestCount)+ } finally {+ redirecting.shutdown()+ elsewhere.shutdown()+ }+ }++ @Test+ fun `an event line that never ends is cut at the cap, not buffered whole`() = runTest {+ val cap = 4 * 1024 * 1024+ val endless = MockWebServer().apply {+ dispatcher = object : Dispatcher() {+ // Past the cap with no newline, then the server goes quiet. A reader that+ // waits for the end of the line would sit here until the read timeout.+ override fun dispatch(request: RecordedRequest) = MockResponse()+ .setHeader("Content-Type", "text/event-stream")+ .setBody("data: " + "x".repeat(cap + cap / 4))+ .throttleBody(cap + 64L * 1024, 2, TimeUnit.SECONDS)+ }+ start()+ }+ val impatient = McpHttpClient(OkHttpClient.Builder().readTimeout(1, TimeUnit.SECONDS).build())+ try {+ val e = failureOf { impatient.session(McpEndpoint(endless.url("/mcp").toString())).initialize() }+ assertEquals(McpFailure.NOT_MCP, e.kind)+ assertTrue(e.detail, e.detail.contains("larger than"))+ } finally {+ endless.shutdown()+ }+ }}diff --git a/docs/mcp-servers.md b/docs/mcp-servers.mdindex df0074c..5002b02 100644--- a/docs/mcp-servers.md+++ b/docs/mcp-servers.md@@ -23,7 +23,8 @@ headers are kept in Gotcha's encrypted connector store on the phone.Plain `http://` works for servers on your own network: `localhost`, `.local` and `.lan`names, and private, link-local and Tailscale (100.64.0.0/10) addresses. A token or headersent over `http://` to anywhere else could be read on the way, so Gotcha asks for `https://`-there.+there. For the same reason Gotcha never follows a redirect: the token and headers would go to+a URL it never checked.## What the assistant gets@@ -64,6 +65,7 @@ known tools and shows the error under the server.| The server refused the token or headers (HTTP 401/403) | The token, or the header name and value. || Nothing answered at this URL (HTTP 404) | The path: many servers serve MCP at `/mcp`. || This server uses the older HTTP+SSE transport | Look for a Streamable HTTP endpoint in the server's docs. |+| The server returned HTTP 301/302/307/308 and a URL | The server moved: enter the URL it names. || The server answered, but not as an MCP server | The URL points at a web page or another API. || Couldn't reach the server | The address, the network, and whether the server is running. |