Fix MCP tool invocation: notification handling, TLS multi-record, idle timeout

- HttpTransport: add handleNotification() for fire-and-forget JSON-RPC
  messages (no response expected). Without this, notifications/initialized
  hung forever waiting for a response that never came.

- McpRouting: detect JSON-RPC notifications (no "id" field) and return
  202 Accepted immediately instead of dispatching through handleRequest.
  Also add 5s timeout on receiveText() for /register to prevent hangs.

- TlsInputStream: same multi-record fix as TlsAcceptor handshake —
  check netIn.position() before reading from stream. HTTP headers and
  body arriving in the same mux DATA frame caused the body read to block.

- TunnelClientImpl: catch ClosedSendChannelException in onBinaryMessage
  to prevent crash when WebSocket frames arrive after disconnect.

- TunnelForegroundService: handle double-wake by disconnecting stale
  connection before reconnecting.

- Increase idle timeout to 30 minutes for testing (was 5 minutes, which
  caused the connection to drop right when Claude tried tool calls).

Verified: Claude connected via OAuth, called echo and device_info tools
successfully through the full relay → device → MCP pipeline.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jason Monk 2026-04-06 16:41:22 -04:00
parent 9737a2d3ea
commit d8c4b6454d
6 changed files with 105 additions and 45 deletions

View file

@ -48,8 +48,8 @@ import org.koin.core.qualifier.named
import org.koin.dsl.bind
import org.koin.dsl.module
/** Idle timeout before disconnecting the tunnel (5 minutes). */
private const val IDLE_TIMEOUT_MS = 5 * 60 * 1000L
/** Idle timeout before disconnecting the tunnel (30 minutes for testing). */
private const val IDLE_TIMEOUT_MS = 30 * 60 * 1000L
/**
* Root Koin module that wires all app dependencies.

View file

@ -66,4 +66,13 @@ internal class HttpTransport : Transport {
return deferred.await()
}
/**
* Handles an incoming JSON-RPC notification (no response expected).
* Feeds the message to the SDK Server without waiting for a response.
*/
suspend fun handleNotification(notification: JSONRPCMessage) {
val handler = messageHandler ?: return
handler(notification)
}
}

View file

@ -147,49 +147,55 @@ fun Application.configureMcpRouting(
}
val body = try {
mcpJson.parseToJsonElement(call.receiveText()).jsonObject
} catch (_: Exception) {
call.respond(HttpStatusCode.BadRequest)
val text = kotlinx.coroutines.withTimeout(5000) {
call.receiveText()
}
mcpJson.parseToJsonElement(text).jsonObject
} catch (e: Exception) {
println("McpRouting: /register body read failed: ${e::class.simpleName}: ${e.message}")
call.respondText("{}", ContentType.Application.Json, HttpStatusCode.BadRequest)
return@post
}
val clientName = body["client_name"]?.jsonPrimitive?.content ?: "unknown"
val clientId = java.util.UUID.randomUUID().toString()
call.respond(
HttpStatusCode.Created,
buildJsonObject {
put("client_id", clientId)
put("client_name", clientName)
put(
"redirect_uris",
kotlinx.serialization.json.JsonArray(
(body["redirect_uris"] as? kotlinx.serialization.json.JsonArray)
?.toList() ?: emptyList()
)
val response = buildJsonObject {
put("client_id", clientId)
put("client_name", clientName)
put(
"redirect_uris",
kotlinx.serialization.json.JsonArray(
(body["redirect_uris"] as? kotlinx.serialization.json.JsonArray)
?.toList() ?: emptyList()
)
put(
"grant_types",
kotlinx.serialization.json.JsonArray(
listOf(
kotlinx.serialization.json.JsonPrimitive(
"authorization_code"
),
kotlinx.serialization.json.JsonPrimitive(
"urn:ietf:params:oauth:grant-type:device_code"
)
)
put(
"grant_types",
kotlinx.serialization.json.JsonArray(
listOf(
kotlinx.serialization.json.JsonPrimitive(
"authorization_code"
),
kotlinx.serialization.json.JsonPrimitive(
"urn:ietf:params:oauth:grant-type:device_code"
)
)
)
put(
"response_types",
kotlinx.serialization.json.JsonArray(
listOf(
kotlinx.serialization.json.JsonPrimitive("code")
)
)
put(
"response_types",
kotlinx.serialization.json.JsonArray(
listOf(
kotlinx.serialization.json.JsonPrimitive("code")
)
)
put("token_endpoint_auth_method", "none")
}
)
put("token_endpoint_auth_method", "none")
}
call.respondText(
response.toString(),
ContentType.Application.Json,
HttpStatusCode.Created
)
}
@ -375,8 +381,23 @@ fun Application.configureMcpRouting(
// Parse and dispatch JSON-RPC request through SDK transport
val requestBody = call.receiveText()
val responseJson = dispatchJsonRpc(integrationServer.transport, requestBody)
call.respondText(responseJson, ContentType.Application.Json)
// JSON-RPC notifications have no "id" field and expect no response
val parsed = try {
mcpJson.parseToJsonElement(requestBody).jsonObject
} catch (_: Exception) {
null
}
val isNotification = parsed != null && !parsed.containsKey("id")
if (isNotification) {
// Fire-and-forget: dispatch to SDK but return 202 immediately
dispatchNotification(integrationServer.transport, requestBody)
call.respond(HttpStatusCode.Accepted)
} else {
val responseJson = dispatchJsonRpc(integrationServer.transport, requestBody)
call.respondText(responseJson, ContentType.Application.Json)
}
}
}
}
@ -453,6 +474,15 @@ private suspend fun createIntegrationServer(
* Dispatches a raw JSON-RPC request string through the SDK Server via HttpTransport.
* Returns the JSON-RPC response string.
*/
internal suspend fun dispatchNotification(transport: HttpTransport, requestBody: String) {
val message = try {
mcpJson.decodeFromString(JSONRPCMessage.serializer(), requestBody)
} catch (_: Exception) {
return
}
transport.handleNotification(message)
}
internal suspend fun dispatchJsonRpc(transport: HttpTransport, requestBody: String): String {
val message = try {
mcpJson.decodeFromString(JSONRPCMessage.serializer(), requestBody)

View file

@ -48,7 +48,11 @@ class TunnelClientImpl(
override fun onBinaryMessage(data: ByteArray) {
val muxFrame = MuxCodec.decode(data)
scope.launch {
demux.handleFrame(muxFrame)
try {
demux.handleFrame(muxFrame)
} catch (_: kotlinx.coroutines.channels.ClosedSendChannelException) {
// WebSocket frame arrived after disconnect, ignore
}
}
}

View file

@ -248,14 +248,19 @@ internal class TlsInputStream(
// Need to decrypt more data
appIn.clear()
while (true) {
val tlsData =
try {
kotlinx.coroutines.runBlocking { stream.read() }
} catch (_: Exception) {
return -1
}
netIn = ensureCapacity(netIn, tlsData.size)
netIn.put(tlsData)
// Only read from the stream if netIn has no leftover data.
// Multiple TLS records may arrive in a single mux DATA frame,
// so netIn may still have data from a previous unwrap.
if (netIn.position() == 0) {
val tlsData =
try {
kotlinx.coroutines.runBlocking { stream.read() }
} catch (_: Exception) {
return -1
}
netIn = ensureCapacity(netIn, tlsData.size)
netIn.put(tlsData)
}
netIn.flip()
val result = engine.unwrap(netIn, appIn)

View file

@ -52,6 +52,18 @@ class TunnelForegroundService : LifecycleService() {
super.onStartCommand(intent, flags, startId)
lifecycleScope.launch {
if (tunnelClient.state.value == TunnelState.CONNECTING) {
Log.i(TAG, "Already connecting, skipping")
return@launch
}
if (tunnelClient.state.value == TunnelState.CONNECTED) {
Log.i(TAG, "Already connected, disconnecting first to refresh")
try {
tunnelClient.disconnect()
} catch (_: Exception) {
// Best-effort
}
}
try {
tunnelClient.connect(relayUrl)
} catch (e: Exception) {