Skip to content

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.

Slash-tolerant MCP initialize: toggle /mcp spellings once

Rishabh Bajpaid96fc91eb585
diff --git a/app/src/main/java/com/gotcha/connectors/mcp/McpHttpClient.kt b/app/src/main/java/com/gotcha/connectors/mcp/McpHttpClient.kt
index 45e8bf1..62fe5da 100644
--- a/app/src/main/java/com/gotcha/connectors/mcp/McpHttpClient.kt
+++ b/app/src/main/java/com/gotcha/connectors/mcp/McpHttpClient.kt
@@ -129,7 +129,14 @@ class McpHttpClient(
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) {
+ inner class Session internal constructor(initialEndpoint: McpEndpoint) {
+ /**
+ * Where requests go. The slash-tolerant retry may move it to the
+ * working spelling; the setter stays private so all writes happen
+ * under the session mutex.
+ */
+ var endpoint: McpEndpoint = initialEndpoint
+ private set
private val mutex = Mutex()
private var sessionId: String? = null
private var protocolVersion: String? = null
@@ -168,24 +175,26 @@ class McpHttpClient(
private suspend fun initializeLocked(): McpServerInfo {
sessionId = null
protocolVersion = null
- val reply = exchange(
- this,
- rpcRequest(
- "initialize",
- buildJsonObject {
- put("protocolVersion", PROTOCOL_VERSION)
- put("capabilities", buildJsonObject {})
- put(
- "clientInfo",
- buildJsonObject {
- put("name", CLIENT_NAME)
- put("version", CLIENT_VERSION)
- }
- )
- }
- ),
- firstRequest = true
- )
+ val configured = endpoint
+ val reply = try {
+ exchange(this, initializeBody(), firstRequest = true)
+ } catch (e: McpException) {
+ retryInitialize(e)
+ }
+ var ok = false
+ try {
+ val server = initializedServer(reply)
+ ok = true
+ return server
+ } finally {
+ // The fallback spelling may answer but not as MCP (RPC error,
+ // no result, no version): don't stick to a spelling that never
+ // worked. Cancellation restores too.
+ if (!ok) endpoint = configured
+ }
+ }
+
+ private suspend fun initializedServer(reply: Reply): McpServerInfo {
sessionId = reply.sessionId
val result = reply.result()
val version = (result["protocolVersion"] as? JsonPrimitive)?.contentOrNull
@@ -208,6 +217,29 @@ class McpHttpClient(
return server
}
+ /**
+ * "/mcp" and "/mcp/" are the same thing: when the server 404s one spelling
+ * before any session exists, try the other once (issue #154) rather than
+ * fail the whole setup. A second failure restores the configured URL and
+ * reports the retry's error, so the message describes the last attempt.
+ */
+ private suspend fun retryInitialize(first: McpException): Reply {
+ val original = endpoint
+ val alternate = slashToggled(original.url)
+ if (first.kind != McpFailure.NOT_FOUND || alternate == null) throw first
+ endpoint = original.copy(url = alternate)
+ var ok = false
+ try {
+ val reply = exchange(this, initializeBody(), firstRequest = true)
+ ok = true
+ return reply
+ } finally {
+ // Cancellation included: a failed retry must not leave the
+ // alternate spelling stored.
+ if (!ok) endpoint = original
+ }
+ }
+
/** One request, initialising first if needed, and once more if the server dropped the session. */
private suspend fun requestLocked(method: String, params: JsonObject): JsonObject {
if (protocolVersion == null) initializeLocked()
@@ -315,6 +347,35 @@ class McpHttpClient(
throw McpException(McpFailure.HTTP, "too many redirects", lastCode)
}
+ /**
+ * The URL with its trailing slash toggled: "/mcp" becomes "/mcp/" and back.
+ * Null when there is nothing to toggle (unparseable, or the bare root).
+ * Query and fragment survive; the rest of the URL is untouched. Visible
+ * for tests.
+ */
+ internal fun slashToggled(url: String): String? {
+ val parsed = url.toHttpUrlOrNull() ?: return null
+ val path = parsed.encodedPath
+ if (path == "/") return null
+ val toggled = if (path.endsWith("/")) path.dropLast(1) else "$path/"
+ return parsed.newBuilder().encodedPath(toggled).build().toString()
+ }
+
+ private fun initializeBody(): Outgoing = rpcRequest(
+ "initialize",
+ buildJsonObject {
+ put("protocolVersion", PROTOCOL_VERSION)
+ put("capabilities", buildJsonObject {})
+ put(
+ "clientInfo",
+ buildJsonObject {
+ put("name", CLIENT_NAME)
+ put("version", CLIENT_VERSION)
+ }
+ )
+ }
+ )
+
/**
* Where a redirect points, when it is safe to follow: the same origin
* (scheme, host and port — the token stays where the user put it), or an
diff --git a/app/src/test/java/com/gotcha/connectors/mcp/McpHttpClientTest.kt b/app/src/test/java/com/gotcha/connectors/mcp/McpHttpClientTest.kt
index 78edea6..198e349 100644
--- a/app/src/test/java/com/gotcha/connectors/mcp/McpHttpClientTest.kt
+++ b/app/src/test/java/com/gotcha/connectors/mcp/McpHttpClientTest.kt
@@ -10,6 +10,7 @@ import okhttp3.mockwebserver.MockWebServer
import okhttp3.mockwebserver.RecordedRequest
import org.junit.After
import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Assert.fail
import org.junit.Before
@@ -390,4 +391,79 @@ class McpHttpClientTest {
endless.shutdown()
}
}
+
+ @Test
+ fun `a missing trailing slash is toggled once before failing`() = runTest {
+ // Serves only the slashed spelling, 404s the bare one, never redirects.
+ val picky = MockWebServer().apply {
+ dispatcher = object : Dispatcher() {
+ override fun dispatch(request: RecordedRequest): MockResponse {
+ if (request.path != "/mcp/") return MockResponse().setResponseCode(404)
+ return fake.dispatch(request)
+ }
+ }
+ start()
+ }
+ try {
+ val info = client.session(McpEndpoint(picky.url("/mcp").toString())).initialize()
+ assertEquals("Docs", info.name)
+ } finally {
+ picky.shutdown()
+ }
+ }
+
+ @Test
+ fun `an extra trailing slash is toggled once before failing`() = runTest {
+ // Serves only the bare spelling, 404s the slashed one, never redirects.
+ val picky = MockWebServer().apply {
+ dispatcher = object : Dispatcher() {
+ override fun dispatch(request: RecordedRequest): MockResponse {
+ if (request.path != "/mcp") return MockResponse().setResponseCode(404)
+ return fake.dispatch(request)
+ }
+ }
+ start()
+ }
+ try {
+ val info = client.session(McpEndpoint(picky.url("/mcp/").toString())).initialize()
+ assertEquals("Docs", info.name)
+ } finally {
+ picky.shutdown()
+ }
+ }
+
+ @Test
+ fun `two missing spellings still fail, on the configured URL`() = runTest {
+ // 404s everything: the retry must not mask a genuinely absent server,
+ // and the session keeps the URL the user entered.
+ val absent = MockWebServer().apply {
+ dispatcher = object : Dispatcher() {
+ override fun dispatch(request: RecordedRequest) =
+ MockResponse().setResponseCode(404)
+ }
+ start()
+ }
+ try {
+ val session = client.session(McpEndpoint(absent.url("/mcp").toString()))
+ val e = failureOf { session.initialize() }
+ assertEquals(McpFailure.NOT_FOUND, e.kind)
+ // One POST + old-transport GET per spelling, then give up.
+ val paths = List(4) { absent.takeRequest(5, TimeUnit.SECONDS)!!.path }
+ assertEquals(listOf("/mcp", "/mcp", "/mcp/", "/mcp/"), paths)
+ assertEquals(absent.url("/mcp").toString(), session.endpoint.url)
+ } finally {
+ absent.shutdown()
+ }
+ }
+
+ @Test
+ fun `slash toggling leaves the rest of the URL alone`() {
+ val client = McpHttpClient()
+ assertEquals("http://h/mcp/", client.slashToggled("http://h/mcp"))
+ assertEquals("http://h/mcp", client.slashToggled("http://h/mcp/"))
+ assertEquals("http://h/a/b/", client.slashToggled("http://h/a/b"))
+ assertEquals("http://h/mcp/?k=v", client.slashToggled("http://h/mcp?k=v"))
+ assertNull(client.slashToggled("http://h/"))
+ assertNull(client.slashToggled("not a url"))
+ }
}