From 21cd2832250c2a9f5fc710e89d31cee1221b4772 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 15 Nov 2026 21:37:07 -0800 Subject: [PATCH 01/90] ADFA-7139 Refresh libs/plugin-api.jar for DebuggerEndpointService The AI-Agent-MCP debugger entry compiles against DebuggerEndpointService, DebuggerEndpoint and the debugger.endpoints permission, which the checked-in plugin-api.jar lacks. The jar is rebuilt from CodeOnTheGo branch sqlite-debugger/ADFA-7139, commit 8e7473b76 ("Add DebuggerEndpointService and the debugger.endpoints permission"); the plugin-api module is unchanged by the later commits on that branch. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- libs/plugin-api.jar | Bin 433257 -> 443851 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/libs/plugin-api.jar b/libs/plugin-api.jar index b3f00fb0202ddae5b89cd77c1f74176a457c85f7..0165f176208712e9a6b6dfa7c7cda17b5a34c0a3 100644 GIT binary patch delta 112018 zcmZ6SV|d@ux8-Bowr$(CZQJa(abxEf+iYyJLE|*G)39-a>CAoZo%zpscV6$$v(Gwf z?S0lkFcnMqT@@0Uv0O}i85|7k5dsX1F?o<2L`DRIoEig(0etvUtUY^$nzNnhc1+uG@`>&HVqrj-s`%vf%ED1-~`kFX0i)Dd{CMx zHEGBGffp^rjF?`nC9~+nqt%(Pe}Ld;hO{R)Eu9t}gx581^7UXjX{l-3GBar8$i>QmOxEMRj+zp3+!L=YKpZsK1Q-p*9`*+~L$l=H#%Ea{=uKwMZkw9b~kW{IO zC@>)4e;2$O8U^SX6O-`cb>&deSQoQ{ry9kAgN{5)LnSsRO$bdAGFZdxyES|*THKjK zC8l}LAYDGorE>%~bR;z1l=K;IWfP^FlmEz{M*RpUE6s2dD@NB6D zTA?}P_I@^0YGApxhKSqWO^s2NYV*uC2S=J8u;syO^WGNT$y=5#+N}_>@H!LwTOR?N zlqL&vZS}&4uGKA17YO>Nw1{=EWEydDfi_hm%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Ry2^ zV;UKhvix5L|C}HCHvsek9RQpt;%5GH4&`531$6foumHfp6dH839UpuEjU2N>%6o~5 z@e(ZRHR@LgD%b@BW$X6u(F*ZrLpm0gE=D10jQ^(fhuOdRESp7h&tl_Iqq&&-kp2i<6!B>u#XSXqC1WC} z?;e~Dfw5cT4;6g#kzG9IodSk9a=u75keJ(z+k9dLwE1^MPTf$+(J7BXz|FP zpdv7Up8A1CUKGJqVBQcL~&1|R@N0;BWy`(SjQ;Xd{wLCHo3xt0Prj~4~YLT#mBDnTlUcE}sxp@$L3>;d4kh@fC! zn41LJo2?AkD=D&QN4pIkDU??RMA=qCBe>?!*9L=PE#o1Lo*_E(hV!pk{vjuoW9Ll2QpiaT8rQc922vDqx;H zaz-N~*YS9u#}7a}IaOdCW*Mp}2gMIiI*271j{@zbmVx)TRcY&U9F`99dI;?3Pl3OY zhj0PJpOwsiyWE%8&@|<0xGF3)1m$3dE;r*Lpzb`7AQM8k-IZ%)P z3u&nVit+8nUkHB{ko72hPc4S5lWBjkDCz*K=EnEop@VBFH7LOKsR||q#KSg<;goNwhCm^tD_;<;0b)o$DAqqA)HFTpMnCLH_ z{e=jx;W0xZ4ImQBo+CKB2^hI8>!2zt>OtN+8bID#d;fT`eF3S8G=c!z{TL__RMZGm zgMaux)ExF=B{$rT1Cd}{cUkGnA(CeG;&`4@C zTp!jr{g*dO3tS!c;r(BTIsuRzEq)6S-{QkxeoU>vewSbT3&|q`?>ZcP`JSYL|6O#? zKL5ocX#ut^dU$YX^#z`Slo~hki1G^p4gE>f3>I(%XOe z2mfc`P g|7QvOuR&py4oc{Ti<3!UOJEm7gDrmazz)ayANAt_@&Et; From 6f2fde440c49a5f3214a87fcb430b9599f37fffa Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 15 Nov 2026 21:37:08 -0800 Subject: [PATCH 02/90] ADFA-7139 AI-Agent-MCP: automatic server entry for the open project's debugger An app built in Code on the Go with cogo.sqliteDebugger=true serves its databases over MCP on 127.0.0.1. AI-Agent-MCP now offers that server to the Agent with nothing typed in. - One automatic server entry per endpoint reported by DebuggerEndpointService: http://127.0.0.1:/mcp, the token kept in memory only and never stored in the Keystore. No endpoint means no entry and no error. - The endpoint is re-read before reconnecting after a refused connection, 401 or 403, so a relaunched app (new port and token) is picked up; its tools stay offered across the relaunch. A refused read is logged once. - For this entry only, tools whose readOnlyHint is exactly true (boolean) start switched on and others start off. Hand-added servers keep today's behaviour even when they claim the hint. AI-Core still asks for approval on every call of a contributed tool, so the pre-approval does not skip the prompt; automatic approval is ADFA-7147. - The manifest declares debugger.endpoints and plugin.min_ide_version 26.43: an older Code on the Go rejects the unknown permission at validation, so it cannot install this version at all. - Showing the entry in the settings screen is deferred to phase 2: the eight phase 1 tools are all read-only, so nothing needs switching on. Tests: no endpoint; stale endpoint (refused, 401, 403) re-read; relaunch through a fake MCP server keeps the tools; the annotation rule (true, false, missing, "true", 1, null); a hand-added server claiming the hint stays off; a repeated read failure is logged once. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../AI-Agent-MCP/src/main/AndroidManifest.xml | 19 +- .../aiagentmcp/client/McpConnections.kt | 5 + .../plugins/aiagentmcp/client/McpSession.kt | 4 + .../plugins/aiagentmcp/client/McpTool.kt | 3 + .../aiagentmcp/debugger/AutomaticServers.kt | 199 ++++++++++++++++++ .../aiagentmcp/debugger/EndpointRetry.kt | 49 +++++ .../aiagentmcp/debugger/ReadOnlyTrust.kt | 33 +++ .../plugins/aiagentmcp/plugin/McpPlugin.kt | 51 ++++- .../plugins/aiagentmcp/settings/McpServer.kt | 3 + .../aiagentmcp/tools/McpToolCatalog.kt | 33 ++- .../plugins/aiagentmcp/tools/McpToolSource.kt | 36 ++-- .../debugger/AutomaticServersTest.kt | 182 ++++++++++++++++ .../aiagentmcp/debugger/EndpointRetryTest.kt | 142 +++++++++++++ .../debugger/ReadOnlyHintParsingTest.kt | 66 ++++++ .../debugger/RelaunchToolSourceTest.kt | 122 +++++++++++ .../debugger/RepeatedFailureLogTest.kt | 23 ++ .../aiagentmcp/testing/FakeMcpServer.kt | 59 ++++++ 17 files changed, 1001 insertions(+), 28 deletions(-) create mode 100644 plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt create mode 100644 plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/EndpointRetry.kt create mode 100644 plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReadOnlyTrust.kt create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServersTest.kt create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/EndpointRetryTest.kt create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReadOnlyHintParsingTest.kt create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/RelaunchToolSourceTest.kt create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/RepeatedFailureLogTest.kt create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/testing/FakeMcpServer.kt diff --git a/plugins/AI-Agent-MCP/src/main/AndroidManifest.xml b/plugins/AI-Agent-MCP/src/main/AndroidManifest.xml index 4c179768d..a41b06ca9 100644 --- a/plugins/AI-Agent-MCP/src/main/AndroidManifest.xml +++ b/plugins/AI-Agent-MCP/src/main/AndroidManifest.xml @@ -39,23 +39,26 @@ android:name="plugin.author" android:value="App Dev for All" /> - + + android:value="26.43" /> - + + android:value="network.access,debugger.endpoints" /> = emptyMap(), + val readOnlyHint: Boolean = false, ) /** diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt new file mode 100644 index 000000000..89c997a7f --- /dev/null +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt @@ -0,0 +1,199 @@ +package com.itsaky.androidide.plugins.aiagentmcp.debugger + +import android.util.Log +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.client.McpTool +import com.itsaky.androidide.plugins.aiagentmcp.logging.LOG_PREFIX +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServer +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpServerHealth +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpToolCatalog +import com.itsaky.androidide.plugins.services.DebuggerEndpoint +import java.util.concurrent.CopyOnWriteArrayList + +private const val TAG = "$LOG_PREFIX.AutomaticServers" + +/** One endpoint as this plugin needs it, kept apart from the host type so tests need no jar. */ +data class AutomaticEndpoint(val applicationId: String, val port: Int, val token: String) { + // The token is a credential: it stays out of logs. + override fun toString() = "AutomaticEndpoint($applicationId, port=$port)" +} + +/** + * Reports the first failure in full and every later one briefly, so a failure that repeats on a timer + * does not fill the log. One instance per process. + */ +class RepeatedFailureLog( + private val first: (Throwable) -> Unit, + private val later: (Throwable) -> Unit, +) { + private val reported = java.util.concurrent.atomic.AtomicBoolean(false) + + fun report(e: Throwable) { + if (reported.compareAndSet(false, true)) first(e) else later(e) + } +} + +/** + * The server entries Code on the Go supplies for the open project's debuggable apps. + * + * Held in memory only: port and token change on every app start, so nothing here is worth + * persisting, and the token stays out of the Keystore-backed store the user's own servers use. + * Read from the host on [refresh]; an app that has not reported yields no entry at all. + */ +object AutomaticServers { + + const val ID_PREFIX = "debugger:" + + private class State(val endpoint: AutomaticEndpoint, val tools: List = emptyList()) + + @Volatile private var states: Map = emptyMap() + + @Volatile private var source: (() -> List)? = null + + private val listeners = CopyOnWriteArrayList<() -> Unit>() + + private val endpointListeners = CopyOnWriteArrayList<(String) -> Unit>() + + /** The probe calls [refresh] every 20 s, so a refused permission would otherwise log a stack trace forever. */ + private val readFailures = RepeatedFailureLog( + first = { e -> Log.w(TAG, "Could not read the debugger endpoints; keeping the previous entries", e) }, + later = { e -> Log.d(TAG, "Still cannot read the debugger endpoints: $e") }, + ) + + /** Where endpoints come from; null (deactivation) clears every entry. */ + fun install(source: (() -> List)?) { + this.source = source + if (source == null) clear() else refresh() + } + + /** Adapts the host's service. A host without the service, or without the permission, is no source. */ + fun fromHost(read: () -> List): () -> List = { + read().map { AutomaticEndpoint(it.applicationId, it.port, it.token) } + } + + fun addChangeListener(listener: () -> Unit) { + listeners.add(listener) + } + + fun removeChangeListener(listener: () -> Unit) { + listeners.remove(listener) + } + + /** + * Registers [listener], called with the id of an entry that appeared or whose port or token + * changed, so the owner can list its tools at once instead of at the next probe. + */ + fun addEndpointListener(listener: (String) -> Unit) { + endpointListeners.add(listener) + } + + fun removeEndpointListener(listener: (String) -> Unit) { + endpointListeners.remove(listener) + } + + /** + * Re-reads the endpoints. Blocking host call: use a background thread. + * @return true when the set of entries, a port or a token changed. + */ + fun refresh(): Boolean { + val read = source ?: return false + val fresh = try { + read().associateBy { idFor(it.applicationId) } + } catch (e: Exception) { + // A failed read is not "no apps": the entries stay as they were, since wiping them + // would take every debugger tool away from the agent on a transient database error. + readFailures.report(e) + return false + } + val moved = mutableListOf() + val removed: List + val changed = synchronized(this) { + val old = states + val next = fresh.mapValues { (id, endpoint) -> + val previous = old[id] + when { + previous == null -> State(endpoint).also { moved += id } + previous.endpoint == endpoint -> previous + // The previous list stays until the new process answers: the tool names almost + // never change on a relaunch, and an empty list would take every tool away from + // the agent for as long as the re-list takes. + else -> State(endpoint, previous.tools).also { moved += id } + } + } + states = next + removed = (old.keys - next.keys).toList() + old.mapValues { it.value.endpoint } != next.mapValues { it.value.endpoint } + } + for (id in removed) { + McpToolCatalog.forget(id) + McpConnections.invalidate(id) + } + for (id in moved) { + // A refused credential is not final for this entry: the new one has not been tried. + McpServerHealth.credentialChanged(id) + for (l in endpointListeners) runCatching { l(id) } + } + if (changed) fireChanged() + return changed + } + + /** The entries to offer, with their tool switches already decided by [ReadOnlyTrust]. */ + fun servers(): List = states.map { (id, state) -> + McpServer( + id = id, + name = "SQLite debugger (${state.endpoint.applicationId})", + url = urlFor(state.endpoint), + enabled = true, + knownTools = state.tools.map { it.name }, + enabledTools = ReadOnlyTrust.enabledTools(state.tools), + automatic = true, + ) + } + + fun isAutomatic(serverId: String): Boolean = serverId.startsWith(ID_PREFIX) + + /** The bearer token for [serverId], or null when it has no entry (any more). */ + fun token(serverId: String): String? = states[serverId]?.endpoint?.token + + /** The endpoint now stored for [serverId], or null when it has no entry. */ + fun endpoint(serverId: String): AutomaticEndpoint? = states[serverId]?.endpoint + + fun urlFor(endpoint: AutomaticEndpoint) = "http://127.0.0.1:${endpoint.port}/mcp" + + /** + * Remembers what the server listed. + * + * @param origin the endpoint the list was fetched from. A list from an endpoint that has since + * been replaced belongs to the old process and is dropped; the check and the write share one + * lock, so a refresh cannot slip between them. + * @return false when the list was dropped (no entry any more, or [origin] is out of date). + */ + fun recordTools(serverId: String, origin: AutomaticEndpoint, tools: List): Boolean { + synchronized(this) { + val state = states[serverId] ?: return false + if (state.endpoint != origin) return false + // The probe re-lists every cycle; an unchanged list must not make the agent rebuild. + if (state.tools == tools) return true + states = states + (serverId to State(state.endpoint, tools)) + } + fireChanged() + return true + } + + fun clear() { + val had = synchronized(this) { states.isNotEmpty().also { states = emptyMap() } } + if (had) fireChanged() + } + + fun idFor(applicationId: String) = ID_PREFIX + applicationId + + private fun fireChanged() { + for (l in listeners) runCatching { l() } + } +} + +/** Every server the agent may use: the user's own plus the automatic entries. */ +object McpServers { + fun all(): List = McpServerStore.servers() + AutomaticServers.servers() +} diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/EndpointRetry.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/EndpointRetry.kt new file mode 100644 index 000000000..d6cfb34fa --- /dev/null +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/EndpointRetry.kt @@ -0,0 +1,49 @@ +package com.itsaky.androidide.plugins.aiagentmcp.debugger + +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServer +import com.itsaky.androidide.plugins.aiagentmcp.transport.McpHttpException +import java.net.ConnectException + +/** + * Retries a call on an automatic entry once, with the endpoint read again. + * + * A relaunched app listens on a new port with a new token, so a refused connection or a 401/403 + * usually means the stored values are stale. The retry happens only when this entry's URL or + * token now differ from the ones the failing call used: asking the same server the same thing + * again helps nobody. A read timeout is not retried: the server may still be running the call, + * and repeating it would run a slow query twice. + * + * @param refresh re-reads the endpoints. + * @param current the entry now stored for an id, or null when its app is gone. + * @param token the token now stored for an id, or null when it has no entry. + */ +class EndpointRetry( + private val refresh: () -> Boolean, + private val current: (String) -> McpServer?, + private val token: (String) -> String?, +) { + fun call(server: McpServer, block: (McpServer) -> T): T { + // What the call is about to use: the credential is read per request, so a refresh by the + // probe that lands first is what this call sends, and is what the comparison must see. + val usedToken = token(server.id) + try { + return block(server) + } catch (e: Exception) { + if (!server.automatic || !isStale(e)) throw e + refresh() + val fresh = current(server.id) ?: throw e + // Judged for this id alone, from the values used: a probe refresh that already + // replaced them still earns the retry, and another app's change does not. + if (fresh.url == server.url && token(server.id) == usedToken) throw e + return block(fresh) + } + } + + companion object { + fun isStale(e: Throwable): Boolean = when (e) { + is ConnectException -> true + is McpHttpException -> e.statusCode == 401 || e.statusCode == 403 + else -> false + } + } +} diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReadOnlyTrust.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReadOnlyTrust.kt new file mode 100644 index 000000000..d19cae5b1 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReadOnlyTrust.kt @@ -0,0 +1,33 @@ +package com.itsaky.androidide.plugins.aiagentmcp.debugger + +import com.itsaky.androidide.plugins.aiagentmcp.client.McpTool + +/** + * Which tools of the automatic debugger entry start switched on, and which this plugin declares read-only. + * + * Declaring a tool read-only does not skip the approval dialog today: AI-Core overrides + * `requiresApproval` to true for every contributed tool (`ContributedToolHandler`), so the Agent still + * asks on each call until automatic approval exists (ADFA-7147). + * + * Only that entry may use this: the hint is the server's own claim, and the debugger endpoint is the + * one server whose code the IDE itself installed. A server the user adds by hand is never asked. + */ +object ReadOnlyTrust { + + /** + * @param tools what `tools/list` returned. + * @return the names of the tools that declared `annotations.readOnlyHint` as boolean true. + */ + fun enabledTools(tools: List): Set = + tools.filter { it.readOnlyHint }.mapTo(linkedSetOf()) { it.name } + + /** + * Reads the hint from one `tools/list` entry's `annotations`. + * + * Exactly boolean true counts. The string "true", 1, false, null and a missing key do not: an + * approval skipped on a loose reading (once AI-Core honours the declaration) cannot be taken back. + * + * @param hint the value under `readOnlyHint`, or null when absent. + */ + fun isReadOnlyHint(hint: Any?): Boolean = hint == true +} diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt index e3f00c588..4333f9fe9 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt @@ -5,6 +5,8 @@ import com.itsaky.androidide.plugins.PluginContext import com.itsaky.androidide.plugins.PluginLifecycleListener import com.itsaky.androidide.plugins.aiagentmcp.R import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticServers +import com.itsaky.androidide.plugins.aiagentmcp.debugger.McpServers import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore import com.itsaky.androidide.plugins.aiagentmcp.settings.McpSettingsFragment import com.itsaky.androidide.plugins.aiagentmcp.tools.McpServerHealth @@ -15,6 +17,7 @@ import com.itsaky.androidide.plugins.extensions.PluginSettingsEntry import com.itsaky.androidide.plugins.extensions.PluginTooltipButton import com.itsaky.androidide.plugins.extensions.PluginTooltipEntry import com.itsaky.androidide.plugins.extensions.SettingsExtension +import com.itsaky.androidide.plugins.services.DebuggerEndpointService import com.itsaky.androidide.plugins.services.SharedServices import com.itsaky.androidide.plugins.services.ToolSourceRegistry import kotlinx.coroutines.CoroutineScope @@ -159,6 +162,20 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { } } + /** + * Lists an automatic entry's tools as soon as its endpoint appears or changes, so a relaunched + * app's next call does not wait for the probe's cadence. + */ + private val relistAutomatic: (String) -> Unit = { id -> + scope.launch { + val server = McpServers.all().firstOrNull { it.id == id && it.enabled } + if (server != null) { + runCatching { McpToolCatalog.connect(server) } + if (isActive) settingsChanged() + } + } + } + override fun initialize(context: PluginContext): Boolean { this.context = context pluginContext = context @@ -174,6 +191,7 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { activationJob = active.coroutineContext[Job] toolSource = McpToolSource() McpServerStore.addChangeListener(settingsChanged) + AutomaticServers.addChangeListener(settingsChanged) McpServerHealth.addChangeListener(healthChanged) context.addPluginLifecycleListener(aiCoreLifecycle) @@ -184,6 +202,10 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { // Tool lists are answered from cache, so the cache has to be filled before the user opens // the Agent — otherwise the first cold-start session sees no MCP tools at all. active.launch { + // Off the main thread: the host reads its database. Before refreshAll, so the entry is + // connected like any other. + installDebuggerEndpoints() + AutomaticServers.addEndpointListener(relistAutomatic) val refreshed = McpToolCatalog.refreshAll { isActive } if (refreshed > 0 && isActive) settingsChanged() probeHealth { isActive } @@ -197,6 +219,8 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { override fun deactivate(): Boolean = try { context.removePluginLifecycleListener(aiCoreLifecycle) McpServerStore.removeChangeListener(settingsChanged) + AutomaticServers.removeChangeListener(settingsChanged) + AutomaticServers.removeEndpointListener(relistAutomatic) McpServerHealth.removeChangeListener(healthChanged) unregisterToolSource() // Before the connections are closed: an in-flight refresh would otherwise repopulate the @@ -212,6 +236,8 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { override fun dispose() { runCatching { context.removePluginLifecycleListener(aiCoreLifecycle) } McpServerStore.removeChangeListener(settingsChanged) + AutomaticServers.removeChangeListener(settingsChanged) + AutomaticServers.removeEndpointListener(relistAutomatic) McpServerHealth.removeChangeListener(healthChanged) unregisterToolSource() stopScope() @@ -237,7 +263,8 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { while (keepGoing()) { delay(PROBE_INTERVAL_MS) cycle++ - val due = McpServerStore.servers().filter { server -> + if (AutomaticServers.refresh()) settingsChanged() + val due = McpServers.all().filter { server -> val health = McpServerHealth.of(server.id) server.enabled && health?.refused != true && (cycle % HEALTHY_PROBE_EVERY == 0 || health?.state != McpServerHealth.State.AVAILABLE) @@ -258,6 +285,27 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { } } + /** + * Points [AutomaticServers] at the host's debugger endpoints. + * + * `plugin.min_ide_version` keeps this plugin off an IDE that lacks the service: such an IDE + * rejects the unknown `debugger.endpoints` permission when it validates the manifest. The catch + * is defence only, for a host that registers no service anyway. A call that later throws (no + * permission, unreadable database) leaves the entries as they were. + */ + private fun installDebuggerEndpoints() { + val service = try { + context.services.get(DebuggerEndpointService::class.java) + } catch (e: Throwable) { + null + } + if (service == null) { + context.logger.info("McpPlugin: this IDE has no debugger endpoint service") + return + } + AutomaticServers.install(AutomaticServers.fromHost { service.endpoints }) + } + /** A fresh scope for this activation; the previous one is cancelled, never reused. */ private fun newScope() = CoroutineScope(SupervisorJob() + Dispatchers.IO) @@ -353,6 +401,7 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { toolSource = null McpConnections.closeAll() McpToolCatalog.clear() + AutomaticServers.install(null) } /** diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServer.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServer.kt index be60ecf21..eb29222ea 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServer.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServer.kt @@ -13,6 +13,8 @@ package com.itsaky.androidide.plugins.aiagentmcp.settings * @property knownTools the tool names last seen on this server, for the toggle list. * @property enabledTools the tools the user switched on; empty is the default, so a new server * contributes nothing until its tools are chosen deliberately. + * @property automatic true for the entry Code on the Go supplies for a debuggable app: never + * stored, no Keystore token, and the only kind whose read-only tools start on. */ data class McpServer( val id: String, @@ -21,6 +23,7 @@ data class McpServer( val enabled: Boolean = true, val knownTools: List = emptyList(), val enabledTools: Set = emptySet(), + val automatic: Boolean = false, ) { /** The tools that should actually be offered to the agent right now. */ val activeTools: List diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt index 8fbb514db..45eab5c04 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt @@ -4,6 +4,9 @@ import android.util.Log import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections import com.itsaky.androidide.plugins.aiagentmcp.client.McpProtocolException import com.itsaky.androidide.plugins.aiagentmcp.client.McpTool +import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticServers +import com.itsaky.androidide.plugins.aiagentmcp.debugger.EndpointRetry +import com.itsaky.androidide.plugins.aiagentmcp.debugger.McpServers import com.itsaky.androidide.plugins.aiagentmcp.errors.McpErrorFormatter import com.itsaky.androidide.plugins.aiagentmcp.errors.McpFailure import com.itsaky.androidide.plugins.aiagentmcp.logging.LOG_PREFIX @@ -27,6 +30,13 @@ object McpToolCatalog { private val toolsByServer = ConcurrentHashMap>() + /** Re-reads an automatic entry's endpoint and tries once more when the stored one is stale. */ + val retry = EndpointRetry( + refresh = AutomaticServers::refresh, + current = { id -> AutomaticServers.servers().firstOrNull { it.id == id } }, + token = AutomaticServers::token, + ) + /** * The cached tools for a server. * @param serverId the server. @@ -61,7 +71,7 @@ object McpToolCatalog { ): Listing { McpServerHealth.connectingIfUnknown(server.id) val listing = try { - list(server, exchangeListener) + retry.call(server) { list(it, exchangeListener) } } catch (e: Throwable) { recordFailure(server, e) throw e @@ -91,10 +101,13 @@ object McpToolCatalog { } private fun isConfigured(serverId: String): Boolean = - McpServerStore.servers().any { it.id == serverId } + McpServers.all().any { it.id == serverId } /** The handshake-and-list itself; see [connect]. */ private fun list(server: McpServer, exchangeListener: McpExchangeListener): Listing { + // Taken before the request: if the endpoint is replaced while this list is in flight, the + // list is the old process's and must not be attached to the new one. + val origin = if (server.automatic) AutomaticServers.endpoint(server.id) else null // Kept, not just its tools: the name the handshake returned lands on the session. val session = McpConnections.session(server) val tools = session.recording(exchangeListener) { @@ -108,8 +121,18 @@ object McpToolCatalog { emptyList() } } - toolsByServer[server.id] = tools - McpServerStore.setKnownTools(server.id, tools.map { it.name }) + if (server.automatic) { + val current = origin != null && AutomaticServers.urlFor(origin) == server.url && + AutomaticServers.recordTools(server.id, origin, tools) + if (!current) { + Log.i(TAG, "Dropping a tool list from an endpoint '${server.name}' has since left") + return Listing(session.serverName, tools) + } + toolsByServer[server.id] = tools + } else { + toolsByServer[server.id] = tools + McpServerStore.setKnownTools(server.id, tools.map { it.name }) + } Log.i(TAG, "Server '${server.name}' listed ${tools.size} tool(s)") return Listing(session.serverName, tools) } @@ -128,7 +151,7 @@ object McpToolCatalog { */ fun refreshAll(keepGoing: () -> Boolean = { true }): Int { var refreshed = 0 - for (server in McpServerStore.servers().filter { it.enabled }) { + for (server in McpServers.all().filter { it.enabled }) { if (!keepGoing()) { Log.i(TAG, "Stopped refreshing tool lists; the caller is gone") break diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt index f4e04bf39..010634ccf 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt @@ -4,12 +4,12 @@ import android.util.Log import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections import com.itsaky.androidide.plugins.aiagentmcp.client.McpSession import com.itsaky.androidide.plugins.aiagentmcp.client.McpTool +import com.itsaky.androidide.plugins.aiagentmcp.debugger.McpServers import com.itsaky.androidide.plugins.aiagentmcp.errors.McpErrorFormatter import com.itsaky.androidide.plugins.aiagentmcp.R import com.itsaky.androidide.plugins.aiagentmcp.logging.LOG_PREFIX import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServer -import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore import com.itsaky.androidide.plugins.services.CapabilityStatus import com.itsaky.androidide.plugins.services.ToolSourceRegistry import java.util.concurrent.CompletableFuture @@ -59,6 +59,7 @@ class McpToolSource : name = exposed.name, description = exposed.tool.description, parametersSchema = exposed.tool.inputSchema, + preApproved = exposed.server.automatic && exposed.tool.readOnlyHint, ) } @@ -68,7 +69,7 @@ class McpToolSource : */ override fun getToolGroups(): List { val namesByServer = exposedTools().groupBy({ it.server.id }, { it.name }) - return McpServerStore.servers().filter { it.enabled }.map { server -> + return McpServers.all().filter { it.enabled }.map { server -> Group( id = server.id, displayName = server.name, @@ -93,7 +94,7 @@ class McpToolSource : enabledHealth().firstOrNull { it?.state == McpServerHealth.State.DEGRADED }?.message private fun enabledHealth(): List = - McpServerStore.servers().filter { it.enabled }.map { McpServerHealth.of(it.id) } + McpServers.all().filter { it.enabled }.map { McpServerHealth.of(it.id) } override fun invoke( invocation: ToolSourceRegistry.ToolInvocation, @@ -140,12 +141,14 @@ class McpToolSource : tool: McpTool, arguments: Map, ): ToolSourceRegistry.ToolOutcome = try { - val session = McpConnections.session(server) - liveSessions[callId] = session - val result = try { - session.callTool(tool.name, arguments) - } finally { - liveSessions.remove(callId) + val result = McpToolCatalog.retry.call(server) { target -> + val session = McpConnections.session(target) + liveSessions[callId] = session + try { + session.callTool(tool.name, arguments) + } finally { + liveSessions.remove(callId) + } } // A reply of any kind, a tool's own failure included, means the server is answering. McpServerHealth.available(server.id) @@ -172,7 +175,7 @@ class McpToolSource : * @return the pairs, in configured order. */ private fun enabledTools(): List> = - McpServerStore.servers() + McpServers.all() .filter { it.enabled } .flatMap { server -> McpToolCatalog.tools(server.id) @@ -231,21 +234,26 @@ class McpToolSource : /** * One tool, as the host contract describes it. * - * Every remote tool asks for approval and declares itself non-read-only: this plugin cannot + * Every remote tool declares that it requires approval and is not read-only: this plugin cannot * know what a server's tool does, and guessing on the permissive side is the one guess that - * cannot be undone. The contract is a Java interface, so its accessors are implemented as + * cannot be undone. The one exception is [preApproved]: a readOnlyHint tool of the automatic + * debugger entry, whose server Code on the Go itself installed, declares no approval needed. + * That is a declaration only: AI-Core currently overrides `requiresApproval` to true for every + * contributed tool (`ContributedToolHandler`), so the Agent still asks on each call. Honouring + * the declaration is tracked in ADFA-7147. The contract is a Java interface, so its accessors are implemented as * functions: Kotlin synthesises properties for *reading* a Java getter, never for overriding one. */ private class Spec( private val name: String, private val description: String, private val parametersSchema: Map, + private val preApproved: Boolean = false, ) : ToolSourceRegistry.ToolSpec { override fun getName(): String = name override fun getDescription(): String = description override fun getParametersSchema(): Map = parametersSchema - override fun requiresApproval(): Boolean = true - override fun isReadOnly(): Boolean = false + override fun requiresApproval(): Boolean = !preApproved + override fun isReadOnly(): Boolean = preApproved } /** diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServersTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServersTest.kt new file mode 100644 index 000000000..e313a7f11 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServersTest.kt @@ -0,0 +1,182 @@ +package com.itsaky.androidide.plugins.aiagentmcp.debugger + +import com.itsaky.androidide.plugins.aiagentmcp.client.McpTool +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpServerHealth +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpToolCatalog +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class AutomaticServersTest { + + @After + fun reset() = AutomaticServers.install(null) + + private fun endpoint(app: String = "com.example.app", port: Int = 4000, token: String = "t1") = + AutomaticEndpoint(app, port, token) + + @Test + fun `no endpoint means no entry and no error`() { + AutomaticServers.install { emptyList() } + assertTrue(AutomaticServers.servers().isEmpty()) + assertTrue(McpServers.all().isEmpty()) + } + + @Test + fun `a host that refuses or lacks the service means no entry and no error`() { + AutomaticServers.install { throw SecurityException("no permission") } + assertTrue(AutomaticServers.servers().isEmpty()) + } + + @Test + fun `an endpoint becomes a loopback entry with its token held in memory`() { + AutomaticServers.install { listOf(endpoint(port = 4321, token = "secret")) } + + val server = AutomaticServers.servers().single() + assertEquals("http://127.0.0.1:4321/mcp", server.url) + assertTrue(server.automatic) + assertTrue(server.enabled) + assertEquals("secret", AutomaticServers.token(server.id)) + assertFalse("secret" in server.toString()) + } + + @Test + fun `the entry disappears when the app stops reporting`() { + var current = listOf(endpoint()) + AutomaticServers.install { current } + assertEquals(1, AutomaticServers.servers().size) + + current = emptyList() + assertTrue(AutomaticServers.refresh()) + assertTrue(AutomaticServers.servers().isEmpty()) + } + + @Test + fun `refresh reports a change only when port or token differ`() { + var current = listOf(endpoint()) + AutomaticServers.install { current } + assertFalse(AutomaticServers.refresh()) + + current = listOf(endpoint(port = 4001)) + assertTrue(AutomaticServers.refresh()) + current = listOf(endpoint(port = 4001, token = "t2")) + assertTrue(AutomaticServers.refresh()) + assertEquals("t2", AutomaticServers.token(AutomaticServers.idFor("com.example.app"))) + } + + @Test + fun `a relaunch keeps the old tools and switches until the new process lists`() { + var current = listOf(endpoint()) + AutomaticServers.install { current } + val id = AutomaticServers.idFor("com.example.app") + AutomaticServers.recordTools(id, endpoint(), listOf(McpTool("q", "", readOnlyHint = true))) + + current = listOf(endpoint(port = 4002)) + AutomaticServers.refresh() + + val server = AutomaticServers.servers().single() + assertEquals(listOf("q"), server.knownTools) + assertEquals(setOf("q"), server.enabledTools) + assertTrue(server.url.endsWith(":4002/mcp")) + } + + @Test + fun `a relaunch asks the owner to list the new endpoint at once`() { + var current = listOf(endpoint()) + val asked = mutableListOf() + AutomaticServers.install { current } + AutomaticServers.addEndpointListener { asked += it } + + assertFalse(AutomaticServers.refresh()) + assertTrue(asked.isEmpty()) + + current = listOf(endpoint(port = 4002, token = "t2")) + AutomaticServers.refresh() + assertEquals(listOf(AutomaticServers.idFor("com.example.app")), asked) + } + + @Test + fun `a relaunch lets the probe ask an entry that had refused its credential`() { + var current = listOf(endpoint()) + AutomaticServers.install { current } + val id = AutomaticServers.idFor("com.example.app") + McpServerHealth.degraded(id, "refused", refused = true) + + current = listOf(endpoint(token = "t2")) + AutomaticServers.refresh() + assertFalse(McpServerHealth.of(id)!!.refused) + McpServerHealth.forget(id) + } + + @Test + fun `a tool list fetched from a replaced endpoint is dropped`() { + var current = listOf(endpoint()) + AutomaticServers.install { current } + val id = AutomaticServers.idFor("com.example.app") + val old = endpoint() + AutomaticServers.recordTools(id, old, listOf(McpTool("fresh", ""))) + + current = listOf(endpoint(port = 4002)) + AutomaticServers.refresh() + assertFalse(AutomaticServers.recordTools(id, old, listOf(McpTool("stale", "")))) + + assertEquals(listOf("fresh"), AutomaticServers.servers().single().knownTools) + assertTrue(AutomaticServers.recordTools(id, endpoint(port = 4002), listOf(McpTool("newer", "")))) + assertEquals(listOf("newer"), AutomaticServers.servers().single().knownTools) + } + + @Test + fun `a failed read keeps the entries as they were`() { + var failing = false + AutomaticServers.install { + if (failing) throw IllegalStateException("db closed") + listOf(endpoint()) + } + val id = AutomaticServers.idFor("com.example.app") + AutomaticServers.recordTools(id, endpoint(), listOf(McpTool("q", "", readOnlyHint = true))) + + failing = true + assertFalse(AutomaticServers.refresh()) + + val server = AutomaticServers.servers().single() + assertEquals(listOf("q"), server.knownTools) + assertEquals("t1", AutomaticServers.token(id)) + } + + @Test + fun `an entry that disappears has its health and cached tools forgotten`() { + var current = listOf(endpoint()) + AutomaticServers.install { current } + val id = AutomaticServers.idFor("com.example.app") + McpServerHealth.available(id) + + current = emptyList() + AutomaticServers.refresh() + + assertNull(McpServerHealth.of(id)) + assertTrue(McpToolCatalog.tools(id).isEmpty()) + } + + @Test + fun `only readOnlyHint tools of the automatic entry start on`() { + AutomaticServers.install { listOf(endpoint()) } + val id = AutomaticServers.idFor("com.example.app") + AutomaticServers.recordTools( + id, + endpoint(), + listOf( + McpTool("reads", "", readOnlyHint = true), + McpTool("writes", "", readOnlyHint = false), + McpTool("unmarked", ""), + ), + ) + + val server = AutomaticServers.servers().single() + assertEquals(listOf("reads", "writes", "unmarked"), server.knownTools) + assertEquals(setOf("reads"), server.enabledTools) + assertEquals(listOf("reads"), server.activeTools) + } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/EndpointRetryTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/EndpointRetryTest.kt new file mode 100644 index 000000000..bbb66d403 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/EndpointRetryTest.kt @@ -0,0 +1,142 @@ +package com.itsaky.androidide.plugins.aiagentmcp.debugger + +import com.itsaky.androidide.plugins.aiagentmcp.client.McpProtocolException +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServer +import com.itsaky.androidide.plugins.aiagentmcp.transport.McpHttpException +import java.net.ConnectException +import java.net.SocketTimeoutException +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertThrows +import org.junit.Test + +class EndpointRetryTest { + + private val app = "com.example.app" + private var stored = listOf(AutomaticEndpoint(app, 1111, "old")) + private val retry = EndpointRetry( + refresh = AutomaticServers::refresh, + current = { id -> AutomaticServers.servers().firstOrNull { it.id == id } }, + token = AutomaticServers::token, + ) + + init { + AutomaticServers.install { stored } + } + + @After + fun reset() = AutomaticServers.install(null) + + private fun server() = AutomaticServers.servers().single() + + @Test + fun `a refused first connect uses the refreshed endpoint on retry`() { + val urls = mutableListOf() + val first = server() + stored = listOf(AutomaticEndpoint(app, 2222, "new")) + + val result = retry.call(first) { s -> + urls += s.url + if (s.url.endsWith(":1111/mcp")) throw ConnectException("refused") + "ok:" + AutomaticServers.token(s.id) + } + + assertEquals("ok:new", result) + assertEquals(listOf("http://127.0.0.1:1111/mcp", "http://127.0.0.1:2222/mcp"), urls) + } + + @Test + fun `401 and 403 also refresh`() { + for (failure in listOf(McpHttpException(401, ""), McpHttpException(403, ""))) { + stored = listOf(AutomaticEndpoint(app, 1111, "old")) + AutomaticServers.install { stored } + val first = server() + stored = listOf(AutomaticEndpoint(app, 3333, "n")) + var calls = 0 + val out = retry.call(first) { s -> calls++; if (calls == 1) throw failure else s.url } + assertEquals("http://127.0.0.1:3333/mcp", out) + } + } + + @Test + fun `a timeout is not retried, so a slow call is not run twice`() { + val first = server() + stored = listOf(AutomaticEndpoint(app, 3333, "n")) + var calls = 0 + assertThrows(SocketTimeoutException::class.java) { + retry.call(first) { calls++; throw SocketTimeoutException("read timed out") } + } + assertEquals(1, calls) + } + + @Test + fun `a credential a concurrent refresh already replaced is still retried`() { + val first = server() + var calls = 0 + val out = retry.call(first) { s -> + calls++ + if (calls == 1) { + // The probe's refresh lands while this call is in flight, so the retry's own + // refresh sees nothing new. + stored = listOf(AutomaticEndpoint(app, 1111, "rotated")) + AutomaticServers.refresh() + throw McpHttpException(401, "") + } + "retried:" + AutomaticServers.token(s.id) + } + assertEquals("retried:rotated", out) + assertEquals(2, calls) + } + + @Test + fun `another app's change does not cause a retry`() { + stored = listOf(AutomaticEndpoint(app, 1111, "old"), AutomaticEndpoint("com.example.other", 9000, "o1")) + AutomaticServers.install { stored } + val mine = AutomaticServers.servers().first { it.id == AutomaticServers.idFor(app) } + stored = listOf(AutomaticEndpoint(app, 1111, "old"), AutomaticEndpoint("com.example.other", 9001, "o2")) + var calls = 0 + assertThrows(ConnectException::class.java) { + retry.call(mine) { calls++; throw ConnectException("refused") } + } + assertEquals(1, calls) + } + + @Test + fun `an unchanged endpoint is not asked twice`() { + var calls = 0 + assertThrows(ConnectException::class.java) { + retry.call(server()) { calls++; throw ConnectException("refused") } + } + assertEquals(1, calls) + } + + @Test + fun `an app that is gone surfaces the original failure`() { + val first = server() + stored = emptyList() + assertThrows(ConnectException::class.java) { + retry.call(first) { throw ConnectException("refused") } + } + } + + @Test + fun `other failures are not retried`() { + stored = listOf(AutomaticEndpoint(app, 4444, "x")) + var calls = 0 + assertThrows(McpProtocolException::class.java) { + retry.call(server()) { calls++; throw McpProtocolException(-32000, "bad") } + } + assertEquals(1, calls) + } + + @Test + fun `a hand-added server is never retried through the endpoint source`() { + val handAdded = McpServer("h", "mine", "http://127.0.0.1:1111/mcp") + stored = listOf(AutomaticEndpoint(app, 5555, "x")) + var calls = 0 + assertThrows(ConnectException::class.java) { + retry.call(handAdded) { calls++; throw ConnectException("refused") } + } + assertEquals(1, calls) + } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReadOnlyHintParsingTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReadOnlyHintParsingTest.kt new file mode 100644 index 000000000..dc940d7c4 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReadOnlyHintParsingTest.kt @@ -0,0 +1,66 @@ +package com.itsaky.androidide.plugins.aiagentmcp.debugger + +import com.itsaky.androidide.plugins.aiagentmcp.client.McpSession +import com.itsaky.androidide.plugins.aiagentmcp.client.McpTool +import com.itsaky.androidide.plugins.aiagentmcp.transport.McpExchangeListener +import com.itsaky.androidide.plugins.aiagentmcp.transport.McpHttpClient +import java.net.HttpURLConnection +import org.json.JSONArray +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** The rule is read from a real `tools/list` reply, so the JSON types are the ones a server sends. */ +class ReadOnlyHintParsingTest { + + private fun listed(annotations: Any?, present: Boolean = true): McpTool { + val tool = JSONObject().put("name", "t") + if (present) tool.put("annotations", annotations) + val http = object : McpHttpClient() { + override fun post( + url: String, + token: String, + body: JSONObject, + sessionId: String?, + protocolVersion: String?, + extraHeaders: Map, + onConnected: (HttpURLConnection) -> Unit, + exchangeListener: McpExchangeListener, + ): Response { + val result = when (body.optString("method")) { + "initialize" -> JSONObject().put("protocolVersion", "2026-07-28") + "tools/list" -> JSONObject().put("tools", JSONArray().put(tool)) + else -> return Response(null, null) + } + val reply = JSONObject().put("jsonrpc", "2.0").put("id", body.opt("id")).put("result", result) + return Response(reply.toString(), null) + } + } + return McpSession("http://127.0.0.1:1/mcp", { com.itsaky.androidide.plugins.aiagentmcp.client.McpCredentials("", emptyMap()) }, http) + .listTools().single() + } + + private fun hint(value: Any?) = listed(JSONObject().put("readOnlyHint", value)) + + @Test fun `boolean true is read only`() = assertTrue(hint(true).readOnlyHint) + + @Test fun `boolean false is not`() = assertFalse(hint(false).readOnlyHint) + + @Test fun `missing hint is not`() = assertFalse(listed(JSONObject()).readOnlyHint) + + @Test fun `missing annotations is not`() = assertFalse(listed(null, present = false).readOnlyHint) + + @Test fun `string true is not`() = assertFalse(hint("true").readOnlyHint) + + @Test fun `number one is not`() = assertFalse(hint(1).readOnlyHint) + + @Test fun `json null is not`() = assertFalse(hint(JSONObject.NULL).readOnlyHint) + + @Test + fun `trust enables exactly the true ones`() { + val tools = listOf(McpTool("a", "", readOnlyHint = true), McpTool("b", "")) + assertEquals(setOf("a"), ReadOnlyTrust.enabledTools(tools)) + } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/RelaunchToolSourceTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/RelaunchToolSourceTest.kt new file mode 100644 index 000000000..a0b33707e --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/RelaunchToolSourceTest.kt @@ -0,0 +1,122 @@ +package com.itsaky.androidide.plugins.aiagentmcp.debugger + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpToolCatalog +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpToolSource +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import com.itsaky.androidide.plugins.services.ToolSourceRegistry +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import java.util.concurrent.TimeUnit +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** What the agent is offered, driven through [McpToolSource] against loopback servers. */ +class RelaunchToolSourceTest { + + private val app = "com.example.app" + private val servers = mutableListOf() + private val source = McpToolSource() + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + // The Keystore is not there on the JVM; a hand-added server in these tests has no secrets. + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } returns KeystoreSecretStore.Stored.Absent + every { McpServerStore.headers(any()) } returns emptyMap() + } + + @After + fun tearDown() { + source.close() + AutomaticServers.install(null) + McpConnections.closeAll() + McpToolCatalog.clear() + servers.forEach { it.stop() } + plugin.dispose() + unmockkObject(McpServerStore) + } + + private fun fake(token: String, vararg tools: org.json.JSONObject) = + FakeMcpServer(token, tools.toList()).also { servers += it } + + private fun offered(): Map = + source.listTools().associateBy { it.name } + + private fun invoke(name: String): ToolSourceRegistry.ToolOutcome = + source.invoke( + mockk { + every { toolName } returns name + every { arguments } returns emptyMap() + every { callId } returns "call-1" + } + ).get(30, TimeUnit.SECONDS) + + private fun debuggerTools() = arrayOf(tool("list_tables", true), tool("run_sql", false), tool("unmarked", null)) + + @Test + fun `a relaunch keeps the read-only tools offered and the next call reaches the new endpoint`() { + val first = fake("t1", *debuggerTools()) + var stored = listOf(AutomaticEndpoint(app, first.port, "t1")) + AutomaticServers.install { stored } + McpToolCatalog.connect(AutomaticServers.servers().single()) + val before = offered() + assertEquals(1, before.size) + val name = before.keys.single() + + val second = fake("t2", *debuggerTools()) + stored = listOf(AutomaticEndpoint(app, second.port, "t2")) + assertTrue(AutomaticServers.refresh()) + + // No re-list has happened yet: the agent must not lose its tools meanwhile. + assertEquals(setOf(name), offered().keys) + val outcome = invoke(name) + assertTrue(outcome.errorMessage, outcome.isSuccess) + assertEquals("served by ${second.port}", outcome.output) + } + + @Test + fun `an automatic entry's read-only tool is pre-approved and the others are not offered`() { + val server = fake("t1", *debuggerTools()) + AutomaticServers.install { listOf(AutomaticEndpoint(app, server.port, "t1")) } + McpToolCatalog.connect(AutomaticServers.servers().single()) + + val spec = offered().values.single() + assertTrue(spec.name.endsWith("list_tables")) + assertFalse(spec.requiresApproval()) + assertTrue(spec.isReadOnly) + } + + @Test + fun `a hand-added server claiming readOnlyHint is off by default and asks once switched on`() { + val server = fake("", tool("claims", true)) + val handAdded = McpServerStore.saveDetails( + McpServerStore.newServer("Mine", "http://127.0.0.1:${server.port}/mcp") + ) + McpToolCatalog.connect(handAdded) + assertTrue(McpToolCatalog.tools(handAdded.id).single().readOnlyHint) + + assertTrue(offered().isEmpty()) + + McpServerStore.setToolEnabled(handAdded.id, "claims", true) + val spec = offered().values.single() + assertTrue(spec.requiresApproval()) + assertFalse(spec.isReadOnly) + } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/RepeatedFailureLogTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/RepeatedFailureLogTest.kt new file mode 100644 index 000000000..4b75f36f6 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/RepeatedFailureLogTest.kt @@ -0,0 +1,23 @@ +package com.itsaky.androidide.plugins.aiagentmcp.debugger + +import org.junit.Assert.assertEquals +import org.junit.Test + +class RepeatedFailureLogTest { + @Test + fun `the first failure is reported in full and the repeats briefly`() { + val full = mutableListOf() + val brief = mutableListOf() + val log = RepeatedFailureLog(first = { full += it }, later = { brief += it }) + val a = SecurityException("a") + val b = SecurityException("b") + val c = IllegalStateException("c") + + log.report(a) + log.report(b) + log.report(c) + + assertEquals(listOf(a), full) + assertEquals(listOf(b, c), brief) + } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/testing/FakeMcpServer.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/testing/FakeMcpServer.kt new file mode 100644 index 000000000..8cfa7c223 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/testing/FakeMcpServer.kt @@ -0,0 +1,59 @@ +package com.itsaky.androidide.plugins.aiagentmcp.testing + +import com.sun.net.httpserver.HttpServer +import java.net.InetSocketAddress +import org.json.JSONArray +import org.json.JSONObject + +/** + * A loopback MCP server for tests: answers the handshake, `tools/list` and `tools/call` over + * plain JSON, and 401 unless the bearer token is [token] (any request when it is empty). A call's text names the port that served + * it, so a test can tell which endpoint a call reached. + * + * @param tools the `tools/list` entries. + */ +class FakeMcpServer(val token: String, private val tools: List) { + + private val server: HttpServer = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply { + createContext("/mcp") { exchange -> + val request = JSONObject(exchange.requestBody.use { String(it.readBytes()) }) + val id = request.opt("id") + if (token.isNotEmpty() && exchange.requestHeaders.getFirst("Authorization") != "Bearer $token") { + exchange.sendResponseHeaders(401, -1) + } else if (id == null) { + exchange.sendResponseHeaders(202, -1) + } else { + val result = when (request.getString("method")) { + "initialize" -> JSONObject() + .put("protocolVersion", "2025-03-26") + .put("serverInfo", JSONObject().put("name", "fake")) + "tools/list" -> JSONObject().put("tools", JSONArray(tools)) + "tools/call" -> JSONObject().put( + "content", + JSONArray().put(JSONObject().put("type", "text").put("text", "served by $port")), + ) + else -> JSONObject() + } + val bytes = JSONObject().put("jsonrpc", "2.0").put("id", id).put("result", result) + .toString().toByteArray() + exchange.responseHeaders.add("Content-Type", "application/json") + exchange.sendResponseHeaders(200, bytes.size.toLong()) + exchange.responseBody.use { it.write(bytes) } + } + exchange.close() + } + start() + } + + val port: Int get() = server.address.port + + fun stop() = server.stop(0) + + companion object { + fun tool(name: String, readOnlyHint: Boolean?): JSONObject = JSONObject() + .put("name", name) + .put("description", name) + .put("inputSchema", JSONObject().put("type", "object")) + .also { if (readOnlyHint != null) it.put("annotations", JSONObject().put("readOnlyHint", readOnlyHint)) } + } +} From aa490b601d7b7262eaa51ab1cb6d5c75c7c9d228 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 15 Nov 2026 21:37:08 -0800 Subject: [PATCH 03/90] ADFA-7139 AI-Agent-MCP: document the debugger entry The plugin README and the plugin's help page describe the automatic SQLite debugger entry, its read-only tool rule and the approval prompt. plugins/README.md lists debugger.endpoints among the permissions and says a plugin declaring it needs plugin.min_ide_version of at least 26.43. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- plugins/AI-Agent-MCP/README.md | 30 +++++++++++++++++++++++--- plugins/AI-Agent-MCP/ai-agent-mcp.html | 3 ++- plugins/README.md | 4 +++- 3 files changed, 32 insertions(+), 5 deletions(-) diff --git a/plugins/AI-Agent-MCP/README.md b/plugins/AI-Agent-MCP/README.md index 50a6d7788..ec74f1854 100644 --- a/plugins/AI-Agent-MCP/README.md +++ b/plugins/AI-Agent-MCP/README.md @@ -36,7 +36,8 @@ Configuration → MCP servers**: 1. **Add server** — name, endpoint URL, optional token. 2. **Connect** — saves the server, performs the MCP handshake and lists the tools it offers, all in one step. -3. Switch on the tools you want. **They start off**: one popular GitHub server +3. Switch on the tools you want. **They start off** (except the read-only tools + of the automatic debugger entry, below): one popular GitHub server advertises around ninety tools, which would fill a phone-sized context window on its own. 4. **Clear stored credential** — removes the stored token and headers. The token @@ -47,6 +48,26 @@ Every remote tool asks for approval on every call, and there is no "always allow" for contributed tools — they run outside the Agent's own path containment, so the dialog is the only gate. +### The SQLite debugger entry + +For an app built in Code on the Go with `cogo.sqliteDebugger=true`, the plugin +adds a server entry on its own, named "SQLite debugger ()", with +no URL or token to type. Code on the Go stores the port and token the running +debug app reports; the plugin reads them through the `DebuggerEndpointService` +(permission `debugger.endpoints`, so it needs Code on the Go 26.43 or later) and +points the entry at `http://127.0.0.1:/mcp`. A relaunched app gets a new +port and token, and the plugin reads them again after a refused connection. An +app that has not reported yet has no entry, and no error is shown. + +- It is held in memory only and is **not shown in the settings screen in this + version**, so there is no switch to turn it off there. +- The tools that declare MCP's `readOnlyHint: true` start switched **on**. Any + other tool of that entry starts off. The hint is trusted for this entry only, + never for a server you add yourself. +- The Agent still asks for approval on every call: AI-Core makes every + contributed tool ask (it ignores the tool's own `requiresApproval`). Approving + read-only calls automatically is tracked in ADFA-7147. + ## Transport MCP's **Streamable HTTP** transport over `HttpURLConnection`: @@ -105,10 +126,13 @@ Two dependencies were deliberately not taken: - `http://` is accepted only for a server on this device (`localhost`, `127.0.0.0/8`, `[::1]`), with or without credentials; any other host needs `https://`, since its traffic would cross a network in the clear. The check is `McpUrlPolicy`, built on - the host's `ServerUrl` (plugin-api **26.42**, hence this plugin's - `min_ide_version`), and judges the URL as typed with no DNS lookup. Save refuses + the host's `ServerUrl` (plugin-api 26.42), and judges the URL as typed with no DNS lookup. Save refuses such a URL, and the transport refuses it again, so a server saved before the rule is listed with a warning and never contacted until it is switched to `https://`. +- The plugin declares the `debugger.endpoints` permission, to offer the SQLite debugger of the + open project's app without typing a port or token. Code on the Go 26.42 and older reject an + unknown permission when they validate the manifest, so this version needs **26.43 or newer** + (`plugin.min_ide_version`); users on 26.42 or older cannot install it. - Redirects are never followed automatically. A 3xx is repeated only when it resolves to the same origin, so the bearer token and the user's own headers cannot be replayed to another host in one hop. diff --git a/plugins/AI-Agent-MCP/ai-agent-mcp.html b/plugins/AI-Agent-MCP/ai-agent-mcp.html index 5277617f4..92f0cf1ea 100644 --- a/plugins/AI-Agent-MCP/ai-agent-mcp.html +++ b/plugins/AI-Agent-MCP/ai-agent-mcp.html @@ -141,7 +141,8 @@

Usage

New tools always arrive switched off, including on the connection - that discovers them. Nothing a server adds later becomes visible to the model + that discovers them. The one exception is the read-only tools of the SQLite + debugger entry that Code on the Go supplies for your own debug app. Nothing a server adds later becomes visible to the model without your say-so.
diff --git a/plugins/README.md b/plugins/README.md index 2eb07e5c4..d6dc15178 100644 --- a/plugins/README.md +++ b/plugins/README.md @@ -148,7 +148,9 @@ A plugin is an Android *application* module (despite installing as a library) wi Available permission strings (declared comma-separated in `plugin.permissions`): `filesystem.read`, `filesystem.write`, `network.access`, `system.commands`, `ide.settings`, -`project.structure`. +`project.structure`, `native.code`, `ide.environment.write`, `debugger.endpoints`. An IDE rejects +a manifest that names a permission it does not know, so a plugin declaring `debugger.endpoints` +needs `plugin.min_ide_version` of at least 26.43. --- From 816e8cc80278ecd19d1b38b72eefa08363d4b01d Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 15 Nov 2026 23:17:33 -0800 Subject: [PATCH 04/90] ADFA-7139 AI-Agent-MCP: raise plugin.min_ide_version to 26.47, the first release with debugger.endpoints Code on the Go 26.43 to 26.46 are released and none carries PluginPermission.DEBUGGER_ENDPOINTS or DebuggerEndpointService. An unknown permission key does not only warn: PluginManager.loadPlugin (PluginManager.kt:568) calls PluginSecurityManager.validatePlugin, which returns false when validatePermissions (PluginSecurityManager.kt:50, :92) finds a key outside PluginPermission, and loadPlugin then fails with "plugin failed security validation". The same code is at tags 26.42 and 26.46 and on origin/stage. The warn-and-drop at PluginManager.kt:582 runs only after validation passed, so it never sees an unknown key from a manifest. 26.46 therefore rejects this plugin, and the floor must be the next release, 26.47 (26.46 was tagged 2026-11-10, weekly cadence). The manifest comment, plugin README and plugins/README.md say so. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- plugins/AI-Agent-MCP/README.md | 9 +++++---- plugins/AI-Agent-MCP/src/main/AndroidManifest.xml | 15 +++++++++------ plugins/README.md | 5 +++-- 3 files changed, 17 insertions(+), 12 deletions(-) diff --git a/plugins/AI-Agent-MCP/README.md b/plugins/AI-Agent-MCP/README.md index ec74f1854..3e1f4544c 100644 --- a/plugins/AI-Agent-MCP/README.md +++ b/plugins/AI-Agent-MCP/README.md @@ -54,7 +54,7 @@ For an app built in Code on the Go with `cogo.sqliteDebugger=true`, the plugin adds a server entry on its own, named "SQLite debugger ()", with no URL or token to type. Code on the Go stores the port and token the running debug app reports; the plugin reads them through the `DebuggerEndpointService` -(permission `debugger.endpoints`, so it needs Code on the Go 26.43 or later) and +(permission `debugger.endpoints`, so it needs Code on the Go 26.47 or later) and points the entry at `http://127.0.0.1:/mcp`. A relaunched app gets a new port and token, and the plugin reads them again after a refused connection. An app that has not reported yet has no entry, and no error is shown. @@ -130,9 +130,10 @@ Two dependencies were deliberately not taken: such a URL, and the transport refuses it again, so a server saved before the rule is listed with a warning and never contacted until it is switched to `https://`. - The plugin declares the `debugger.endpoints` permission, to offer the SQLite debugger of the - open project's app without typing a port or token. Code on the Go 26.42 and older reject an - unknown permission when they validate the manifest, so this version needs **26.43 or newer** - (`plugin.min_ide_version`); users on 26.42 or older cannot install it. + open project's app without typing a port or token. Code on the Go 26.46 and older reject a + manifest that names a permission they do not know (`PluginSecurityManager.validatePlugin`), so this + version needs **26.47 or newer**, the first release that ships `DebuggerEndpointService` + (`plugin.min_ide_version`); users on 26.46 or older cannot install it. - Redirects are never followed automatically. A 3xx is repeated only when it resolves to the same origin, so the bearer token and the user's own headers cannot be replayed to another host in one hop. diff --git a/plugins/AI-Agent-MCP/src/main/AndroidManifest.xml b/plugins/AI-Agent-MCP/src/main/AndroidManifest.xml index a41b06ca9..e1ed9f715 100644 --- a/plugins/AI-Agent-MCP/src/main/AndroidManifest.xml +++ b/plugins/AI-Agent-MCP/src/main/AndroidManifest.xml @@ -39,14 +39,17 @@ android:name="plugin.author" android:value="App Dev for All" /> - + + android:value="26.47" /> Date: Sun, 15 Nov 2026 23:17:33 -0800 Subject: [PATCH 05/90] ADFA-7139 AI-Agent-MCP: an activation that ends during the first endpoint read leaves nothing behind The host's database read blocks and cannot be cancelled. If the plugin was deactivated meanwhile, the old coroutine resumed, re-installed the endpoint source and added the endpoint listener, which nothing removed; a quick re-activate added it twice. Now the launch checks the activation before and after the read, install() keeps neither the source nor the entries of a finished activation, and deactivate removes the listener after the scope ends so a late add is caught. McpPluginDebuggerStartTest fails without this (a listener is left registered when the activation ended during the read) and passes with it; it also checks that a live activation adds one listener. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../aiagentmcp/debugger/AutomaticServers.kt | 34 +++++++- .../plugins/aiagentmcp/plugin/McpPlugin.kt | 30 +++++-- .../plugin/McpPluginDebuggerStartTest.kt | 81 +++++++++++++++++++ 3 files changed, 135 insertions(+), 10 deletions(-) create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginDebuggerStartTest.kt diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt index 89c997a7f..c899401be 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt @@ -61,10 +61,31 @@ object AutomaticServers { later = { e -> Log.d(TAG, "Still cannot read the debugger endpoints: $e") }, ) - /** Where endpoints come from; null (deactivation) clears every entry. */ + /** + * Where endpoints come from; null (deactivation) clears every entry. + * + * @param keepGoing false once the activation installing [source] is over. The first read blocks + * and cannot be cancelled, so an activation that ended during it must neither keep [source] + * nor publish what it read: deactivation has already cleared everything, and a later + * activation owns the state now. + */ fun install(source: (() -> List)?) { - this.source = source - if (source == null) clear() else refresh() + if (source == null) { + // Under the lock the other overload takes, so a late install cannot set its source after this. + synchronized(this) { this.source = null } + clear() + } else { + install(source) { true } + } + } + + /** As [install], for a source that may be superseded while its first read is blocked. */ + fun install(source: () -> List, keepGoing: () -> Boolean) { + synchronized(this) { + if (!keepGoing()) return + this.source = source + } + refresh(keepGoing) } /** Adapts the host's service. A host without the service, or without the permission, is no source. */ @@ -92,11 +113,15 @@ object AutomaticServers { endpointListeners.remove(listener) } + /** How many endpoint listeners are registered; a test seam for a listener nothing removes. */ + internal val endpointListenerCount: Int get() = endpointListeners.size + /** * Re-reads the endpoints. Blocking host call: use a background thread. + * @param keepGoing checked after the read, before anything is stored. * @return true when the set of entries, a port or a token changed. */ - fun refresh(): Boolean { + fun refresh(keepGoing: () -> Boolean = { true }): Boolean { val read = source ?: return false val fresh = try { read().associateBy { idFor(it.applicationId) } @@ -109,6 +134,7 @@ object AutomaticServers { val moved = mutableListOf() val removed: List val changed = synchronized(this) { + if (!keepGoing()) return false val old = states val next = fresh.mapValues { (id, endpoint) -> val previous = old[id] diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt index 4333f9fe9..3d4b2f953 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt @@ -204,8 +204,7 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { active.launch { // Off the main thread: the host reads its database. Before refreshAll, so the entry is // connected like any other. - installDebuggerEndpoints() - AutomaticServers.addEndpointListener(relistAutomatic) + startDebuggerEntry { isActive } val refreshed = McpToolCatalog.refreshAll { isActive } if (refreshed > 0 && isActive) settingsChanged() probeHealth { isActive } @@ -220,12 +219,14 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { context.removePluginLifecycleListener(aiCoreLifecycle) McpServerStore.removeChangeListener(settingsChanged) AutomaticServers.removeChangeListener(settingsChanged) - AutomaticServers.removeEndpointListener(relistAutomatic) McpServerHealth.removeChangeListener(healthChanged) unregisterToolSource() // Before the connections are closed: an in-flight refresh would otherwise repopulate the // catalogue and the session map straight after they were cleared. stopScope() + // After the scope ends, not before: startDebuggerEntry adds this listener and then checks + // the scope, so one added late is removed by that check and one added early is removed here. + AutomaticServers.removeEndpointListener(relistAutomatic) releaseConnections() true } catch (e: Exception) { @@ -237,10 +238,10 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { runCatching { context.removePluginLifecycleListener(aiCoreLifecycle) } McpServerStore.removeChangeListener(settingsChanged) AutomaticServers.removeChangeListener(settingsChanged) - AutomaticServers.removeEndpointListener(relistAutomatic) McpServerHealth.removeChangeListener(healthChanged) unregisterToolSource() stopScope() + AutomaticServers.removeEndpointListener(relistAutomatic) releaseConnections() pluginContext = null context.logger.info("McpPlugin: disposed") @@ -293,7 +294,24 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { * is defence only, for a host that registers no service anyway. A call that later throws (no * permission, unreadable database) leaves the entries as they were. */ - private fun installDebuggerEndpoints() { + /** + * Installs the host's endpoints and starts listening for changes, unless the activation ends first. + * + * The host's database read blocks and cancellation cannot interrupt it, so [keepGoing] is + * consulted around it. The listener is re-checked after it is added: [deactivate] ends the scope + * before it removes the listener, so one added in between is seen here and taken out again. + * + * @param keepGoing false once this activation is over. + */ + internal fun startDebuggerEntry(keepGoing: () -> Boolean) { + if (!keepGoing()) return + installDebuggerEndpoints(keepGoing) + if (!keepGoing()) return + AutomaticServers.addEndpointListener(relistAutomatic) + if (!keepGoing()) AutomaticServers.removeEndpointListener(relistAutomatic) + } + + private fun installDebuggerEndpoints(keepGoing: () -> Boolean) { val service = try { context.services.get(DebuggerEndpointService::class.java) } catch (e: Throwable) { @@ -303,7 +321,7 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { context.logger.info("McpPlugin: this IDE has no debugger endpoint service") return } - AutomaticServers.install(AutomaticServers.fromHost { service.endpoints }) + AutomaticServers.install(AutomaticServers.fromHost { service.endpoints }, keepGoing) } /** A fresh scope for this activation; the previous one is cancelled, never reused. */ diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginDebuggerStartTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginDebuggerStartTest.kt new file mode 100644 index 000000000..596ef7272 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginDebuggerStartTest.kt @@ -0,0 +1,81 @@ +package com.itsaky.androidide.plugins.aiagentmcp.plugin + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticServers +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.services.DebuggerEndpoint +import com.itsaky.androidide.plugins.services.DebuggerEndpointService +import io.mockk.every +import io.mockk.mockk +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * An activation that ends during the host's blocking first read of the debugger endpoints must + * leave no source and no listener behind: nothing removes them after [McpPlugin.deactivate]. + */ +class McpPluginDebuggerStartTest { + + private val entered = CountDownLatch(1) + private val release = CountDownLatch(1) + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + AutomaticServers.install(null) + val endpoint = mockk { + every { applicationId } returns "com.example.app" + every { port } returns 4000 + every { token } returns "t1" + } + val service = mockk { + every { endpoints } answers { + entered.countDown() + release.await(10, TimeUnit.SECONDS) + listOf(endpoint) + } + } + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + every { context.services.get(DebuggerEndpointService::class.java) } returns service + plugin = McpPlugin().also { it.initialize(context) } + } + + @After + fun tearDown() { + release.countDown() + plugin.dispose() + AutomaticServers.install(null) + } + + @Test + fun `an activation that ends during the first read installs nothing and adds no listener`() { + val listeners = AutomaticServers.endpointListenerCount + val active = AtomicBoolean(true) + val start = Thread { plugin.startDebuggerEntry { active.get() } }.also { it.start() } + assertTrue("the read never started", entered.await(10, TimeUnit.SECONDS)) + + active.set(false) + release.countDown() + start.join(10_000) + + assertTrue(AutomaticServers.servers().isEmpty()) + assertEquals(listeners, AutomaticServers.endpointListenerCount) + } + + @Test + fun `a live activation installs the entry and the listener once`() { + val listeners = AutomaticServers.endpointListenerCount + release.countDown() + plugin.startDebuggerEntry { true } + + assertEquals(1, AutomaticServers.servers().size) + assertEquals(listeners + 1, AutomaticServers.endpointListenerCount) + } +} From 185d360cde82da897766067da728cd85f6f9c1f0 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 15 Nov 2026 23:17:33 -0800 Subject: [PATCH 06/90] ADFA-7139 AI-Agent-MCP: a session for a replaced debugger endpoint sends no token credentialsFor returned the entry's current token for any session of that id, so the old session's close() sent DELETE to the old port carrying the new process's token. The supplier now takes the url its session was built for and releases the token only while the entry still points there. ReplacedEndpointCredentialTest replaces an endpoint and checks the DELETE the old server saw: it fails without this (the DELETE carried "Bearer new-token") and passes with it. FakeMcpServer now records requests and can hand out a session id. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../aiagentmcp/client/McpConnections.kt | 15 ++++-- .../client/ReplacedEndpointCredentialTest.kt | 49 +++++++++++++++++++ .../aiagentmcp/testing/FakeMcpServer.kt | 24 ++++++++- 3 files changed, 82 insertions(+), 6 deletions(-) create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/ReplacedEndpointCredentialTest.kt diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt index 76ac6442c..e1f469474 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt @@ -59,7 +59,7 @@ object McpConnections { stale = current?.second // A supplier, not the values: the session is kept for the life of the process, and a // token in one of its fields would be readable in a heap dump for just as long. - McpSession(server.url, { credentialsFor(server.id) }) + McpSession(server.url, { credentialsFor(server.id, server.url) }) .also { sessions[server.id] = key to it } } @@ -88,16 +88,21 @@ object McpConnections { * does not register, and it is what keeps the plaintext from outliving the request. * * @param serverId the server being called. + * @param url the url the calling session was built for. An automatic entry's token is released + * only while the entry still points there; a session for a replaced endpoint gets none, so + * its `close()` and any call still in flight cannot hand the new process's token to the old port. * @return its token and headers; either may be empty. * @throws UnreadableSecretException when a stored credential cannot be decrypted here. Sending * the request without it would earn a 401 and tell the user their token was refused. * @throws UnavailableSecretException when the keystore could not be reached to decrypt one, a * failure to retry rather than to report as a lost credential. */ - private fun credentialsFor(serverId: String): McpCredentials { + private fun credentialsFor(serverId: String, url: String): McpCredentials { if (AutomaticServers.isAutomatic(serverId)) { - // Read per request, so a refreshed endpoint's token is used without a new session. - return McpCredentials(AutomaticServers.token(serverId).orEmpty(), emptyMap()) + // Read per request, so a token refreshed on the same port is used without a new session. + val endpoint = AutomaticServers.endpoint(serverId) + val token = if (endpoint != null && AutomaticServers.urlFor(endpoint) == url) endpoint.token else "" + return McpCredentials(token, emptyMap()) } val token = when (val stored = McpServerStore.token(serverId)) { // Trimmed here, not by the store: the host's readAndMigrate migrates verbatim, and a @@ -128,7 +133,7 @@ object McpConnections { private fun keyFor(server: McpServer): Key { // Headers join the key for the same reason the token does: edit one and the old session // would keep sending the old value until the IDE restarts. - val credentials = credentialsFor(server.id) + val credentials = credentialsFor(server.id, server.url) return Key( serverId = server.id, url = server.url, diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/ReplacedEndpointCredentialTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/ReplacedEndpointCredentialTest.kt new file mode 100644 index 000000000..fda4e6a69 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/ReplacedEndpointCredentialTest.kt @@ -0,0 +1,49 @@ +package com.itsaky.androidide.plugins.aiagentmcp.client + +import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticEndpoint +import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticServers +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpToolCatalog +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +/** A session for a replaced debugger endpoint must not send the new endpoint's token to the old port. */ +class ReplacedEndpointCredentialTest { + + private val app = "com.example.app" + private val servers = mutableListOf() + + @After + fun tearDown() { + AutomaticServers.install(null) + McpConnections.closeAll() + McpToolCatalog.clear() + servers.forEach { it.stop() } + } + + @Test + fun `closing the session of a replaced endpoint does not send the new token to the old port`() { + val old = FakeMcpServer("old-token", listOf(tool("list_tables", true)), sessionId = "s1") + .also { servers += it } + val replacement = FakeMcpServer("new-token", listOf(tool("list_tables", true)), sessionId = "s2") + .also { servers += it } + var stored = listOf(AutomaticEndpoint(app, old.port, "old-token")) + AutomaticServers.install { stored } + + val session = McpConnections.session(AutomaticServers.servers().single()) + session.listTools() + assertTrue("the session opened against the old endpoint", old.requests.any { it.httpMethod == "POST" }) + + stored = listOf(AutomaticEndpoint(app, replacement.port, "new-token")) + assertTrue(AutomaticServers.refresh()) + McpConnections.session(AutomaticServers.servers().single()) // replaces and closes the old one + + val delete = old.requests.single { it.httpMethod == "DELETE" } + assertNotEquals("Bearer new-token", delete.authorization) + assertEquals(null, delete.authorization?.removePrefix("Bearer ")?.takeIf { it.isNotEmpty() }) + } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/testing/FakeMcpServer.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/testing/FakeMcpServer.kt index 8cfa7c223..c2c6383da 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/testing/FakeMcpServer.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/testing/FakeMcpServer.kt @@ -10,12 +10,31 @@ import org.json.JSONObject * plain JSON, and 401 unless the bearer token is [token] (any request when it is empty). A call's text names the port that served * it, so a test can tell which endpoint a call reached. * + * Every request is recorded in [requests], and a non-null [sessionId] is handed out on `initialize`, + * so a test can see the `DELETE` a closing session sends and which token it carried. + * * @param tools the `tools/list` entries. + * @param sessionId the `Mcp-Session-Id` to assign, or null for a server without sessions. */ -class FakeMcpServer(val token: String, private val tools: List) { +class FakeMcpServer( + val token: String, + private val tools: List, + private val sessionId: String? = null, +) { + + /** One request as the server saw it. */ + data class Seen(val httpMethod: String, val authorization: String?) + + val requests = java.util.concurrent.CopyOnWriteArrayList() private val server: HttpServer = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply { createContext("/mcp") { exchange -> + requests += Seen(exchange.requestMethod, exchange.requestHeaders.getFirst("Authorization")) + if (exchange.requestMethod == "DELETE") { + exchange.sendResponseHeaders(200, -1) + exchange.close() + return@createContext + } val request = JSONObject(exchange.requestBody.use { String(it.readBytes()) }) val id = request.opt("id") if (token.isNotEmpty() && exchange.requestHeaders.getFirst("Authorization") != "Bearer $token") { @@ -37,6 +56,9 @@ class FakeMcpServer(val token: String, private val tools: List) { val bytes = JSONObject().put("jsonrpc", "2.0").put("id", id).put("result", result) .toString().toByteArray() exchange.responseHeaders.add("Content-Type", "application/json") + if (sessionId != null && request.getString("method") == "initialize") { + exchange.responseHeaders.add("Mcp-Session-Id", sessionId) + } exchange.sendResponseHeaders(200, bytes.size.toLong()) exchange.responseBody.use { it.write(bytes) } } From 3fc5002e09509833a05136ddbb98a1019e04ea60 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 16 Nov 2026 19:04:30 -0800 Subject: [PATCH 07/90] ADFA-7139 AI-Agent-MCP: move the stacked KDoc onto installDebuggerEndpoints The doc describing the host endpoint service sat on startDebuggerEntry above its own KDoc; it belongs to installDebuggerEndpoints, which reads the service. Comment-only change, so no test. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../plugins/aiagentmcp/plugin/McpPlugin.kt | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt index 3d4b2f953..cf5fb22c9 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt @@ -286,14 +286,6 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { } } - /** - * Points [AutomaticServers] at the host's debugger endpoints. - * - * `plugin.min_ide_version` keeps this plugin off an IDE that lacks the service: such an IDE - * rejects the unknown `debugger.endpoints` permission when it validates the manifest. The catch - * is defence only, for a host that registers no service anyway. A call that later throws (no - * permission, unreadable database) leaves the entries as they were. - */ /** * Installs the host's endpoints and starts listening for changes, unless the activation ends first. * @@ -311,6 +303,14 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { if (!keepGoing()) AutomaticServers.removeEndpointListener(relistAutomatic) } + /** + * Points [AutomaticServers] at the host's debugger endpoints. + * + * `plugin.min_ide_version` keeps this plugin off an IDE that lacks the service: such an IDE + * rejects the unknown `debugger.endpoints` permission when it validates the manifest. The catch + * is defence only, for a host that registers no service anyway. A call that later throws (no + * permission, unreadable database) leaves the entries as they were. + */ private fun installDebuggerEndpoints(keepGoing: () -> Boolean) { val service = try { context.services.get(DebuggerEndpointService::class.java) From 5911aaccaadd9fa7bd454672a3b9f8b0c133eb34 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 16 Nov 2026 19:04:30 -0800 Subject: [PATCH 08/90] ADFA-7139 AI-Agent-MCP: the health probe refreshes nothing once its activation is over probeHealth checked keepGoing only before the delay, then called AutomaticServers.refresh() without it, so a deactivation during the delay (or during the refresh's blocking read) let the refresh restore the automatic entries that install(null) had just cleared, and re-publish them. It now returns if the activation ended during the delay, passes keepGoing to refresh (which checks it after the read, before storing) and re-checks before settingsChanged(). startDebuggerEntry and installDebuggerEndpoints already guard each step. probeHealth is now internal with an intervalMs parameter so a test can drive it. Tests: McpPluginProbeHealthTest (ended during the delay; ended during the refresh read). Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../plugins/aiagentmcp/plugin/McpPlugin.kt | 14 ++-- .../plugin/McpPluginProbeHealthTest.kt | 77 +++++++++++++++++++ 2 files changed, 86 insertions(+), 5 deletions(-) create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginProbeHealthTest.kt diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt index cf5fb22c9..4fc17e476 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt @@ -207,7 +207,7 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { startDebuggerEntry { isActive } val refreshed = McpToolCatalog.refreshAll { isActive } if (refreshed > 0 && isActive) settingsChanged() - probeHealth { isActive } + probeHealth({ isActive }) } true } catch (e: Exception) { @@ -257,14 +257,18 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { * Servers are asked in parallel, so one that hangs until its timeout delays no other's tag. * * @param keepGoing false once this activation is over; checked before each probe, since a probe - * blocks on a socket with no suspension point, like [McpToolCatalog.refreshAll]. + * blocks on a socket with no suspension point, like [McpToolCatalog.refreshAll]. Checked again + * after the delay and, inside [AutomaticServers.refresh], after its blocking read: deactivation + * clears the automatic entries, and a refresh that outlived it would restore them. + * @param intervalMs the wait between cycles; a seam for tests. */ - private suspend fun probeHealth(keepGoing: () -> Boolean) { + internal suspend fun probeHealth(keepGoing: () -> Boolean, intervalMs: Long = PROBE_INTERVAL_MS) { var cycle = 0 while (keepGoing()) { - delay(PROBE_INTERVAL_MS) + delay(intervalMs) + if (!keepGoing()) return cycle++ - if (AutomaticServers.refresh()) settingsChanged() + if (AutomaticServers.refresh(keepGoing) && keepGoing()) settingsChanged() val due = McpServers.all().filter { server -> val health = McpServerHealth.of(server.id) server.enabled && health?.refused != true && (cycle % HEALTHY_PROBE_EVERY == 0 || diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginProbeHealthTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginProbeHealthTest.kt new file mode 100644 index 000000000..a0d34bfde --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginProbeHealthTest.kt @@ -0,0 +1,77 @@ +package com.itsaky.androidide.plugins.aiagentmcp.plugin + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticEndpoint +import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticServers +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import io.mockk.every +import io.mockk.mockk +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicInteger +import kotlinx.coroutines.runBlocking +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * The health probe must not refresh or re-publish the automatic entries once its activation is + * over: deactivation has cleared them, and a refresh that outlived it would restore them. + */ +class McpPluginProbeHealthTest { + + private lateinit var plugin: McpPlugin + private val reads = AtomicInteger() + private val active = AtomicBoolean(true) + + @Before + fun setUp() { + AutomaticServers.install(null) + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + } + + @After + fun tearDown() { + plugin.dispose() + AutomaticServers.install(null) + } + + private var current = emptyList() + private var onRead: () -> Unit = {} + + private fun installSource() { + AutomaticServers.install({ + reads.incrementAndGet() + onRead() + current + }) + } + + @Test + fun `an activation that ends during the delay refreshes nothing`() { + installSource() + current = listOf(AutomaticEndpoint("com.example.app", 4000, "t1")) + val before = reads.get() + // The loop condition sees a live activation; the check after the delay sees it ended. + val asked = AtomicInteger() + + runBlocking { plugin.probeHealth({ asked.incrementAndGet() == 1 }, intervalMs = 10) } + + assertEquals(before, reads.get()) + assertTrue(AutomaticServers.servers().isEmpty()) + } + + @Test + fun `an activation that ends during the refresh read stores nothing`() { + installSource() + current = listOf(AutomaticEndpoint("com.example.app", 4000, "t1")) + onRead = { active.set(false) } + + runBlocking { plugin.probeHealth({ active.get() }, intervalMs = 10) } + + assertTrue(AutomaticServers.servers().isEmpty()) + } +} From 994860ea48693983aa9c55aa679e1e175cb1a2ab Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 16 Nov 2026 21:24:17 -0800 Subject: [PATCH 09/90] ADFA-7139 AI-Agent-MCP: no refresh restores automatic entries after deactivation AutomaticServers.refresh now stores nothing when the source it read is no longer the installed one, so a refresh started by EndpointRetry (default keepGoing) that was in flight when install(null) cleared the entries cannot bring them back. Every caller is covered, not only the ones passing keepGoing. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../aiagentmcp/debugger/AutomaticServers.kt | 6 ++++- .../plugin/McpPluginProbeHealthTest.kt | 23 ++++++++++++++++++- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt index c899401be..0be21ef45 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt @@ -118,6 +118,10 @@ object AutomaticServers { /** * Re-reads the endpoints. Blocking host call: use a background thread. + * Nothing is stored when the source that was read is no longer installed, so a refresh in + * flight when deactivation cleared the entries (or a later activation replaced the source) + * cannot restore them, whichever caller started it. + * * @param keepGoing checked after the read, before anything is stored. * @return true when the set of entries, a port or a token changed. */ @@ -134,7 +138,7 @@ object AutomaticServers { val moved = mutableListOf() val removed: List val changed = synchronized(this) { - if (!keepGoing()) return false + if (source !== read || !keepGoing()) return false val old = states val next = fresh.mapValues { (id, endpoint) -> val previous = old[id] diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginProbeHealthTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginProbeHealthTest.kt index a0d34bfde..2704fc576 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginProbeHealthTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginProbeHealthTest.kt @@ -4,8 +4,10 @@ import com.itsaky.androidide.plugins.PluginContext import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticEndpoint import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticServers import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpToolCatalog import io.mockk.every import io.mockk.mockk +import java.net.ConnectException import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicInteger import kotlinx.coroutines.runBlocking @@ -17,7 +19,8 @@ import org.junit.Test /** * The health probe must not refresh or re-publish the automatic entries once its activation is - * over: deactivation has cleared them, and a refresh that outlived it would restore them. + * over: deactivation has cleared them, and a refresh that outlived it would restore them. The same + * holds for the endpoint retry's refresh. */ class McpPluginProbeHealthTest { @@ -74,4 +77,22 @@ class McpPluginProbeHealthTest { assertTrue(AutomaticServers.servers().isEmpty()) } + + @Test + fun `an endpoint retry in flight at deactivation restores nothing`() { + installSource() + current = listOf(AutomaticEndpoint("com.example.app", 4000, "t1")) + AutomaticServers.refresh() + val server = AutomaticServers.servers().single() + current = listOf(AutomaticEndpoint("com.example.app", 4001, "t2")) + // Deactivation lands while the retry's refresh is reading the host. + onRead = { AutomaticServers.install(null) } + + try { + McpToolCatalog.retry.call(server) { throw ConnectException("refused") } + } catch (expected: ConnectException) { + } + + assertTrue(AutomaticServers.servers().isEmpty()) + } } From 6e57f6a5ee786360ce834c896a1f557ae610ccf8 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 16 Nov 2026 22:49:35 -0800 Subject: [PATCH 10/90] ADFA-7139 AI-Agent-MCP: tidy the keepGoing KDoc and a duplicate tool-list notification @param keepGoing was documented on the install overload that has no such parameter; it now sits on the two-argument overload that takes it. probeHealth called settingsChanged() after AutomaticServers.refresh returned true. refresh returns true only when it fired its change listeners, and McpPlugin.activate registers settingsChanged on them before probeHealth starts, so the agent was told twice. The call is removed; no test, since the agent is notified exactly as before. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../aiagentmcp/debugger/AutomaticServers.kt | 14 ++++++++------ .../plugins/aiagentmcp/plugin/McpPlugin.kt | 3 ++- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt index 0be21ef45..bf53c980a 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt @@ -63,11 +63,6 @@ object AutomaticServers { /** * Where endpoints come from; null (deactivation) clears every entry. - * - * @param keepGoing false once the activation installing [source] is over. The first read blocks - * and cannot be cancelled, so an activation that ended during it must neither keep [source] - * nor publish what it read: deactivation has already cleared everything, and a later - * activation owns the state now. */ fun install(source: (() -> List)?) { if (source == null) { @@ -79,7 +74,14 @@ object AutomaticServers { } } - /** As [install], for a source that may be superseded while its first read is blocked. */ + /** + * As [install], for a source that may be superseded while its first read is blocked. + * + * @param keepGoing false once the activation installing [source] is over. The first read blocks + * and cannot be cancelled, so an activation that ended during it must neither keep [source] + * nor publish what it read: deactivation has already cleared everything, and a later + * activation owns the state now. + */ fun install(source: () -> List, keepGoing: () -> Boolean) { synchronized(this) { if (!keepGoing()) return diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt index 4fc17e476..3b0635433 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt @@ -268,7 +268,8 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { delay(intervalMs) if (!keepGoing()) return cycle++ - if (AutomaticServers.refresh(keepGoing) && keepGoing()) settingsChanged() + // A change already told the agent: refresh fires the change listener added on activation. + AutomaticServers.refresh(keepGoing) val due = McpServers.all().filter { server -> val health = McpServerHealth.of(server.id) server.enabled && health?.refused != true && (cycle % HEALTHY_PROBE_EVERY == 0 || From 02704e7451b7471e2f91e1669b6d8f15eeda7621 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 16 Nov 2026 22:49:35 -0800 Subject: [PATCH 11/90] ADFA-7139 AI-Agent-MCP: a cancelled tool call does not run its endpoint retry EndpointRetry runs a call a second time against the re-read endpoint. A cancel landing between the attempts found no live session to drop (the first had ended, the second not begun), so the retry went out anyway. McpToolSource now records a cancel for a running call and the retry's block checks it before opening a session, failing as an interrupted read, which is how a dropped connection already reports a cancel (classified as Cancelled, so the server is not marked degraded). Test: CancelBetweenAttemptsTest cancels from inside the retry's endpoint re-read; without the check the new endpoint receives the retry. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../plugins/aiagentmcp/tools/McpToolSource.kt | 19 ++++ .../debugger/CancelBetweenAttemptsTest.kt | 98 +++++++++++++++++++ 2 files changed, 117 insertions(+) create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/CancelBetweenAttemptsTest.kt diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt index 010634ccf..0bc2e7eae 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt @@ -12,6 +12,7 @@ import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServer import com.itsaky.androidide.plugins.services.CapabilityStatus import com.itsaky.androidide.plugins.services.ToolSourceRegistry +import java.io.InterruptedIOException import java.util.concurrent.CompletableFuture import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ExecutorService @@ -42,6 +43,16 @@ class McpToolSource : */ private val liveSessions = ConcurrentHashMap() + /** Calls whose worker is running, so [cancel] knows whether a flag will ever be read. */ + private val running: MutableSet = ConcurrentHashMap.newKeySet() + + /** + * Running calls that were cancelled. The session drop in [cancel] reaches only a request in + * flight; one landing between the two attempts of the endpoint retry finds no session, so the + * retry reads this before it sends anything. + */ + private val cancelled: MutableSet = ConcurrentHashMap.newKeySet() + /** * Remote calls run here rather than on the common pool: an MCP call blocks on a socket for as * long as the read timeout, and the common pool is sized for CPU work. @@ -114,6 +125,7 @@ class McpToolSource : override fun cancel(callId: String) { inFlight.remove(callId)?.cancel(true) + if (callId in running) cancelled += callId // The worker is blocked on a socket read, where an interrupt does nothing; dropping the // connection is what actually ends it. Only this call's, so a concurrent call against // another server keeps its socket. @@ -141,7 +153,11 @@ class McpToolSource : tool: McpTool, arguments: Map, ): ToolSourceRegistry.ToolOutcome = try { + running += callId val result = McpToolCatalog.retry.call(server) { target -> + // Cancelled between two attempts (or before the first): nothing is sent. Signalled as + // an interrupted read, which is how a dropped connection already reports a cancel. + if (callId in cancelled) throw InterruptedIOException("Tool call $callId was cancelled") val session = McpConnections.session(target) liveSessions[callId] = session try { @@ -158,6 +174,9 @@ class McpToolSource : McpToolCatalog.recordFailure(server, e) val context = McpPlugin.getContext()?.androidContext Outcome(false, "", McpErrorFormatter.format(context, server.name, e)) + } finally { + running -= callId + cancelled -= callId } /** diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/CancelBetweenAttemptsTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/CancelBetweenAttemptsTest.kt new file mode 100644 index 000000000..901d4ec4c --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/CancelBetweenAttemptsTest.kt @@ -0,0 +1,98 @@ +package com.itsaky.androidide.plugins.aiagentmcp.debugger + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpToolCatalog +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpToolSource +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import com.itsaky.androidide.plugins.services.ToolSourceRegistry +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import java.util.concurrent.TimeUnit +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + + +/** A cancel that lands between the endpoint retry's two attempts must stop the second one. */ +class CancelBetweenAttemptsTest { + + private val app = "com.example.app" + private val servers = mutableListOf() + private val source = McpToolSource() + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + // The Keystore is not there on the JVM; a hand-added server in these tests has no secrets. + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } returns KeystoreSecretStore.Stored.Absent + every { McpServerStore.headers(any()) } returns emptyMap() + } + + @After + fun tearDown() { + source.close() + AutomaticServers.install(null) + McpConnections.closeAll() + McpToolCatalog.clear() + servers.forEach { it.stop() } + plugin.dispose() + unmockkObject(McpServerStore) + } + + private fun fake(token: String, vararg tools: org.json.JSONObject) = + FakeMcpServer(token, tools.toList()).also { servers += it } + + private fun offered(): Map = + source.listTools().associateBy { it.name } + + private fun invoke(name: String): java.util.concurrent.CompletableFuture = + source.invoke( + mockk { + every { toolName } returns name + every { arguments } returns emptyMap() + every { callId } returns "call-1" + } + ) + + @Test + fun `a cancel between the attempts sends nothing to the new endpoint`() { + val first = fake("t1", tool("list_tables", true)) + var stored = listOf(AutomaticEndpoint(app, first.port, "t1")) + var cancelOnRead = false + AutomaticServers.install { + if (cancelOnRead) source.cancel("call-1") + stored + } + McpToolCatalog.connect(AutomaticServers.servers().single()) + val name = offered().keys.single() + + // The app relaunches: the first attempt is refused, and the retry's re-read is where the + // cancel lands. + first.stop() + val second = fake("t2", tool("list_tables", true)) + stored = listOf(AutomaticEndpoint(app, second.port, "t2")) + cancelOnRead = true + val future = invoke(name) + + // The agent's future is cancelled with the call; the worker behind it is what must stop. + // Bounded wait: without the check the retry reaches the new endpoint within milliseconds. + val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(2) + while (second.requests.isEmpty() && System.nanoTime() < deadline) Thread.sleep(20) + assertTrue(future.isCompletedExceptionally) + assertTrue("the retry was sent anyway: ${second.requests}", second.requests.isEmpty()) + } +} From d102bfe9c6de22c5d13a16e2164861fd0ee651e7 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 16 Nov 2026 22:50:08 -0800 Subject: [PATCH 12/90] ADFA-7139 AI-Agent-MCP: tell each app's SQLite debugger tools apart by name and description Every SQLite debugger entry is named "SQLite debugger ()" and tool names use the first 10 identifier characters of the server name, so every entry's tools began sqlite_deb. With two apps reporting, the model saw sqlite_deb_query and sqlite_deb_query_2 with identical descriptions, and which app got "_2" followed the host's row order. Now, for automatic entries only: - the name prefix is db_ plus the first 7 characters of the application ID's last segment (db_notes_query); apps whose prefix would be shared (com.a.notes, com.b.notes) both use the first 5 characters of the segment plus 4 hex digits of a digest of the full application ID (notes_3fa1_query). It depends only on the set of IDs, so it is stable across restarts and row order, and stays within the 10-character prefix rule. The collision set is every automatic entry, not only those with tools on. - each description starts " (SQLite debugger): ", so the model and the approval dialog name the app. Hand-added servers keep McpToolText.exposedName(server.name, ...) and their own description. What depends on the names or descriptions: - ReadOnlyTrust.enabledTools and the stored knownTools/enabledTools use the server's own tool names (query), not the exposed ones: unchanged. - The tool source registration with AI-Core (listTools/getToolGroups): the exposed names and descriptions of these tools change once, on upgrade; group ids and display names do not. Calls resolve by exposed name from the same list, so listing and invoking agree. - AI-Core's session-grant key (addons#167, ContributedToolHandler.sessionApprovalKey = provider:tool name:digest(description, schema)): it changes once for these tools, so a grant given to the old text is not carried over, and it now differs per app, so an "Always Allow" for one app's query no longer covers another's. Tests: AppToolNamesTest (two apps; two with the same last segment, both row orders; one app with a hand-added server unchanged), McpToolTextTest (appPrefixes). Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- plugins/AI-Agent-MCP/README.md | 9 ++ .../aiagentmcp/debugger/AutomaticServers.kt | 3 + .../plugins/aiagentmcp/tools/McpToolSource.kt | 37 ++++- .../plugins/aiagentmcp/tools/McpToolText.kt | 46 ++++++ .../aiagentmcp/debugger/AppToolNamesTest.kt | 136 ++++++++++++++++++ .../aiagentmcp/tools/McpToolTextTest.kt | 19 +++ 6 files changed, 246 insertions(+), 4 deletions(-) create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AppToolNamesTest.kt diff --git a/plugins/AI-Agent-MCP/README.md b/plugins/AI-Agent-MCP/README.md index 3e1f4544c..1268b9a5d 100644 --- a/plugins/AI-Agent-MCP/README.md +++ b/plugins/AI-Agent-MCP/README.md @@ -59,6 +59,15 @@ points the entry at `http://127.0.0.1:/mcp`. A relaunched app gets a new port and token, and the plugin reads them again after a refused connection. An app that has not reported yet has no entry, and no error is shown. +Each app's tools are told apart for the model. Their names start with `db_` and +the last segment of the application ID (`db_notes_query` for +`com.example.notes`); when two apps would share that prefix, both use the first +five characters of the segment and four hex digits derived from the full +application ID (`notes_3fa1_query`), so a name never depends on which app was +read first. Each description starts with the application ID, as +"com.example.notes (SQLite debugger): ...", and the approval dialog shows it. +Servers you add yourself keep the name prefix taken from their label. + - It is held in memory only and is **not shown in the settings screen in this version**, so there is no switch to turn it off there. - The tools that declare MCP's `readOnlyHint: true` start switched **on**. Any diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt index bf53c980a..58701d1d4 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt @@ -220,6 +220,9 @@ object AutomaticServers { fun idFor(applicationId: String) = ID_PREFIX + applicationId + /** The application ID an automatic entry's id was made from. */ + fun applicationIdOf(serverId: String) = serverId.removePrefix(ID_PREFIX) + private fun fireChanged() { for (l in listeners) runCatching { l() } } diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt index 0bc2e7eae..7f0dd210d 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt @@ -4,6 +4,7 @@ import android.util.Log import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections import com.itsaky.androidide.plugins.aiagentmcp.client.McpSession import com.itsaky.androidide.plugins.aiagentmcp.client.McpTool +import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticServers import com.itsaky.androidide.plugins.aiagentmcp.debugger.McpServers import com.itsaky.androidide.plugins.aiagentmcp.errors.McpErrorFormatter import com.itsaky.androidide.plugins.aiagentmcp.R @@ -68,7 +69,7 @@ class McpToolSource : override fun listTools(): List = exposedTools().map { exposed -> Spec( name = exposed.name, - description = exposed.tool.description, + description = exposed.description, parametersSchema = exposed.tool.inputSchema, preApproved = exposed.server.automatic && exposed.tool.readOnlyHint, ) @@ -222,8 +223,20 @@ class McpToolSource : val exposed = mutableListOf() val taken = mutableSetOf() + // From every automatic entry, not only those offering tools, so a prefix does not change + // when another app's tools are switched off or its tool list is still empty. + val appPrefixes = McpToolText.appPrefixes( + McpServers.all().filter { it.automatic }.map { AutomaticServers.applicationIdOf(it.id) }, + ) for ((server, tool) in enabledTools()) { - val base = McpToolText.exposedName(server.name, tool.name) + val base = if (server.automatic) { + McpToolText.exposedNameWithPrefix( + appPrefixes.getValue(AutomaticServers.applicationIdOf(server.id)), + tool.name, + ) + } else { + McpToolText.exposedName(server.name, tool.name) + } if (base == null) { Log.w(TAG, "Dropping a tool from '${server.name}': its name has nothing usable") continue @@ -237,7 +250,7 @@ class McpToolSource : Log.i(TAG, "'${tool.name}' on '${server.name}' shares a name; offering it as '$name'") } taken += name - exposed += Exposed(server, tool, name) + exposed += Exposed(server, tool, name, describe(server, tool)) } return exposed } @@ -248,7 +261,23 @@ class McpToolSource : * @property tool the tool, as the server described it. * @property name the name the agent and the model see. */ - private class Exposed(val server: McpServer, val tool: McpTool, val name: String) + private class Exposed( + val server: McpServer, + val tool: McpTool, + val name: String, + val description: String, + ) + + /** + * The description the model and the approval dialog see. A SQLite debugger tool starts with + * its application ID: every entry's tools say the same thing otherwise, and the model could + * not tell which app's database one reads. A hand-added server's text is passed through. + */ + private fun describe(server: McpServer, tool: McpTool): String { + if (!server.automatic) return tool.description + val app = "${AutomaticServers.applicationIdOf(server.id)} (SQLite debugger)" + return if (tool.description.isBlank()) app else "$app: ${tool.description}" + } /** * One tool, as the host contract describes it. diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolText.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolText.kt index 18291c736..781cf00f0 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolText.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolText.kt @@ -33,6 +33,52 @@ object McpToolText { return if (prefix.isEmpty()) tool else "${prefix}_$tool" } + /** + * As [exposedName], for a prefix that is already decided (see [appPrefixes]). + * @param prefix a sanitised prefix of at most [MAX_PREFIX_LENGTH] characters. + */ + fun exposedNameWithPrefix(prefix: String, toolName: String): String? { + val tool = identifier(toolName).take(MAX_NAME_LENGTH).trim('_') + if (tool.isEmpty()) return null + return if (prefix.isEmpty()) tool else "${prefix}_$tool" + } + + /** + * The name prefix of each SQLite debugger entry, told apart by app. + * + * The server label cannot do it: every entry is labelled "SQLite debugger (...)", and the + * first [MAX_PREFIX_LENGTH] characters of that are the same for all of them. The prefix is + * `db_` and the first seven characters of the application ID's last segment. Entries whose + * prefix would still be shared (`com.a.notes` and `com.b.notes`) all take the first five + * characters of the segment and four hex digits of a digest of the full application ID + * instead. Both forms depend only on the set of application IDs, never on their order, and + * fit [MAX_PREFIX_LENGTH]. + * + * @param applicationIds the application ID of every entry. + * @return the prefix by application ID. + */ + fun appPrefixes(applicationIds: Collection): Map { + val ids = applicationIds.distinct() + val plain = ids.associateWith { id -> + "db_" + segment(id).take(MAX_PREFIX_LENGTH - 3).trim('_') + } + val shared = plain.values.groupingBy { it }.eachCount() + return ids.associateWith { id -> + if (shared.getValue(plain.getValue(id)) == 1) { + plain.getValue(id) + } else { + segment(id).take(5).trim('_') + "_" + digest(id) + } + } + } + + private fun segment(applicationId: String): String = + identifier(applicationId.substringAfterLast('.')).ifEmpty { "app" } + + private fun digest(text: String): String = + java.security.MessageDigest.getInstance("SHA-256").digest(text.toByteArray()) + .take(2).joinToString("") { "%02x".format(it) } + /** * A free variant of [name], numbered when two tools ended up sharing one exposed name. * diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AppToolNamesTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AppToolNamesTest.kt new file mode 100644 index 000000000..e1ab30db6 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AppToolNamesTest.kt @@ -0,0 +1,136 @@ +package com.itsaky.androidide.plugins.aiagentmcp.debugger + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpToolCatalog +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpToolSource +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import com.itsaky.androidide.plugins.services.ToolSourceRegistry +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import java.util.concurrent.TimeUnit +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + + +/** + * What the model is told for each SQLite debugger entry: tools that differ per app in name and + * description, so two apps reporting for one project are never confused. + */ +class AppToolNamesTest { + + private val servers = mutableListOf() + private val source = McpToolSource() + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + // The Keystore is not there on the JVM; a hand-added server in these tests has no secrets. + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } returns KeystoreSecretStore.Stored.Absent + every { McpServerStore.headers(any()) } returns emptyMap() + } + + @After + fun tearDown() { + source.close() + AutomaticServers.install(null) + McpConnections.closeAll() + McpToolCatalog.clear() + servers.forEach { it.stop() } + plugin.dispose() + unmockkObject(McpServerStore) + } + + private fun fake(token: String, vararg tools: org.json.JSONObject) = + FakeMcpServer(token, tools.toList()).also { servers += it } + + private fun offered(): Map = + source.listTools().associateBy { it.name } + + private fun invoke(name: String): ToolSourceRegistry.ToolOutcome = + source.invoke( + mockk { + every { toolName } returns name + every { arguments } returns emptyMap() + every { callId } returns "call-1" + } + ).get(30, TimeUnit.SECONDS) + + private fun debuggerTools() = arrayOf(tool("list_tables", true), tool("run_sql", false), tool("unmarked", null)) + + private fun connectAll(vararg apps: Pair, reversed: Boolean = false) { + val endpoints = apps.map { (id, server) -> AutomaticEndpoint(id, server.port, server.token) } + AutomaticServers.install { if (reversed) endpoints.reversed() else endpoints } + AutomaticServers.servers().forEach { McpToolCatalog.connect(it) } + } + + /** The exposed names by application ID, read from each description. */ + private fun byApp(): Map> = offered().values.associate { + it.description.substringBefore(" (SQLite debugger)") to (it.name to it.description) + } + + @Test + fun `two apps get distinct tool names and descriptions naming each app`() { + connectAll( + "com.example.notes" to fake("a", tool("query", true)), + "com.example.shop" to fake("b", tool("query", true)), + ) + + val apps = byApp() + assertEquals(setOf("com.example.notes", "com.example.shop"), apps.keys) + assertEquals("db_notes_query", apps.getValue("com.example.notes").first) + assertEquals("db_shop_query", apps.getValue("com.example.shop").first) + assertEquals("com.example.notes (SQLite debugger): query", apps.getValue("com.example.notes").second) + } + + @Test + fun `apps sharing a last segment stay distinct and keep their names whatever the row order`() { + val one = "com.alpha.notes" + val two = "com.beta.notes" + connectAll(one to fake("a", tool("query", true)), two to fake("b", tool("query", true))) + val forward = byApp() + assertEquals(2, forward.values.map { it.first }.toSet().size) + assertTrue(forward.getValue(one).first.length <= 10 + "_query".length) + + AutomaticServers.install(null) + McpToolCatalog.clear() + servers.forEach { it.stop() } + servers.clear() + connectAll(one to fake("a", tool("query", true)), two to fake("b", tool("query", true)), reversed = true) + + assertEquals(forward, byApp()) + } + + @Test + fun `a single app still works and a hand-added server keeps its name and description`() { + val debugger = fake("a", tool("query", true)) + connectAll("com.example.notes" to debugger) + val mine = fake("", tool("claims", true)) + val handAdded = McpServerStore.saveDetails( + McpServerStore.newServer("Company Docs", "http://127.0.0.1:${mine.port}/mcp") + ) + McpToolCatalog.connect(handAdded) + McpServerStore.setToolEnabled(handAdded.id, "claims", true) + + val specs = offered() + assertEquals(setOf("db_notes_query", "company_do_claims"), specs.keys) + assertEquals("claims", specs.getValue("company_do_claims").description) + val outcome = invoke("db_notes_query") + assertTrue(outcome.errorMessage, outcome.isSuccess) + } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolTextTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolTextTest.kt index 41e7afe3a..a7a0c6374 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolTextTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolTextTest.kt @@ -2,6 +2,7 @@ package com.itsaky.androidide.plugins.aiagentmcp.tools import org.junit.Assert.assertEquals import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue import org.junit.Test /** @@ -59,4 +60,22 @@ class McpToolTextTest { assertNull(McpToolText.disambiguate("git_search", taken)) } + + @Test + fun givenAppIds_whenPrefixed_thenEachAppGetsItsOwnShortStablePrefix() { + val ids = listOf("com.example.notes", "com.example.shop", "org.other.Notes") + val prefixes = McpToolText.appPrefixes(ids) + assertEquals("db_shop", prefixes.getValue("com.example.shop")) + // The two notes apps share a segment: both fall back to segment plus digest. + val a = prefixes.getValue("com.example.notes") + val b = prefixes.getValue("org.other.Notes") + assertEquals(2, setOf(a, b).size) + assertTrue(a.startsWith("notes_") && a.length <= 10) + assertEquals(prefixes, McpToolText.appPrefixes(ids.reversed())) + } + + @Test + fun givenAnAppIdWithNothingUsable_whenPrefixed_thenItStillGetsAName() { + assertEquals("db_app", McpToolText.appPrefixes(listOf("com.example.***")).getValue("com.example.***")) + } } From 96b49e3996e57057be5aa966e916cd5c4c7b727f Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 16 Nov 2026 23:09:17 -0800 Subject: [PATCH 13/90] ADFA-7139 AI-Agent-MCP: switch on only the SQLite debugger's four core tools An SQLite debugger entry now starts with list_databases, get_schema, query and get_events switched on, each only when the server advertises it with readOnlyHint: true. Its other tools stay known but off. A tool without readOnlyHint exactly true is still never switched on; hand-added servers are unchanged. This changes ADFA-7139's earlier rule, under which every read-only tool started on. Why: AI-Core describes at most 12 contributed tools per message (4 in compact mode), in order, and drops the rest, and every app has its own entry. With all 8 read-only tools on, two apps used the whole normal budget and a hand-added server pushed SQLite debugger tools out silently. Phase 2 adds the entry to settings so a user can switch the others on. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- plugins/AI-Agent-MCP/README.md | 16 +++++--- plugins/AI-Agent-MCP/ai-agent-mcp.html | 5 ++- .../aiagentmcp/debugger/ReadOnlyTrust.kt | 29 +++++++++++--- .../plugins/aiagentmcp/settings/McpServer.kt | 3 +- .../aiagentmcp/debugger/AppToolNamesTest.kt | 2 +- .../debugger/AutomaticServersTest.kt | 39 ++++++++++++++----- .../debugger/CancelBetweenAttemptsTest.kt | 4 +- .../debugger/ReadOnlyHintParsingTest.kt | 21 ++++++++-- .../debugger/RelaunchToolSourceTest.kt | 4 +- 9 files changed, 92 insertions(+), 31 deletions(-) diff --git a/plugins/AI-Agent-MCP/README.md b/plugins/AI-Agent-MCP/README.md index 1268b9a5d..b3780e9b8 100644 --- a/plugins/AI-Agent-MCP/README.md +++ b/plugins/AI-Agent-MCP/README.md @@ -36,8 +36,8 @@ Configuration → MCP servers**: 1. **Add server** — name, endpoint URL, optional token. 2. **Connect** — saves the server, performs the MCP handshake and lists the tools it offers, all in one step. -3. Switch on the tools you want. **They start off** (except the read-only tools - of the automatic debugger entry, below): one popular GitHub server +3. Switch on the tools you want. **They start off** (except four read-only tools + of the automatic SQLite debugger entry, below): one popular GitHub server advertises around ninety tools, which would fill a phone-sized context window on its own. 4. **Clear stored credential** — removes the stored token and headers. The token @@ -70,9 +70,15 @@ Servers you add yourself keep the name prefix taken from their label. - It is held in memory only and is **not shown in the settings screen in this version**, so there is no switch to turn it off there. -- The tools that declare MCP's `readOnlyHint: true` start switched **on**. Any - other tool of that entry starts off. The hint is trusted for this entry only, - never for a server you add yourself. +- Four tools start switched **on**: `list_databases`, `get_schema`, `query` and + `get_events`, each only when the server declares MCP's `readOnlyHint: true` for + it. Every other tool of that entry (today `list_connections`, + `explain_query_plan`, `get_stats` and `integrity_check`) starts off, and so + does any tool without that hint. The hint is trusted for this entry only, never + for a server you add yourself. Four, not all eight, because AI-Core describes + at most 12 contributed tools per message (4 for a small on-device model), in + order, and drops the rest; every app has its own entry. Switching the others + on will come with showing this entry in the settings screen (phase 2). - The Agent still asks for approval on every call: AI-Core makes every contributed tool ask (it ignores the tool's own `requiresApproval`). Approving read-only calls automatically is tracked in ADFA-7147. diff --git a/plugins/AI-Agent-MCP/ai-agent-mcp.html b/plugins/AI-Agent-MCP/ai-agent-mcp.html index 92f0cf1ea..410a38967 100644 --- a/plugins/AI-Agent-MCP/ai-agent-mcp.html +++ b/plugins/AI-Agent-MCP/ai-agent-mcp.html @@ -141,8 +141,9 @@

Usage

New tools always arrive switched off, including on the connection - that discovers them. The one exception is the read-only tools of the SQLite - debugger entry that Code on the Go supplies for your own debug app. Nothing a server adds later becomes visible to the model + that discovers them. The one exception is four read-only tools (list databases, get schema, + query and get events) of the SQLite debugger entry that Code on the Go + supplies for your own debug app. Nothing a server adds later becomes visible to the model without your say-so.
diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReadOnlyTrust.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReadOnlyTrust.kt index d19cae5b1..36efda224 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReadOnlyTrust.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReadOnlyTrust.kt @@ -3,23 +3,42 @@ package com.itsaky.androidide.plugins.aiagentmcp.debugger import com.itsaky.androidide.plugins.aiagentmcp.client.McpTool /** - * Which tools of the automatic debugger entry start switched on, and which this plugin declares read-only. + * Which tools of an automatic SQLite debugger entry start switched on, and which this plugin declares + * read-only. * * Declaring a tool read-only does not skip the approval dialog today: AI-Core overrides * `requiresApproval` to true for every contributed tool (`ContributedToolHandler`), so the Agent still * asks on each call until automatic approval exists (ADFA-7147). * - * Only that entry may use this: the hint is the server's own claim, and the debugger endpoint is the - * one server whose code the IDE itself installed. A server the user adds by hand is never asked. + * Only that entry may use this: the hint is the server's own claim, and the SQLite debugger endpoint + * is the one server whose code the IDE itself installed. A server the user adds by hand is never asked. */ object ReadOnlyTrust { + /** + * The only tools of an SQLite debugger entry that start switched on, and only when the server + * advertises them with `readOnlyHint: true`. Its other tools (today `list_connections`, + * `explain_query_plan`, `get_stats` and `integrity_check`) stay known but off. + * + * Why four: AI-Core describes at most 12 contributed tools per message + * (`PromptToolBudget.MAX_CONTRIBUTED_TOOLS`) and only 4 in compact mode + * (`COMPACT_MAX_CONTRIBUTED_TOOLS`), counting them in order and dropping the rest. Every app + * gets its own entry, so with all 8 read-only tools on, two apps alone would use the whole + * normal budget. With four each, two apps use 8 of 12 and in compact mode the first app's four + * fill the budget. A hand-added server's tools are listed before any app's, so one with ten or + * more switched-on tools leaves room for only two of an app's four (none in compact mode). + * + * Phase 2 adds the SQLite debugger entry to AI-Agent-MCP's settings, so a user can switch the + * others on. + */ + val CORE_TOOLS: Set = linkedSetOf("list_databases", "get_schema", "query", "get_events") + /** * @param tools what `tools/list` returned. - * @return the names of the tools that declared `annotations.readOnlyHint` as boolean true. + * @return the names of the [CORE_TOOLS] that declared `annotations.readOnlyHint` as boolean true. */ fun enabledTools(tools: List): Set = - tools.filter { it.readOnlyHint }.mapTo(linkedSetOf()) { it.name } + tools.filter { it.readOnlyHint && it.name in CORE_TOOLS }.mapTo(linkedSetOf()) { it.name } /** * Reads the hint from one `tools/list` entry's `annotations`. diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServer.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServer.kt index eb29222ea..95bbeffaa 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServer.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServer.kt @@ -14,7 +14,8 @@ package com.itsaky.androidide.plugins.aiagentmcp.settings * @property enabledTools the tools the user switched on; empty is the default, so a new server * contributes nothing until its tools are chosen deliberately. * @property automatic true for the entry Code on the Go supplies for a debuggable app: never - * stored, no Keystore token, and the only kind whose read-only tools start on. + * stored, no Keystore token, and the only kind with tools that start on (four read-only ones, + * see `ReadOnlyTrust.CORE_TOOLS`). */ data class McpServer( val id: String, diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AppToolNamesTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AppToolNamesTest.kt index e1ab30db6..04093db5c 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AppToolNamesTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AppToolNamesTest.kt @@ -71,7 +71,7 @@ class AppToolNamesTest { } ).get(30, TimeUnit.SECONDS) - private fun debuggerTools() = arrayOf(tool("list_tables", true), tool("run_sql", false), tool("unmarked", null)) + private fun debuggerTools() = arrayOf(tool("list_databases", true), tool("run_sql", false), tool("unmarked", null)) private fun connectAll(vararg apps: Pair, reversed: Boolean = false) { val endpoints = apps.map { (id, server) -> AutomaticEndpoint(id, server.port, server.token) } diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServersTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServersTest.kt index e313a7f11..660784420 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServersTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServersTest.kt @@ -72,14 +72,14 @@ class AutomaticServersTest { var current = listOf(endpoint()) AutomaticServers.install { current } val id = AutomaticServers.idFor("com.example.app") - AutomaticServers.recordTools(id, endpoint(), listOf(McpTool("q", "", readOnlyHint = true))) + AutomaticServers.recordTools(id, endpoint(), listOf(McpTool("query", "", readOnlyHint = true))) current = listOf(endpoint(port = 4002)) AutomaticServers.refresh() val server = AutomaticServers.servers().single() - assertEquals(listOf("q"), server.knownTools) - assertEquals(setOf("q"), server.enabledTools) + assertEquals(listOf("query"), server.knownTools) + assertEquals(setOf("query"), server.enabledTools) assertTrue(server.url.endsWith(":4002/mcp")) } @@ -161,22 +161,41 @@ class AutomaticServersTest { } @Test - fun `only readOnlyHint tools of the automatic entry start on`() { + fun `only readOnlyHint core tools of the automatic entry start on`() { AutomaticServers.install { listOf(endpoint()) } val id = AutomaticServers.idFor("com.example.app") AutomaticServers.recordTools( id, endpoint(), listOf( - McpTool("reads", "", readOnlyHint = true), - McpTool("writes", "", readOnlyHint = false), - McpTool("unmarked", ""), + McpTool("query", "", readOnlyHint = true), + McpTool("get_stats", "", readOnlyHint = true), + McpTool("get_schema", "", readOnlyHint = false), + McpTool("get_events", ""), ), ) val server = AutomaticServers.servers().single() - assertEquals(listOf("reads", "writes", "unmarked"), server.knownTools) - assertEquals(setOf("reads"), server.enabledTools) - assertEquals(listOf("reads"), server.activeTools) + assertEquals(listOf("query", "get_stats", "get_schema", "get_events"), server.knownTools) + assertEquals(setOf("query"), server.enabledTools) + assertEquals(listOf("query"), server.activeTools) + } + + @Test + fun `the four core tools start on and the other four stay known but off`() { + AutomaticServers.install { listOf(endpoint()) } + val names = listOf( + "list_connections", "list_databases", "get_schema", "query", + "explain_query_plan", "get_stats", "integrity_check", "get_events", + ) + AutomaticServers.recordTools( + AutomaticServers.idFor("com.example.app"), + endpoint(), + names.map { McpTool(it, "", readOnlyHint = true) }, + ) + + val server = AutomaticServers.servers().single() + assertEquals(names, server.knownTools) + assertEquals(setOf("list_databases", "get_schema", "query", "get_events"), server.enabledTools) } } diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/CancelBetweenAttemptsTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/CancelBetweenAttemptsTest.kt index 901d4ec4c..08134d1d6 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/CancelBetweenAttemptsTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/CancelBetweenAttemptsTest.kt @@ -70,7 +70,7 @@ class CancelBetweenAttemptsTest { @Test fun `a cancel between the attempts sends nothing to the new endpoint`() { - val first = fake("t1", tool("list_tables", true)) + val first = fake("t1", tool("list_databases", true)) var stored = listOf(AutomaticEndpoint(app, first.port, "t1")) var cancelOnRead = false AutomaticServers.install { @@ -83,7 +83,7 @@ class CancelBetweenAttemptsTest { // The app relaunches: the first attempt is refused, and the retry's re-read is where the // cancel lands. first.stop() - val second = fake("t2", tool("list_tables", true)) + val second = fake("t2", tool("list_databases", true)) stored = listOf(AutomaticEndpoint(app, second.port, "t2")) cancelOnRead = true val future = invoke(name) diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReadOnlyHintParsingTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReadOnlyHintParsingTest.kt index dc940d7c4..74c724506 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReadOnlyHintParsingTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReadOnlyHintParsingTest.kt @@ -59,8 +59,23 @@ class ReadOnlyHintParsingTest { @Test fun `json null is not`() = assertFalse(hint(JSONObject.NULL).readOnlyHint) @Test - fun `trust enables exactly the true ones`() { - val tools = listOf(McpTool("a", "", readOnlyHint = true), McpTool("b", "")) - assertEquals(setOf("a"), ReadOnlyTrust.enabledTools(tools)) + fun `trust enables exactly the core tools that declared true`() { + val tools = listOf( + McpTool("query", "", readOnlyHint = true), + McpTool("get_schema", ""), + McpTool("get_stats", "", readOnlyHint = true), + ) + assertEquals(setOf("query"), ReadOnlyTrust.enabledTools(tools)) + } + + @Test + fun `the core tools are exactly these four`() { + assertEquals(setOf("list_databases", "get_schema", "query", "get_events"), ReadOnlyTrust.CORE_TOOLS) + } + + @Test + fun `a query tool that is not read only stays off`() { + val tools = listOf(McpTool("query", "", readOnlyHint = false), McpTool("list_databases", "")) + assertEquals(emptySet(), ReadOnlyTrust.enabledTools(tools)) } } diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/RelaunchToolSourceTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/RelaunchToolSourceTest.kt index a0b33707e..918a694ab 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/RelaunchToolSourceTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/RelaunchToolSourceTest.kt @@ -68,7 +68,7 @@ class RelaunchToolSourceTest { } ).get(30, TimeUnit.SECONDS) - private fun debuggerTools() = arrayOf(tool("list_tables", true), tool("run_sql", false), tool("unmarked", null)) + private fun debuggerTools() = arrayOf(tool("list_databases", true), tool("run_sql", false), tool("unmarked", null)) @Test fun `a relaunch keeps the read-only tools offered and the next call reaches the new endpoint`() { @@ -98,7 +98,7 @@ class RelaunchToolSourceTest { McpToolCatalog.connect(AutomaticServers.servers().single()) val spec = offered().values.single() - assertTrue(spec.name.endsWith("list_tables")) + assertTrue(spec.name.endsWith("list_databases")) assertFalse(spec.requiresApproval()) assertTrue(spec.isReadOnly) } From eb97b3a1f1d22cd2f287e0a0f12b19275c6894ed Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 16 Nov 2026 23:09:26 -0800 Subject: [PATCH 14/90] ADFA-7139 AI-Agent-MCP: README names the seven-character app prefix; exposedName reuses exposedNameWithPrefix README: SQLite debugger tool names keep the first seven characters of the application ID's last segment (com.example.myapplication gives db_myappli_query), not the whole segment. McpToolText: exposedName repeated the body of exposedNameWithPrefix; it now sanitises the server label and calls it. No behaviour change. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- plugins/AI-Agent-MCP/README.md | 5 +++-- .../androidide/plugins/aiagentmcp/tools/McpToolText.kt | 8 ++------ 2 files changed, 5 insertions(+), 8 deletions(-) diff --git a/plugins/AI-Agent-MCP/README.md b/plugins/AI-Agent-MCP/README.md index b3780e9b8..a380a1b06 100644 --- a/plugins/AI-Agent-MCP/README.md +++ b/plugins/AI-Agent-MCP/README.md @@ -60,8 +60,9 @@ port and token, and the plugin reads them again after a refused connection. An app that has not reported yet has no entry, and no error is shown. Each app's tools are told apart for the model. Their names start with `db_` and -the last segment of the application ID (`db_notes_query` for -`com.example.notes`); when two apps would share that prefix, both use the first +the first seven characters of the application ID's last segment +(`db_notes_query` for `com.example.notes`, `db_myappli_query` for +`com.example.myapplication`); when two apps would share that prefix, both use the first five characters of the segment and four hex digits derived from the full application ID (`notes_3fa1_query`), so a name never depends on which app was read first. Each description starts with the application ID, as diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolText.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolText.kt index 781cf00f0..faa798dbe 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolText.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolText.kt @@ -26,12 +26,8 @@ object McpToolText { * @param toolName the tool's own name. * @return the exposed name, or null when nothing usable survives sanitising. */ - fun exposedName(serverName: String, toolName: String): String? { - val tool = identifier(toolName).take(MAX_NAME_LENGTH).trim('_') - if (tool.isEmpty()) return null - val prefix = identifier(serverName).take(MAX_PREFIX_LENGTH).trim('_') - return if (prefix.isEmpty()) tool else "${prefix}_$tool" - } + fun exposedName(serverName: String, toolName: String): String? = + exposedNameWithPrefix(identifier(serverName).take(MAX_PREFIX_LENGTH).trim('_'), toolName) /** * As [exposedName], for a prefix that is already decided (see [appPrefixes]). From 71222087274b98927013a80803b40e6fe1ffce80 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Mon, 16 Nov 2026 23:10:38 -0800 Subject: [PATCH 15/90] ADFA-7139 AI-Agent-MCP: read the server list once when naming the tools to offer exposedTools read the server list for the app prefixes and again for the tool loop, so an app listed between the two reads had tools but no prefix and getValue threw. It now reads the list once and uses that snapshot for both. Test: a source whose second read of the list differs; the listing now reads once. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../plugins/aiagentmcp/tools/McpToolSource.kt | 12 +++++++---- .../aiagentmcp/debugger/AppToolNamesTest.kt | 21 +++++++++++++++++++ 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt index 7f0dd210d..81d2e37af 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt @@ -192,10 +192,11 @@ class McpToolSource : /** * Every enabled tool of every enabled server, paired with its server. + * @param servers one snapshot of the server list, so the caller's other reads agree with it. * @return the pairs, in configured order. */ - private fun enabledTools(): List> = - McpServers.all() + private fun enabledTools(servers: List): List> = + servers .filter { it.enabled } .flatMap { server -> McpToolCatalog.tools(server.id) @@ -223,12 +224,15 @@ class McpToolSource : val exposed = mutableListOf() val taken = mutableSetOf() + // Read once: an app listed between two reads would have tools here but no prefix below. + val servers = McpServers.all() + // From every automatic entry, not only those offering tools, so a prefix does not change // when another app's tools are switched off or its tool list is still empty. val appPrefixes = McpToolText.appPrefixes( - McpServers.all().filter { it.automatic }.map { AutomaticServers.applicationIdOf(it.id) }, + servers.filter { it.automatic }.map { AutomaticServers.applicationIdOf(it.id) }, ) - for ((server, tool) in enabledTools()) { + for ((server, tool) in enabledTools(servers)) { val base = if (server.automatic) { McpToolText.exposedNameWithPrefix( appPrefixes.getValue(AutomaticServers.applicationIdOf(server.id)), diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AppToolNamesTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AppToolNamesTest.kt index 04093db5c..48b210049 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AppToolNamesTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AppToolNamesTest.kt @@ -15,6 +15,7 @@ import io.mockk.every import io.mockk.mockk import io.mockk.mockkObject import io.mockk.unmockkObject +import io.mockk.verify import java.util.concurrent.TimeUnit import org.junit.After import org.junit.Assert.assertEquals @@ -116,6 +117,26 @@ class AppToolNamesTest { assertEquals(forward, byApp()) } + @Test + fun `an app listed between two reads of the server list cannot break the listing`() { + connectAll( + "com.example.notes" to fake("a", tool("query", true)), + "com.example.shop" to fake("b", tool("query", true)), + ) + val full = McpServers.all() + val before = full.filter { AutomaticServers.applicationIdOf(it.id) == "com.example.notes" } + // A second read would see the newly listed app; the listing must not make one. + mockkObject(McpServers) + try { + every { McpServers.all() } returnsMany listOf(before, full) andThen full + + assertEquals(setOf("db_notes_query"), source.listTools().map { it.name }.toSet()) + verify(exactly = 1) { McpServers.all() } + } finally { + unmockkObject(McpServers) + } + } + @Test fun `a single app still works and a hand-added server keeps its name and description`() { val debugger = fake("a", tool("query", true)) From 57477d2e2c31dafbec8e7724bc313505e7e3923c Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 18:45:40 -0800 Subject: [PATCH 16/90] ADFA-7139 AI-Agent-MCP: an Error from the host no longer crashes Code on the Go A plugin-api that does not match the host's fails with an Error (AbstractMethodError, NoSuchMethodError, another LinkageError), not an Exception. AutomaticServers.refresh caught only Exception around its read of DebuggerEndpointService.endpoints, so such an Error escaped the activation coroutine. Its scope (SupervisorJob + Dispatchers.IO) had no handler, so the Error reached Android's uncaught-exception handler and took down the IDE, whose process the plugin runs in. - refresh catches Throwable around the read, rethrows CancellationException, reports the failure through the existing RepeatedFailureLog (in full once, briefly after that) and keeps the previous entries. - McpToolCatalog.refreshAll does the same around connect, which calls the host's KeystoreSecretStore and ServerUrl: one server's Error now costs only that server, as an Exception already did. - settingsChanged guards notifyToolsChanged against Throwable, like healthChanged already guards notifyToolSourceStatusChanged: the registry is AI Core's, built against its own plugin-api. - The activation scope gets a CoroutineExceptionHandler as a backstop, logging through android.util.Log, so anything still unforeseen stops at this plugin's log. Tests: a source that throws AbstractMethodError keeps the entries unchanged and refresh returns false; startDebuggerEntry, the health probe and refreshAll survive an AbstractMethodError from the debugger service, the registry and the Keystore; an Error thrown in a coroutine of the plugin's scope never reaches the default uncaught-exception handler. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../aiagentmcp/debugger/AutomaticServers.kt | 13 +- .../plugins/aiagentmcp/plugin/McpPlugin.kt | 42 ++++- .../aiagentmcp/tools/McpToolCatalog.kt | 12 +- .../debugger/AutomaticServersTest.kt | 26 +++ .../plugin/McpPluginHostErrorTest.kt | 148 ++++++++++++++++++ 5 files changed, 231 insertions(+), 10 deletions(-) create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginHostErrorTest.kt diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt index 58701d1d4..26a4b8ce8 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt @@ -10,6 +10,7 @@ import com.itsaky.androidide.plugins.aiagentmcp.tools.McpServerHealth import com.itsaky.androidide.plugins.aiagentmcp.tools.McpToolCatalog import com.itsaky.androidide.plugins.services.DebuggerEndpoint import java.util.concurrent.CopyOnWriteArrayList +import kotlin.coroutines.cancellation.CancellationException private const val TAG = "$LOG_PREFIX.AutomaticServers" @@ -55,7 +56,10 @@ object AutomaticServers { private val endpointListeners = CopyOnWriteArrayList<(String) -> Unit>() - /** The probe calls [refresh] every 20 s, so a refused permission would otherwise log a stack trace forever. */ + /** + * The probe calls [refresh] every 20 s, so a refused permission or a plugin-api mismatch would + * otherwise log a stack trace forever. + */ private val readFailures = RepeatedFailureLog( first = { e -> Log.w(TAG, "Could not read the debugger endpoints; keeping the previous entries", e) }, later = { e -> Log.d(TAG, "Still cannot read the debugger endpoints: $e") }, @@ -131,9 +135,14 @@ object AutomaticServers { val read = source ?: return false val fresh = try { read().associateBy { idFor(it.applicationId) } - } catch (e: Exception) { + } catch (e: CancellationException) { + throw e + } catch (e: Throwable) { // A failed read is not "no apps": the entries stay as they were, since wiping them // would take every debugger tool away from the agent on a transient database error. + // Throwable, not Exception: a plugin-api that does not match the host's fails here with + // an AbstractMethodError or another LinkageError, and one that escaped would end the + // caller's coroutine in the IDE's uncaught-exception handler and crash Code on the Go. readFailures.report(e) return false } diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt index 3b0635433..4f26726e9 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt @@ -1,5 +1,6 @@ package com.itsaky.androidide.plugins.aiagentmcp.plugin +import android.util.Log import com.itsaky.androidide.plugins.IPlugin import com.itsaky.androidide.plugins.PluginContext import com.itsaky.androidide.plugins.PluginLifecycleListener @@ -7,6 +8,7 @@ import com.itsaky.androidide.plugins.aiagentmcp.R import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticServers import com.itsaky.androidide.plugins.aiagentmcp.debugger.McpServers +import com.itsaky.androidide.plugins.aiagentmcp.logging.LOG_PREFIX import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore import com.itsaky.androidide.plugins.aiagentmcp.settings.McpSettingsFragment import com.itsaky.androidide.plugins.aiagentmcp.tools.McpServerHealth @@ -20,6 +22,7 @@ import com.itsaky.androidide.plugins.extensions.SettingsExtension import com.itsaky.androidide.plugins.services.DebuggerEndpointService import com.itsaky.androidide.plugins.services.SharedServices import com.itsaky.androidide.plugins.services.ToolSourceRegistry +import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job @@ -32,6 +35,8 @@ import kotlinx.coroutines.delay import kotlinx.coroutines.isActive import kotlinx.coroutines.launch +private const val TAG = "$LOG_PREFIX.McpPlugin" + /** * Connects the Agent to Model Context Protocol servers. * @@ -118,6 +123,15 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { const val TOOLTIP_TAG_HEADER_REMOVE = "mcp_header_remove" const val TOOLTIP_TAG_BACK = "mcp_back" + /** + * Logs a failure that escaped a coroutine of [newScope]. Platform logging, not + * `context.logger`: a handler that itself threw would hand both failures to the IDE's + * uncaught-exception handler, and a scope exists before [initialize] sets the context. + */ + private val BACKSTOP = CoroutineExceptionHandler { _, e -> + Log.e(TAG, "Background work failed; it stops here and Code on the Go carries on", e) + } + @Volatile private var pluginContext: PluginContext? = null @@ -144,9 +158,19 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { } } - /** Tells the agent to re-read the tool list whenever a server or a toggle changes. */ + /** + * Tells the agent to re-read the tool list whenever a server or a toggle changes. + * + * Guarded against [Throwable], like [healthChanged]: it runs on this plugin's own coroutines, + * and the registry is AI Core's, built against a plugin-api of its own. A LinkageError from it + * would otherwise end the coroutine in the IDE's uncaught-exception handler. + */ private val settingsChanged: () -> Unit = { - resolveToolSourceRegistry()?.notifyToolsChanged(PLUGIN_ID) + try { + resolveToolSourceRegistry()?.notifyToolsChanged(PLUGIN_ID) + } catch (e: Throwable) { + context.logger.warn("McpPlugin: could not tell the agent the tools changed: $e") + } } /** @@ -314,7 +338,8 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { * `plugin.min_ide_version` keeps this plugin off an IDE that lacks the service: such an IDE * rejects the unknown `debugger.endpoints` permission when it validates the manifest. The catch * is defence only, for a host that registers no service anyway. A call that later throws (no - * permission, unreadable database) leaves the entries as they were. + * permission, unreadable database, a LinkageError from a host whose plugin-api differs) leaves + * the entries as they were: [AutomaticServers.refresh] catches it. */ private fun installDebuggerEndpoints(keepGoing: () -> Boolean) { val service = try { @@ -329,8 +354,15 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { AutomaticServers.install(AutomaticServers.fromHost { service.endpoints }, keepGoing) } - /** A fresh scope for this activation; the previous one is cancelled, never reused. */ - private fun newScope() = CoroutineScope(SupervisorJob() + Dispatchers.IO) + /** + * A fresh scope for this activation; the previous one is cancelled, never reused. + * + * [BACKSTOP] logs what escapes a coroutine here. Each host call is guarded where it is made, so + * a failure costs only that call; this catches the one nobody foresaw, which would otherwise + * reach the IDE's uncaught-exception handler and crash Code on the Go, whose process this + * plugin runs in. Internal as a seam, so a test can watch such a failure stop there. + */ + internal fun newScope() = CoroutineScope(SupervisorJob() + Dispatchers.IO + BACKSTOP) /** * Installs [next] as the current scope and cancels whichever scope it displaced. diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt index 45eab5c04..f3798644b 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt @@ -16,6 +16,7 @@ import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore import com.itsaky.androidide.plugins.aiagentmcp.transport.JsonRpc import com.itsaky.androidide.plugins.aiagentmcp.transport.McpExchangeListener import java.util.concurrent.ConcurrentHashMap +import kotlin.coroutines.cancellation.CancellationException private const val TAG = "$LOG_PREFIX.McpToolCatalog" @@ -159,9 +160,14 @@ object McpToolCatalog { try { connect(server) refreshed++ - } catch (e: Exception) { - // One unreachable server must not cost the user the tools of the others. - Log.w(TAG, "Could not list tools for '${server.name}': ${e.message}") + } catch (e: CancellationException) { + throw e + } catch (e: Throwable) { + // One unreachable server must not cost the user the tools of the others. Throwable, + // not Exception: connect calls the host (its Keystore, its ServerUrl), and a + // plugin-api that does not match the host's fails there with a LinkageError, which + // would otherwise end the activation's coroutine and crash Code on the Go. + Log.w(TAG, "Could not list tools for '${server.name}': $e") } } return refreshed diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServersTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServersTest.kt index 660784420..02f7f9860 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServersTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServersTest.kt @@ -8,6 +8,7 @@ import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNull import org.junit.Assert.assertTrue +import org.junit.Assert.fail import org.junit.Test class AutomaticServersTest { @@ -146,6 +147,31 @@ class AutomaticServersTest { assertEquals("t1", AutomaticServers.token(id)) } + /** A host whose plugin-api differs from this plugin's: an Error, which `catch (Exception)` misses. */ + @Test + fun `a read that throws a linkage error keeps the entries as they were`() { + var failing = false + AutomaticServers.install { + if (failing) throw AbstractMethodError("DebuggerEndpointService.getEndpoints") + listOf(endpoint()) + } + val id = AutomaticServers.idFor("com.example.app") + AutomaticServers.recordTools(id, endpoint(), listOf(McpTool("q", "", readOnlyHint = true))) + + failing = true + val changed = try { + AutomaticServers.refresh() + } catch (e: LinkageError) { + fail("refresh let $e escape to its caller's coroutine") + return + } + + assertFalse(changed) + val server = AutomaticServers.servers().single() + assertEquals(listOf("q"), server.knownTools) + assertEquals("t1", AutomaticServers.token(id)) + } + @Test fun `an entry that disappears has its health and cached tools forgotten`() { var current = listOf(endpoint()) diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginHostErrorTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginHostErrorTest.kt new file mode 100644 index 000000000..33fb9d1a4 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginHostErrorTest.kt @@ -0,0 +1,148 @@ +package com.itsaky.androidide.plugins.aiagentmcp.plugin + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticEndpoint +import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticServers +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpToolCatalog +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import com.itsaky.androidide.plugins.services.DebuggerEndpointService +import com.itsaky.androidide.plugins.services.SharedServices +import com.itsaky.androidide.plugins.services.ToolSourceRegistry +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import io.mockk.verify +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * A host whose plugin-api differs from the one this plugin was built against answers a call with an + * Error (AbstractMethodError, NoSuchMethodError, another LinkageError), not an Exception. On this + * plugin's own coroutines such an Error reached the IDE's uncaught-exception handler, which crashes + * Code on the Go, since a plugin runs in its process. + */ +class McpPluginHostErrorTest { + + private lateinit var context: PluginContext + private lateinit var plugin: McpPlugin + private val servers = mutableListOf() + + @Before + fun setUp() { + AutomaticServers.install(null) + context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + } + + @After + fun tearDown() { + SharedServices.unregister(ToolSourceRegistry::class.java) + AutomaticServers.install(null) + McpConnections.closeAll() + McpToolCatalog.clear() + servers.forEach { it.stop() } + plugin.dispose() + } + + private fun fake(token: String, vararg tools: org.json.JSONObject) = + FakeMcpServer(token, tools.toList()).also { servers += it } + + /** Runs [block], turning an Error that escapes it into this test's failure. */ + private fun survives(what: String, block: () -> T): T = try { + block() + } catch (e: Error) { + if (e is AssertionError) throw e + throw AssertionError("$what let $e escape", e) + } + + @Test + fun `a debugger service that throws a linkage error does not end the activation`() { + val service = mockk { + every { endpoints } throws AbstractMethodError("DebuggerEndpointService.getEndpoints") + } + every { context.services.get(DebuggerEndpointService::class.java) } returns service + + survives("startDebuggerEntry") { plugin.startDebuggerEntry { true } } + + assertTrue(AutomaticServers.servers().isEmpty()) + } + + @Test + fun `a registry that throws a linkage error does not end the health probe`() { + val active = AtomicBoolean(true) + val registry = mockk(relaxed = true) { + every { notifyToolsChanged(any()) } answers { + active.set(false) + throw AbstractMethodError("ToolSourceRegistry.notifyToolsChanged") + } + } + SharedServices.register(ToolSourceRegistry::class.java, registry) + val app = fake("t1", tool("query", true)) + AutomaticServers.install { listOf(AutomaticEndpoint("com.example.app", app.port, "t1")) } + // A bound, so a probe that never lists the tools fails the verify below instead of hanging. + val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(20) + + survives("the health probe") { + runBlocking { + plugin.probeHealth({ active.get() && System.nanoTime() < deadline }, intervalMs = 10) + } + } + + verify { registry.notifyToolsChanged(McpPlugin.PLUGIN_ID) } + } + + @Test + fun `a keystore call that throws a linkage error costs only its own server`() { + val app = fake("", tool("query", null)) + val broken = McpServerStore.saveDetails( + McpServerStore.newServer("Broken", "http://127.0.0.1:${app.port}/mcp") + ) + val working = McpServerStore.saveDetails( + McpServerStore.newServer("Working", "http://127.0.0.1:${app.port}/mcp") + ) + mockkObject(McpServerStore) + try { + every { McpServerStore.token(broken.id) } throws AbstractMethodError("KeystoreSecretStore.readAndMigrate") + every { McpServerStore.token(working.id) } returns KeystoreSecretStore.Stored.Absent + every { McpServerStore.headers(any()) } returns emptyMap() + + val answered = survives("refreshAll") { McpToolCatalog.refreshAll() } + + assertEquals(1, answered) + assertEquals(listOf("query"), McpToolCatalog.tools(working.id).map { it.name }) + } finally { + unmockkObject(McpServerStore) + } + } + + @Test + fun `an error that escapes a coroutine stops at the backstop, not at the IDE's handler`() { + val reached = CopyOnWriteArrayList() + val previous = Thread.getDefaultUncaughtExceptionHandler() + Thread.setDefaultUncaughtExceptionHandler { _, e -> reached += e } + try { + runBlocking { + plugin.newScope().launch { throw AbstractMethodError("an unguarded host call") }.join() + } + } finally { + Thread.setDefaultUncaughtExceptionHandler(previous) + } + + assertEquals("reached the IDE's uncaught-exception handler", emptyList(), reached.toList()) + } +} From 3620d18c5221ce1ebddf21a29335ea763bc48c74 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 18:45:47 -0800 Subject: [PATCH 17/90] ADFA-7139 AI-Agent-MCP: the help text names the SQLite debugger tools that start on The plugin tooltip still said every tool stays off until the user turns it on. Since 96b49e39 the automatic SQLite debugger entry turns four tools on by default (ReadOnlyTrust.CORE_TOOLS), as the README and the gallery page say. The tooltip, the in-IDE help page and the gallery card (addon.json) now say so too, and that the entry is not on the MCP servers screen in this version. "Asks for your approval every time" stays: AI-Core still asks on every call of a contributed tool until appdevforall/addons#167 lands. The merge note on #166 lists these lines for whichever of the two lands second. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- plugins/AI-Agent-MCP/addon.json | 2 +- .../src/main/assets/docs/index.html | 18 +++++++++++++----- .../plugins/aiagentmcp/plugin/McpPlugin.kt | 8 ++++++-- 3 files changed, 20 insertions(+), 8 deletions(-) diff --git a/plugins/AI-Agent-MCP/addon.json b/plugins/AI-Agent-MCP/addon.json index 08cb09121..c676d9a79 100644 --- a/plugins/AI-Agent-MCP/addon.json +++ b/plugins/AI-Agent-MCP/addon.json @@ -1,6 +1,6 @@ { "summary": "Give the Agent tools from Model Context Protocol (MCP) servers. Requires the AI Core addon and an AI backend.", - "description": "Connects to MCP servers you configure and adds the tools they offer to the AI Core Agent, next to its own. Each tool starts switched off until you enable it. When the Agent calls a tool, the arguments it chose, which can include your code, are sent to the MCP server that offers that tool. This addon adds tools, not a model, so you still need an AI backend.", + "description": "Connects to MCP servers you configure and adds the tools they offer to the AI Core Agent, next to its own. Each tool starts switched off until you enable it, except four read-only tools of the SQLite debugger entry that Code on the Go adds for your own debug app. When the Agent calls a tool, the arguments it chose, which can include your code, are sent to the MCP server that offers that tool. This addon adds tools, not a model, so you still need an AI backend.", "tags": [ "ai", "agent", diff --git a/plugins/AI-Agent-MCP/src/main/assets/docs/index.html b/plugins/AI-Agent-MCP/src/main/assets/docs/index.html index c8c449df0..e15623f92 100644 --- a/plugins/AI-Agent-MCP/src/main/assets/docs/index.html +++ b/plugins/AI-Agent-MCP/src/main/assets/docs/index.html @@ -72,16 +72,24 @@

Adding a server

Choosing tools

-

Every tool starts switched off. That is deliberate: each enabled tool - costs prompt space on every message you send, and a large server can advertise - ninety of them — enough to fill a phone-sized context window on its own. Switch - on the handful you actually want.

+

Every tool starts switched off, with the one exception below. That is + deliberate: each enabled tool costs prompt space on every message you send, and a + large server can advertise ninety of them — enough to fill a phone-sized context + window on its own. Switch on the handful you actually want.

+

The one exception is the SQLite debugger entry, which Code on the Go + adds by itself for an app you build with the SQLite debugger, named + "SQLite debugger (application ID)". Four of its read-only tools start + switched on: list_databases, get_schema, + query and get_events. Its other tools start off. This + version does not show the entry on the MCP servers screen, so it has no switches + there yet.

The Agent reads this list from memory, so tap Connect again after the server changes; a chat that is already open picks the new list up.

Approval

Every remote tool asks for your approval before it runs, showing the - arguments it would send, and there is no "always allow" for them. The Agent's + arguments it would send, and there is no "always allow" for them. That includes + the four SQLite debugger tools that start switched on. The Agent's own file tools are confined to the open project; a remote tool is confined by nothing this device controls, so the dialog is the only gate — read it.

diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt index 4f26726e9..b44c83f09 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt @@ -508,8 +508,12 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { MCP (Model Context Protocol) servers give the Agent extra tools, such as access to an issue tracker or a documentation site.

To use this add-on, you must also install AI Core. Then go to Preferences → MCP - servers and add a server. Each tool stays off until you turn it on, and - the Agent asks for your approval every time it uses one. + servers
and add a server. Each tool stays off until you turn it + on.

The one exception is the SQLite debugger entry that CoGo adds + for an app you build with the SQLite debugger: four of its read-only tools + start on (list databases, get schema, query, and get events). This version + doesn't list that entry on the MCP servers screen.

The Agent asks for + your approval every time it uses a tool, including those four. """.trimIndent(), buttons = listOf( PluginTooltipButton( From be3dc86e1703311a345717bd83e640054d20130c Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 18:45:59 -0800 Subject: [PATCH 18/90] ADFA-7139 AI-Agent-MCP: an older endpoint read never stores over a newer one AutomaticServers.refresh reads the host outside its lock and, before storing, checked only that the source was still installed. The probe's refresh and a failing call's EndpointRetry can overlap, so the read that started first could finish last and put back the endpoint the other had already replaced. The next failing call healed it through EndpointRetry, at the cost of one refused call. Each read now takes a number under the lock as it starts, and a read whose number is lower than the one already stored is dropped. Test: two interleaved refreshes, the older read released only after the newer one stored; the newer endpoint stays. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../aiagentmcp/debugger/AutomaticServers.kt | 20 ++++++++-- .../debugger/AutomaticServersTest.kt | 38 +++++++++++++++++++ 2 files changed, 55 insertions(+), 3 deletions(-) diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt index 26a4b8ce8..a611a47f9 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt @@ -52,6 +52,13 @@ object AutomaticServers { @Volatile private var source: (() -> List)? = null + /** + * Numbers each [refresh]'s read in the order the reads start, and the number of the read now + * stored. Both are guarded by this object's lock. + */ + private var readsStarted = 0L + private var storedRead = 0L + private val listeners = CopyOnWriteArrayList<() -> Unit>() private val endpointListeners = CopyOnWriteArrayList<(String) -> Unit>() @@ -126,13 +133,19 @@ object AutomaticServers { * Re-reads the endpoints. Blocking host call: use a background thread. * Nothing is stored when the source that was read is no longer installed, so a refresh in * flight when deactivation cleared the entries (or a later activation replaced the source) - * cannot restore them, whichever caller started it. + * cannot restore them, whichever caller started it. Nor is it stored when a refresh that + * started later has already stored its own: the probe's refresh and a failing call's retry can + * overlap, and the read that started first may finish last with the endpoint the other has + * already replaced. * * @param keepGoing checked after the read, before anything is stored. * @return true when the set of entries, a port or a token changed. */ fun refresh(keepGoing: () -> Boolean = { true }): Boolean { - val read = source ?: return false + val (read, ticket) = synchronized(this) { + val current = source ?: return false + current to ++readsStarted + } val fresh = try { read().associateBy { idFor(it.applicationId) } } catch (e: CancellationException) { @@ -149,7 +162,8 @@ object AutomaticServers { val moved = mutableListOf() val removed: List val changed = synchronized(this) { - if (source !== read || !keepGoing()) return false + if (source !== read || !keepGoing() || ticket < storedRead) return false + storedRead = ticket val old = states val next = fresh.mapValues { (id, endpoint) -> val previous = old[id] diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServersTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServersTest.kt index 02f7f9860..d848ae217 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServersTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServersTest.kt @@ -3,6 +3,10 @@ package com.itsaky.androidide.plugins.aiagentmcp.debugger import com.itsaky.androidide.plugins.aiagentmcp.client.McpTool import com.itsaky.androidide.plugins.aiagentmcp.tools.McpServerHealth import com.itsaky.androidide.plugins.aiagentmcp.tools.McpToolCatalog +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger +import kotlin.concurrent.thread import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse @@ -172,6 +176,40 @@ class AutomaticServersTest { assertEquals("t1", AutomaticServers.token(id)) } + /** + * The probe's refresh and a failing call's retry can overlap. The read that started first + * returns the endpoint from before the relaunch, and here it finishes last. + */ + @Test + fun `an older read that finishes last does not store over a newer one`() { + val olderEntered = CountDownLatch(1) + val releaseOlder = CountDownLatch(1) + val reads = AtomicInteger() + AutomaticServers.install { + when (reads.incrementAndGet()) { + 1 -> listOf(endpoint(port = 4000)) + 2 -> { + olderEntered.countDown() + releaseOlder.await(10, TimeUnit.SECONDS) + listOf(endpoint(port = 4000)) + } + else -> listOf(endpoint(port = 4001, token = "t2")) + } + } + val id = AutomaticServers.idFor("com.example.app") + var olderChanged = true + val older = thread { olderChanged = AutomaticServers.refresh() } + assertTrue("the older read never started", olderEntered.await(10, TimeUnit.SECONDS)) + + assertTrue(AutomaticServers.refresh()) + releaseOlder.countDown() + older.join(10_000) + + assertEquals(4001, AutomaticServers.endpoint(id)?.port) + assertEquals("t2", AutomaticServers.token(id)) + assertFalse(olderChanged) + } + @Test fun `an entry that disappears has its health and cached tools forgotten`() { var current = listOf(endpoint()) From fe8e819fce8637102a54e99609776fd370150ddd Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 18:51:46 -0800 Subject: [PATCH 19/90] ADFA-7139 AI-Agent-MCP: the docs name debugger.endpoints beside network.access The manifest has declared network.access,debugger.endpoints since 816e8cc8, but the README, the gallery page (twice), the in-IDE help page and McpPlugin's class KDoc still said the plugin declares network.access and nothing else. Each now names both permissions and says what debugger.endpoints is for: reading the SQLite debugger endpoints Code on the Go stores. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- plugins/AI-Agent-MCP/README.md | 3 ++- plugins/AI-Agent-MCP/ai-agent-mcp.html | 6 ++++-- plugins/AI-Agent-MCP/src/main/assets/docs/index.html | 4 +++- .../androidide/plugins/aiagentmcp/plugin/McpPlugin.kt | 5 +++-- 4 files changed, 12 insertions(+), 6 deletions(-) diff --git a/plugins/AI-Agent-MCP/README.md b/plugins/AI-Agent-MCP/README.md index a380a1b06..bb2f3cf03 100644 --- a/plugins/AI-Agent-MCP/README.md +++ b/plugins/AI-Agent-MCP/README.md @@ -12,7 +12,8 @@ This is a *tool* plugin, not a model backend: it adds no inference. Install `ai-core` declares the filesystem, shell and project permissions its own tools need, and **no network access**. MCP is the mirror image: it declares -`network.access` and nothing else. Keeping them apart is what lets a user install +`network.access`, plus `debugger.endpoints` to read the SQLite debugger endpoints +Code on the Go stores, and nothing else. Keeping them apart is what lets a user install the Agent without granting it the network, or add remote tools without widening what the Agent itself may touch. diff --git a/plugins/AI-Agent-MCP/ai-agent-mcp.html b/plugins/AI-Agent-MCP/ai-agent-mcp.html index 410a38967..ac29bb103 100644 --- a/plugins/AI-Agent-MCP/ai-agent-mcp.html +++ b/plugins/AI-Agent-MCP/ai-agent-mcp.html @@ -52,7 +52,8 @@

Executive overview

It is deliberately a plugin of its own rather than part of AI Core. AI Core declares the filesystem, shell and project permissions its own tools need and no network access; this plugin is the mirror image, declaring - network.access and nothing else. That split is what lets you run the + network.access, plus debugger.endpoints to read the SQLite debugger + endpoints Code on the Go stores, and nothing else. That split is what lets you run the Agent without granting it the network, or add remote tools without widening what the Agent itself may touch.

@@ -119,7 +120,8 @@

Technical architecture

which is a Kotlin Multiplatform library with no stated Android target, ships no HTTP engine, and required a Kotlin version these plugins do not standardise on.

-

The plugin declares network.access and nothing else. It holds no +

The plugin declares network.access and debugger.endpoints, which + only reads the SQLite debugger endpoints Code on the Go stores, and nothing else. It holds no filesystem, shell or project permission, so it cannot read your project; project content reaches a server only if the model puts it in a tool argument and you approve that call.

diff --git a/plugins/AI-Agent-MCP/src/main/assets/docs/index.html b/plugins/AI-Agent-MCP/src/main/assets/docs/index.html index e15623f92..8cead601b 100644 --- a/plugins/AI-Agent-MCP/src/main/assets/docs/index.html +++ b/plugins/AI-Agent-MCP/src/main/assets/docs/index.html @@ -96,7 +96,9 @@

Approval

What is sent

  • The tool's arguments, as the model composed them, to that server only.
  • -
  • Nothing else: this plugin has network access and no other permission. +
  • Nothing else: this plugin has network access, plus + debugger.endpoints to read the SQLite debugger endpoints Code on the Go + stores, and no other permission. It cannot read your project or your files. Anything from your project reaches a server only if the model puts it in an argument and you approve the call.
  • Server and tool names are reduced here to the alphabet a tool name may diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt index b44c83f09..fb8505433 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt @@ -41,8 +41,9 @@ private const val TAG = "$LOG_PREFIX.McpPlugin" * Connects the Agent to Model Context Protocol servers. * * Deliberately a plugin of its own rather than part of AI Core: everything here is network work, - * so it declares `network.access` and nothing else, while AI Core declares the filesystem, shell - * and project permissions its own tools need and no network at all. + * so it declares `network.access`, plus `debugger.endpoints` to read the SQLite debugger endpoints + * Code on the Go stores, and nothing else, while AI Core declares the filesystem, shell and project + * permissions its own tools need and no network at all. */ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { From 21944cf0e897dc228f90f44c2d72397f71d288b8 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 21:53:05 -0800 Subject: [PATCH 20/90] ADFA-7139 AI-Agent-MCP: an OutOfMemoryError from the host reaches the IDE's handler again 57477d2e widened the catches around host calls from Exception to Throwable so that a LinkageError from a mismatched plugin-api would not crash Code on the Go. Throwable also takes in VirtualMachineError (OutOfMemoryError, StackOverflowError) and ThreadDeath. An OutOfMemoryError in the endpoint read was then logged every 20 s as a failed read, and the coroutine backstop swallowed one from any coroutine of the plugin instead of letting the IDE's handler see it. - AutomaticServers.refresh and McpToolCatalog.refreshAll catch Exception and LinkageError only, still rethrowing CancellationException first. - The backstop rethrows a VirtualMachineError or a ThreadDeath. The coroutine machinery passes a failure its handler rethrows, unwrapped, to the thread's uncaught-exception handler. Anything else is logged as before. - The other guards on paths that reach the host follow the same rule: McpPlugin's registry and service calls (settingsChanged, healthChanged, installDebuggerEndpoints, register/unregisterToolSource, resolveToolSourceRegistry), the connect calls of the probe and the relist, dispose's listener removal, the listener loops of McpServerStore, McpServerHealth and AutomaticServers (their listeners tell the host), and McpSession.close and McpConnections' closes (the DELETE reads the Keystore). runCatchingRecoverable is runCatching with that rule. - McpToolSource.runTool keeps Throwable, with a comment: it runs inside CompletableFuture.supplyAsync, which catches every Throwable itself, so narrowing it would only hand AI Core an exceptional future instead of a failure outcome. Tests: a read that throws OutOfMemoryError makes refresh throw it; an OutOfMemoryError escaping a coroutine of the plugin's scope reaches the default uncaught-exception handler; each other narrowed guard lets an OutOfMemoryError from its host call or listener through. The five linkage-error tests still pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../aiagentmcp/client/McpConnections.kt | 7 +- .../plugins/aiagentmcp/client/McpSession.kt | 10 +- .../aiagentmcp/debugger/AutomaticServers.kt | 21 +- .../plugins/aiagentmcp/errors/Recoverable.kt | 21 ++ .../plugins/aiagentmcp/plugin/McpPlugin.kt | 69 +++-- .../aiagentmcp/settings/McpServerStore.kt | 9 +- .../aiagentmcp/tools/McpServerHealth.kt | 9 +- .../aiagentmcp/tools/McpToolCatalog.kt | 17 +- .../plugins/aiagentmcp/tools/McpToolSource.kt | 4 + .../debugger/AutomaticServersTest.kt | 32 ++ .../plugin/McpPluginFatalErrorTest.kt | 288 ++++++++++++++++++ 11 files changed, 445 insertions(+), 42 deletions(-) create mode 100644 plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/Recoverable.kt create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginFatalErrorTest.kt diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt index e1f469474..e1289e8ce 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt @@ -2,6 +2,7 @@ package com.itsaky.androidide.plugins.aiagentmcp.client import android.util.Log import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticServers +import com.itsaky.androidide.plugins.aiagentmcp.errors.runCatchingRecoverable import com.itsaky.androidide.plugins.aiagentmcp.logging.LOG_PREFIX import com.itsaky.androidide.plugins.aiagentmcp.security.UnavailableSecretException import com.itsaky.androidide.plugins.aiagentmcp.security.UnreadableSecretException @@ -65,19 +66,19 @@ object McpConnections { stale?.let { Log.i(TAG, "Server '${server.name}' changed; dropping its session") - runCatching { it.close() } + runCatchingRecoverable { it.close() } } return session } /** Drops the session for [serverId], ending it server-side when it had one. */ fun invalidate(serverId: String) { - sessions.remove(serverId)?.second?.let { runCatching { it.close() } } + sessions.remove(serverId)?.second?.let { runCatchingRecoverable { it.close() } } } /** Ends every session, for the plugin shutting down. */ fun closeAll() { - sessions.values.forEach { (_, session) -> runCatching { session.close() } } + sessions.values.forEach { (_, session) -> runCatchingRecoverable { session.close() } } sessions.clear() } diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSession.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSession.kt index fe5fcaa4c..9371499da 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSession.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSession.kt @@ -2,6 +2,7 @@ package com.itsaky.androidide.plugins.aiagentmcp.client import android.util.Log import com.itsaky.androidide.plugins.aiagentmcp.debugger.ReadOnlyTrust +import com.itsaky.androidide.plugins.aiagentmcp.errors.runCatchingRecoverable import com.itsaky.androidide.plugins.aiagentmcp.logging.LOG_PREFIX import com.itsaky.androidide.plugins.aiagentmcp.transport.JsonRpc import com.itsaky.androidide.plugins.aiagentmcp.transport.McpExchangeListener @@ -193,11 +194,16 @@ class McpSession( runCatching { liveConnection?.disconnect() } } - /** Ends the server-side session, if there is one, and forgets the handshake. */ + /** + * Ends the server-side session, if there is one, and forgets the handshake. + * + * The DELETE is best effort; its credentials come from the host's Keystore, so a LinkageError + * is survived as well as an Exception, and any other Error propagates. + */ @Synchronized fun close() { sessionId?.let { id -> - runCatching { + runCatchingRecoverable { val current = credentials() http.deleteSession(endpoint, current.token, id, current.headers) } diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt index a611a47f9..487cedb75 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt @@ -3,6 +3,7 @@ package com.itsaky.androidide.plugins.aiagentmcp.debugger import android.util.Log import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections import com.itsaky.androidide.plugins.aiagentmcp.client.McpTool +import com.itsaky.androidide.plugins.aiagentmcp.errors.runCatchingRecoverable import com.itsaky.androidide.plugins.aiagentmcp.logging.LOG_PREFIX import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServer import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore @@ -138,6 +139,9 @@ object AutomaticServers { * overlap, and the read that started first may finish last with the endpoint the other has * already replaced. * + * A read that fails with an Exception or a LinkageError leaves the entries as they were; any + * other Error, an OutOfMemoryError above all, propagates to the caller. + * * @param keepGoing checked after the read, before anything is stored. * @return true when the set of entries, a port or a token changed. */ @@ -150,12 +154,18 @@ object AutomaticServers { read().associateBy { idFor(it.applicationId) } } catch (e: CancellationException) { throw e - } catch (e: Throwable) { + } catch (e: Exception) { // A failed read is not "no apps": the entries stay as they were, since wiping them // would take every debugger tool away from the agent on a transient database error. - // Throwable, not Exception: a plugin-api that does not match the host's fails here with - // an AbstractMethodError or another LinkageError, and one that escaped would end the - // caller's coroutine in the IDE's uncaught-exception handler and crash Code on the Go. + readFailures.report(e) + return false + } catch (e: LinkageError) { + // Treated as a failed read too: a plugin-api that does not match the host's fails here + // with an AbstractMethodError or another LinkageError, and one that escaped would end + // the caller's coroutine in the IDE's uncaught-exception handler and crash Code on the + // Go. Nothing broader than these two: an OutOfMemoryError or a StackOverflowError is + // the process failing, not the read, and has to reach that handler rather than be + // logged here every 20 s as a read that failed. readFailures.report(e) return false } @@ -246,8 +256,9 @@ object AutomaticServers { /** The application ID an automatic entry's id was made from. */ fun applicationIdOf(serverId: String) = serverId.removePrefix(ID_PREFIX) + /** A listener that tells the host may fail like any host call; see [runCatchingRecoverable]. */ private fun fireChanged() { - for (l in listeners) runCatching { l() } + for (l in listeners) runCatchingRecoverable { l() } } } diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/Recoverable.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/Recoverable.kt new file mode 100644 index 000000000..9493ebb70 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/Recoverable.kt @@ -0,0 +1,21 @@ +package com.itsaky.androidide.plugins.aiagentmcp.errors + +/** + * As [runCatching], but catching only what this plugin can recover from: an [Exception], or a + * [LinkageError], which is how a host whose plugin-api differs from this plugin's fails a call + * (AbstractMethodError, NoSuchMethodError, NoClassDefFoundError). + * + * Any other Error propagates, a [VirtualMachineError] (OutOfMemoryError, StackOverflowError) above + * all: it means the process is failing, not one call, and the IDE's uncaught-exception handler has + * to see it rather than this plugin quietly carrying on. + * + * @param block the work, usually one that reaches the host directly or through a listener. + * @return its value, or the recoverable failure it threw. + */ +internal inline fun runCatchingRecoverable(block: () -> T): Result = try { + Result.success(block()) +} catch (e: Exception) { + Result.failure(e) +} catch (e: LinkageError) { + Result.failure(e) +} diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt index fb8505433..a4db642fd 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt @@ -8,6 +8,7 @@ import com.itsaky.androidide.plugins.aiagentmcp.R import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticServers import com.itsaky.androidide.plugins.aiagentmcp.debugger.McpServers +import com.itsaky.androidide.plugins.aiagentmcp.errors.runCatchingRecoverable import com.itsaky.androidide.plugins.aiagentmcp.logging.LOG_PREFIX import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore import com.itsaky.androidide.plugins.aiagentmcp.settings.McpSettingsFragment @@ -128,8 +129,14 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { * Logs a failure that escaped a coroutine of [newScope]. Platform logging, not * `context.logger`: a handler that itself threw would hand both failures to the IDE's * uncaught-exception handler, and a scope exists before [initialize] sets the context. + * + * A [VirtualMachineError] (OutOfMemoryError, StackOverflowError) or a [ThreadDeath] is + * rethrown instead: it is the process failing, not this plugin's work, and the IDE's + * handler has to see it. The coroutine machinery hands a failure its handler rethrows, + * unwrapped, to the thread's uncaught-exception handler. */ private val BACKSTOP = CoroutineExceptionHandler { _, e -> + if (e is VirtualMachineError || e is ThreadDeath) throw e Log.e(TAG, "Background work failed; it stops here and Code on the Go carries on", e) } @@ -162,14 +169,17 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { /** * Tells the agent to re-read the tool list whenever a server or a toggle changes. * - * Guarded against [Throwable], like [healthChanged]: it runs on this plugin's own coroutines, - * and the registry is AI Core's, built against a plugin-api of its own. A LinkageError from it - * would otherwise end the coroutine in the IDE's uncaught-exception handler. + * Guarded against a [LinkageError] as well as an [Exception], like [healthChanged]: it runs on + * this plugin's own coroutines, and the registry is AI Core's, built against a plugin-api of + * its own. A LinkageError from it would otherwise end the coroutine in the IDE's + * uncaught-exception handler. Nothing broader: an OutOfMemoryError has to reach that handler. */ private val settingsChanged: () -> Unit = { try { resolveToolSourceRegistry()?.notifyToolsChanged(PLUGIN_ID) - } catch (e: Throwable) { + } catch (e: Exception) { + context.logger.warn("McpPlugin: could not tell the agent the tools changed: $e") + } catch (e: LinkageError) { context.logger.warn("McpPlugin: could not tell the agent the tools changed: $e") } } @@ -181,7 +191,9 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { private val healthChanged: () -> Unit = { try { if (registered) resolveToolSourceRegistry()?.notifyToolSourceStatusChanged(PLUGIN_ID) - } catch (e: Throwable) { + } catch (e: Exception) { + context.logger.debug("McpPlugin: could not report a health change: ${e.message}") + } catch (e: LinkageError) { // An AI Core built before contract 2 has no such method; its tags cannot show health. context.logger.debug("McpPlugin: could not report a health change: ${e.message}") } @@ -195,7 +207,7 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { scope.launch { val server = McpServers.all().firstOrNull { it.id == id && it.enabled } if (server != null) { - runCatching { McpToolCatalog.connect(server) } + runCatchingRecoverable { McpToolCatalog.connect(server) } if (isActive) settingsChanged() } } @@ -260,7 +272,7 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { } override fun dispose() { - runCatching { context.removePluginLifecycleListener(aiCoreLifecycle) } + runCatchingRecoverable { context.removePluginLifecycleListener(aiCoreLifecycle) } McpServerStore.removeChangeListener(settingsChanged) AutomaticServers.removeChangeListener(settingsChanged) McpServerHealth.removeChangeListener(healthChanged) @@ -306,7 +318,7 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { if (!keepGoing()) return@async false val before = McpToolCatalog.tools(server.id) // Recorded by connect itself; a failure here is what the tag already shows. - runCatching { McpToolCatalog.connect(server) } + runCatchingRecoverable { McpToolCatalog.connect(server) } McpToolCatalog.tools(server.id) != before } }.awaitAll().any { it } @@ -343,11 +355,9 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { * the entries as they were: [AutomaticServers.refresh] catches it. */ private fun installDebuggerEndpoints(keepGoing: () -> Boolean) { - val service = try { + val service = runCatchingRecoverable { context.services.get(DebuggerEndpointService::class.java) - } catch (e: Throwable) { - null - } + }.getOrNull() if (service == null) { context.logger.info("McpPlugin: this IDE has no debugger endpoint service") return @@ -361,7 +371,8 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { * [BACKSTOP] logs what escapes a coroutine here. Each host call is guarded where it is made, so * a failure costs only that call; this catches the one nobody foresaw, which would otherwise * reach the IDE's uncaught-exception handler and crash Code on the Go, whose process this - * plugin runs in. Internal as a seam, so a test can watch such a failure stop there. + * plugin runs in. A VirtualMachineError or a ThreadDeath it passes on to that handler. Internal + * as a seam, so a test can watch where such a failure ends up. */ internal fun newScope() = CoroutineScope(SupervisorJob() + Dispatchers.IO + BACKSTOP) @@ -414,9 +425,10 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { /** * Registers this plugin's tools with AI Core, if the registry is reachable. * - * Guarded against [Throwable] rather than [Exception]: on an IDE older than the release that - * ships the contract the class is simply absent, and a [NoClassDefFoundError] here would fail - * the whole plugin rather than the one thing it cannot do. + * Guarded against a [LinkageError] as well as an [Exception]: on an IDE older than the release + * that ships the contract the class is simply absent, and a [NoClassDefFoundError] here would + * fail the whole plugin rather than the one thing it cannot do. Nothing broader: an + * OutOfMemoryError has to reach the IDE's uncaught-exception handler. * * @return true when registered (now or already), false when AI Core is absent. */ @@ -430,24 +442,30 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { registered = true context.logger.info("McpPlugin: registered the MCP tool source with AI Core") true - } catch (e: Throwable) { + } catch (e: Exception) { + context.logger.error("McpPlugin: could not register the MCP tool source", e) + false + } catch (e: LinkageError) { context.logger.error("McpPlugin: could not register the MCP tool source", e) false } } - /** Withdraws the tools, so a disabled plugin stops appearing in the agent's tool list. */ + /** + * Withdraws the tools, so a disabled plugin stops appearing in the agent's tool list. + * + * Guarded like [registerToolSource]: an Exception or a LinkageError is logged, anything else + * propagates. + */ private fun unregisterToolSource() { if (!registered) return val source = toolSource - try { + runCatchingRecoverable { if (source != null) { resolveToolSourceRegistry()?.unregisterToolSource(source) context.logger.info("McpPlugin: unregistered the MCP tool source") } - } catch (e: Throwable) { - context.logger.warn("McpPlugin: could not unregister the MCP tool source", e) - } + }.onFailure { e -> context.logger.warn("McpPlugin: could not unregister the MCP tool source", e) } registered = false } @@ -463,12 +481,13 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { /** * Resolves AI Core's tool registry, preferring the process-global registry and falling back to * the provider-scoped lookup so a registry cleared by another plugin is not fatal. - * @return the registry, or null when AI Core is absent or too old to carry the contract. + * @return the registry, or null when AI Core is absent or too old to carry the contract, or + * the lookup failed with an Exception or a LinkageError. Any other Error propagates. */ - private fun resolveToolSourceRegistry(): ToolSourceRegistry? = try { + private fun resolveToolSourceRegistry(): ToolSourceRegistry? = runCatchingRecoverable { SharedServices.get(ToolSourceRegistry::class.java) ?: context.getPluginService(AI_CORE_PLUGIN_ID, ToolSourceRegistry::class.java) - } catch (e: Throwable) { + }.getOrElse { e -> context.logger.warn("McpPlugin: could not resolve the tool registry: ${e.message}") null } diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStore.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStore.kt index 1cd47b47f..a6c33fb01 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStore.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStore.kt @@ -338,11 +338,18 @@ object McpServerStore { private fun prefs(): SharedPreferences? = McpPlugin.getContext()?.getPluginSharedPreferences(PREFERENCE_FILE) + /** + * Tells every listener, one failing listener costing only itself. A listener may call the + * host, so a LinkageError is survived as well as an Exception; anything else, an + * OutOfMemoryError above all, propagates to whoever made the change. + */ private fun fireChanged() { for (listener in listeners) { try { listener() - } catch (e: Throwable) { + } catch (e: Exception) { + Log.e(TAG, "A settings change listener threw", e) + } catch (e: LinkageError) { Log.e(TAG, "A settings change listener threw", e) } } diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpServerHealth.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpServerHealth.kt index 168722041..f068df2b5 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpServerHealth.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpServerHealth.kt @@ -94,11 +94,18 @@ object McpServerHealth { if (byServer.put(serverId, health) != health) fireChanged() } + /** + * Tells every listener, one failing listener costing only itself. A listener may call the + * host, so a LinkageError is survived as well as an Exception; anything else, an + * OutOfMemoryError above all, propagates to whoever made the change. + */ private fun fireChanged() { for (listener in listeners) { try { listener() - } catch (e: Throwable) { + } catch (e: Exception) { + Log.e(TAG, "A health change listener threw", e) + } catch (e: LinkageError) { Log.e(TAG, "A health change listener threw", e) } } diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt index f3798644b..c80b8a219 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt @@ -147,6 +147,9 @@ object McpToolCatalog { * a cancelled refresh carries on filling this cache and [McpConnections] after both were * cleared, leaving sockets nothing can reach. * + * A server that fails with an Exception or a LinkageError is skipped; any other Error, an + * OutOfMemoryError above all, ends the walk and propagates. + * * @param keepGoing false once the caller has stopped caring; the walk stops there. * @return how many servers answered. */ @@ -162,11 +165,15 @@ object McpToolCatalog { refreshed++ } catch (e: CancellationException) { throw e - } catch (e: Throwable) { - // One unreachable server must not cost the user the tools of the others. Throwable, - // not Exception: connect calls the host (its Keystore, its ServerUrl), and a - // plugin-api that does not match the host's fails there with a LinkageError, which - // would otherwise end the activation's coroutine and crash Code on the Go. + } catch (e: Exception) { + // One unreachable server must not cost the user the tools of the others. + Log.w(TAG, "Could not list tools for '${server.name}': $e") + } catch (e: LinkageError) { + // Costs only this server too: connect calls the host (its Keystore, its ServerUrl), + // and a plugin-api that does not match the host's fails there with a LinkageError, + // which would otherwise end the activation's coroutine and crash Code on the Go. + // Nothing broader: an OutOfMemoryError is the process failing, not this server, and + // has to reach the IDE's uncaught-exception handler. Log.w(TAG, "Could not list tools for '${server.name}': $e") } } diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt index 81d2e37af..98cfbce1e 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt @@ -171,6 +171,10 @@ class McpToolSource : McpServerHealth.available(server.id) Outcome(result.success, result.text, result.errorMessage) } catch (e: Throwable) { + // Throwable, unlike the other host-facing catches in this plugin: this runs inside + // CompletableFuture.supplyAsync, which catches every Throwable itself, so narrowing this + // would not bring an OutOfMemoryError to the IDE's handler. It would only hand AI Core an + // exceptionally completed future in place of the failure outcome it expects. Log.w(TAG, "Tool '${tool.name}' on '${server.name}' failed", e) McpToolCatalog.recordFailure(server, e) val context = McpPlugin.getContext()?.androidContext diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServersTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServersTest.kt index d848ae217..fe68c8ad1 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServersTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServersTest.kt @@ -11,6 +11,7 @@ import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows import org.junit.Assert.assertTrue import org.junit.Assert.fail import org.junit.Test @@ -210,6 +211,37 @@ class AutomaticServersTest { assertFalse(olderChanged) } + /** The process failing, not the read: the IDE's handler has to see it, not a log line every 20 s. */ + @Test + fun `a read that throws an OutOfMemoryError reaches the caller`() { + var failing = false + AutomaticServers.install { + if (failing) throw OutOfMemoryError("reading the debugger endpoints") + listOf(endpoint()) + } + + failing = true + val thrown = assertThrows(OutOfMemoryError::class.java) { AutomaticServers.refresh() } + + assertEquals("reading the debugger endpoints", thrown.message) + } + + /** The listener added on activation tells the host, so it can fail like a host call. */ + @Test + fun `a change listener that throws an OutOfMemoryError reaches the caller`() { + var current = listOf(endpoint()) + AutomaticServers.install { current } + val listener: () -> Unit = { throw OutOfMemoryError("telling the agent") } + AutomaticServers.addChangeListener(listener) + try { + current = listOf(endpoint(port = 4001)) + + assertThrows(OutOfMemoryError::class.java) { AutomaticServers.refresh() } + } finally { + AutomaticServers.removeChangeListener(listener) + } + } + @Test fun `an entry that disappears has its health and cached tools forgotten`() { var current = listOf(endpoint()) diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginFatalErrorTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginFatalErrorTest.kt new file mode 100644 index 000000000..ce5abe483 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginFatalErrorTest.kt @@ -0,0 +1,288 @@ +package com.itsaky.androidide.plugins.aiagentmcp.plugin + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticEndpoint +import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticServers +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServer +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpServerHealth +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpToolCatalog +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import com.itsaky.androidide.plugins.services.DebuggerEndpoint +import com.itsaky.androidide.plugins.services.DebuggerEndpointService +import com.itsaky.androidide.plugins.services.SharedServices +import com.itsaky.androidide.plugins.services.ToolSourceRegistry +import io.mockk.Runs +import io.mockk.every +import io.mockk.just +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicInteger +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertSame +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * An OutOfMemoryError (or a StackOverflowError, or a ThreadDeath) is the process failing, not one + * host call. The guards that keep a LinkageError from a mismatched plugin-api away from the IDE's + * uncaught-exception handler must let it through: caught, it was logged as an ordinary failure, + * every 20 s on the probe's path, and the IDE never learnt of it. + */ +class McpPluginFatalErrorTest { + + private lateinit var context: PluginContext + private lateinit var plugin: McpPlugin + private val servers = mutableListOf() + + @Before + fun setUp() { + AutomaticServers.install(null) + context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + } + + @After + fun tearDown() { + // First, so no listener of this plugin hears the cleanup below. + plugin.dispose() + SharedServices.unregister(ToolSourceRegistry::class.java) + AutomaticServers.install(null) + McpConnections.closeAll() + McpToolCatalog.clear() + servers.forEach { it.stop() } + } + + private fun fake(token: String, vararg tools: JSONObject, sessionId: String? = null) = + FakeMcpServer(token, tools.toList(), sessionId).also { servers += it } + + private fun userServer(port: Int): McpServer = + McpServerStore.saveDetails(McpServerStore.newServer("Server", "http://127.0.0.1:$port/mcp")) + + /** Runs [block] with the default uncaught-exception handler replaced; returns what reached it. */ + private fun reachingDefaultHandler(waitMs: Long = 0, block: () -> Unit): List { + val reached = CopyOnWriteArrayList() + val first = CountDownLatch(1) + val previous = Thread.getDefaultUncaughtExceptionHandler() + Thread.setDefaultUncaughtExceptionHandler { _, e -> + reached += e + first.countDown() + } + try { + block() + if (waitMs > 0) first.await(waitMs, TimeUnit.MILLISECONDS) + } finally { + Thread.setDefaultUncaughtExceptionHandler(previous) + } + return reached.toList() + } + + private fun awaitUntil(what: String, condition: () -> Boolean) { + val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10) + while (!condition()) { + check(System.nanoTime() < deadline) { "timed out waiting until $what" } + Thread.sleep(10) + } + } + + @Test + fun `an OutOfMemoryError that escapes a coroutine reaches the IDE's handler`() { + val error = OutOfMemoryError("in a coroutine of the plugin's scope") + + val reached = reachingDefaultHandler { + runBlocking { plugin.newScope().launch { throw error }.join() } + } + + assertEquals(1, reached.size) + assertSame(error, reached.single()) + } + + @Test + fun `a keystore call that throws an OutOfMemoryError ends the refresh`() { + val server = userServer(fake("", tool("query", null)).port) + mockkObject(McpServerStore) + try { + every { McpServerStore.token(server.id) } throws OutOfMemoryError("KeystoreSecretStore.readAndMigrate") + + assertThrows(OutOfMemoryError::class.java) { McpToolCatalog.refreshAll() } + } finally { + unmockkObject(McpServerStore) + } + } + + @Test + fun `a keystore call that throws an OutOfMemoryError ends the health probe`() { + val server = userServer(fake("", tool("query", null)).port) + val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(3) + mockkObject(McpServerStore) + try { + every { McpServerStore.token(server.id) } throws OutOfMemoryError("KeystoreSecretStore.readAndMigrate") + + assertThrows(OutOfMemoryError::class.java) { + runBlocking { plugin.probeHealth({ System.nanoTime() < deadline }, intervalMs = 10) } + } + } finally { + unmockkObject(McpServerStore) + } + } + + @Test + fun `a registry that throws an OutOfMemoryError ends the health probe`() { + val active = AtomicBoolean(true) + val registry = mockk(relaxed = true) { + every { notifyToolsChanged(any()) } answers { + active.set(false) + throw OutOfMemoryError("ToolSourceRegistry.notifyToolsChanged") + } + } + SharedServices.register(ToolSourceRegistry::class.java, registry) + val app = fake("t1", tool("query", true)) + AutomaticServers.install { listOf(AutomaticEndpoint("com.example.app", app.port, "t1")) } + val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(20) + + assertThrows(OutOfMemoryError::class.java) { + runBlocking { + plugin.probeHealth({ active.get() && System.nanoTime() < deadline }, intervalMs = 10) + } + } + } + + @Test + fun `a debugger service lookup that throws an OutOfMemoryError reaches the caller`() { + every { context.services.get(DebuggerEndpointService::class.java) } throws + OutOfMemoryError("PluginContext.services.get") + + assertThrows(OutOfMemoryError::class.java) { plugin.startDebuggerEntry { true } } + } + + @Test + fun `a registry lookup that throws an OutOfMemoryError ends the activation`() { + every { context.getPluginService(any(), ToolSourceRegistry::class.java) } throws + OutOfMemoryError("PluginContext.getPluginService") + try { + assertThrows(OutOfMemoryError::class.java) { plugin.activate() } + } finally { + every { context.getPluginService(any(), ToolSourceRegistry::class.java) } returns null + } + } + + @Test + fun `a registration that throws an OutOfMemoryError ends the activation`() { + val registry = mockk(relaxed = true) { + every { registerToolSource(any()) } throws OutOfMemoryError("ToolSourceRegistry.registerToolSource") + } + SharedServices.register(ToolSourceRegistry::class.java, registry) + + assertThrows(OutOfMemoryError::class.java) { plugin.activate() } + } + + @Test + fun `an unregistration that throws an OutOfMemoryError ends the deactivation`() { + val registry = mockk(relaxed = true) + SharedServices.register(ToolSourceRegistry::class.java, registry) + assertTrue(plugin.activate()) + every { registry.unregisterToolSource(any()) } throws + OutOfMemoryError("ToolSourceRegistry.unregisterToolSource") + try { + assertThrows(OutOfMemoryError::class.java) { plugin.deactivate() } + } finally { + every { registry.unregisterToolSource(any()) } just Runs + } + } + + @Test + fun `a health report that throws an OutOfMemoryError reaches whoever changed the health`() { + val registry = mockk(relaxed = true) + SharedServices.register(ToolSourceRegistry::class.java, registry) + assertTrue(plugin.activate()) + every { registry.notifyToolSourceStatusChanged(any()) } throws + OutOfMemoryError("ToolSourceRegistry.notifyToolSourceStatusChanged") + try { + assertThrows(OutOfMemoryError::class.java) { McpServerHealth.available("a-server") } + } finally { + every { registry.notifyToolSourceStatusChanged(any()) } just Runs + } + } + + @Test + fun `a settings listener that throws an OutOfMemoryError reaches whoever changed the settings`() { + val listener: () -> Unit = { throw OutOfMemoryError("telling the agent") } + McpServerStore.addChangeListener(listener) + try { + assertThrows(OutOfMemoryError::class.java) { userServer(1) } + } finally { + McpServerStore.removeChangeListener(listener) + } + } + + @Test + fun `a keystore call that throws an OutOfMemoryError while closing a session reaches the caller`() { + val server = userServer(fake("", tool("query", null), sessionId = "s1").port) + mockkObject(McpServerStore) + try { + every { McpServerStore.token(server.id) } returns KeystoreSecretStore.Stored.Absent + every { McpServerStore.headers(any()) } returns emptyMap() + McpToolCatalog.connect(server) + every { McpServerStore.token(server.id) } throws OutOfMemoryError("KeystoreSecretStore.readAndMigrate") + + assertThrows(OutOfMemoryError::class.java) { McpConnections.closeAll() } + } finally { + unmockkObject(McpServerStore) + } + } + + @Test + fun `dispose lets an OutOfMemoryError from the host through`() { + every { context.removePluginLifecycleListener(any()) } throws + OutOfMemoryError("PluginContext.removePluginLifecycleListener") + try { + assertThrows(OutOfMemoryError::class.java) { plugin.dispose() } + } finally { + every { context.removePluginLifecycleListener(any()) } just Runs + } + } + + @Test + fun `a relist that throws an OutOfMemoryError reaches the IDE's handler`() { + val app = fake("t1", tool("query", true)) + val currentPort = AtomicInteger(app.port) + val service = mockk { + every { endpoints } answers { listOf(DebuggerEndpoint("com.example.app", currentPort.get(), "t1", 0L)) } + } + every { context.services.get(DebuggerEndpointService::class.java) } returns service + val id = AutomaticServers.idFor("com.example.app") + assertTrue(plugin.activate()) + // The activation's own refresh lists the tools; after it only a relist connects, until the + // probe's first cycle 20 s later. + awaitUntil("the activation listed the tools") { McpToolCatalog.tools(id).isNotEmpty() } + mockkObject(McpToolCatalog) + try { + every { McpToolCatalog.connect(any(), any()) } throws OutOfMemoryError("relisting a relaunched app") + + val reached = reachingDefaultHandler(waitMs = 10_000) { + currentPort.set(app.port + 1) + AutomaticServers.refresh() + } + + assertTrue("reached the IDE's handler: $reached", reached.firstOrNull() is OutOfMemoryError) + } finally { + unmockkObject(McpToolCatalog) + } + } +} From d68fde9424905371e6b5588bc9e6d2fccc5fac07 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Tue, 17 Nov 2026 21:53:42 -0800 Subject: [PATCH 21/90] ADFA-7139 AI-Agent-MCP: min_ide_version is 26.48, since 26.47 shipped without the service Code on the Go 26.47 was released on 2026-11-17 without DebuggerEndpointService or the debugger.endpoints permission: the CoGo stack that adds them (#2259 to #2261) is not merged yet. So the first release that can ship them is 26.48. plugin.min_ide_version, its manifest comment, the plugin README and plugins/README.md now say 26.48 or later. 26.48 is still a guess, valid only if the stack merges before that release is cut. The manifest and both READMEs say to recheck it against the real release number before merging. The plugin manager only displays min_ide_version and checks it is not blank; it never compares it with the running version, so a debug build of Code on the Go still loads the plugin. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- plugins/AI-Agent-MCP/README.md | 9 +++++---- .../AI-Agent-MCP/src/main/AndroidManifest.xml | 20 ++++++++++--------- plugins/README.md | 3 ++- 3 files changed, 18 insertions(+), 14 deletions(-) diff --git a/plugins/AI-Agent-MCP/README.md b/plugins/AI-Agent-MCP/README.md index bb2f3cf03..8a1461e13 100644 --- a/plugins/AI-Agent-MCP/README.md +++ b/plugins/AI-Agent-MCP/README.md @@ -55,7 +55,7 @@ For an app built in Code on the Go with `cogo.sqliteDebugger=true`, the plugin adds a server entry on its own, named "SQLite debugger ()", with no URL or token to type. Code on the Go stores the port and token the running debug app reports; the plugin reads them through the `DebuggerEndpointService` -(permission `debugger.endpoints`, so it needs Code on the Go 26.47 or later) and +(permission `debugger.endpoints`, so it needs Code on the Go 26.48 or later) and points the entry at `http://127.0.0.1:/mcp`. A relaunched app gets a new port and token, and the plugin reads them again after a refused connection. An app that has not reported yet has no entry, and no error is shown. @@ -147,10 +147,11 @@ Two dependencies were deliberately not taken: such a URL, and the transport refuses it again, so a server saved before the rule is listed with a warning and never contacted until it is switched to `https://`. - The plugin declares the `debugger.endpoints` permission, to offer the SQLite debugger of the - open project's app without typing a port or token. Code on the Go 26.46 and older reject a + open project's app without typing a port or token. Code on the Go 26.47 and older reject a manifest that names a permission they do not know (`PluginSecurityManager.validatePlugin`), so this - version needs **26.47 or newer**, the first release that ships `DebuggerEndpointService` - (`plugin.min_ide_version`); users on 26.46 or older cannot install it. + version needs **26.48 or later**, the first release that ships `DebuggerEndpointService` + (`plugin.min_ide_version`); users on 26.47 or older cannot install it. 26.48 assumes the + release after 26.47 ships it; recheck it against the real release number before merging. - Redirects are never followed automatically. A 3xx is repeated only when it resolves to the same origin, so the bearer token and the user's own headers cannot be replayed to another host in one hop. diff --git a/plugins/AI-Agent-MCP/src/main/AndroidManifest.xml b/plugins/AI-Agent-MCP/src/main/AndroidManifest.xml index e1ed9f715..bb853f280 100644 --- a/plugins/AI-Agent-MCP/src/main/AndroidManifest.xml +++ b/plugins/AI-Agent-MCP/src/main/AndroidManifest.xml @@ -39,17 +39,19 @@ android:name="plugin.author" android:value="App Dev for All" /> - + + android:value="26.48" /> Date: Wed, 18 Nov 2026 17:49:25 -0800 Subject: [PATCH 22/90] ADFA-7139 AI-Agent-MCP: an endpoint listener's OutOfMemoryError reaches the caller 21944cf0 narrowed the listener loops of McpServerStore, McpServerHealth and AutomaticServers.fireChanged to runCatchingRecoverable, but missed the endpoint-listener loop in AutomaticServers.refresh, which kept a bare runCatching. McpPlugin's relist listener is the one registered there; an OutOfMemoryError or a StackOverflowError raised while it ran was swallowed, not passed on to the IDE's uncaught-exception handler. The loop now uses runCatchingRecoverable, like fireChanged in the same file: an Exception or a LinkageError still costs only that listener's call, and any other Error propagates to refresh's caller. The KDoc of addEndpointListener and refresh says so. The other bare runCatching calls stay, since none of them calls host code or a listener that does: - McpSession.cancel (McpSession.kt:194): HttpURLConnection.disconnect. - McpToolSource.cancel (McpToolSource.kt:133): McpSession.cancel above. - McpTranscriptDialog.copy (McpTranscriptDialog.kt:70): the platform ClipboardManager. - McpHttpClient.kt:118 drains a 202 body from the platform connection; :144 calls McpExchangeListener, whose only implementations are this plugin's own McpExchangeLog and NONE. - McpRedactor.kt:56 (URLDecoder) and McpLogFormat.kt:56 (org.json): JDK and platform parsing. Tests: an endpoint listener that throws OutOfMemoryError makes refresh throw it (with the bare runCatching: "expected java.lang.OutOfMemoryError to be thrown, but nothing was thrown"); one that throws AbstractMethodError costs only its own call, and the next listener still hears the relaunch. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../aiagentmcp/debugger/AutomaticServers.kt | 8 +++- .../debugger/AutomaticServersTest.kt | 37 +++++++++++++++++++ 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt index 487cedb75..643762385 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt @@ -118,6 +118,9 @@ object AutomaticServers { /** * Registers [listener], called with the id of an entry that appeared or whose port or token * changed, so the owner can list its tools at once instead of at the next probe. + * + * Guarded like the change listeners: an Exception or a LinkageError from [listener] costs only + * that call, and any other Error propagates to [refresh]'s caller; see [runCatchingRecoverable]. */ fun addEndpointListener(listener: (String) -> Unit) { endpointListeners.add(listener) @@ -140,7 +143,8 @@ object AutomaticServers { * already replaced. * * A read that fails with an Exception or a LinkageError leaves the entries as they were; any - * other Error, an OutOfMemoryError above all, propagates to the caller. + * other Error, an OutOfMemoryError above all, propagates to the caller. So does one from a + * change or endpoint listener. * * @param keepGoing checked after the read, before anything is stored. * @return true when the set of entries, a port or a token changed. @@ -197,7 +201,7 @@ object AutomaticServers { for (id in moved) { // A refused credential is not final for this entry: the new one has not been tried. McpServerHealth.credentialChanged(id) - for (l in endpointListeners) runCatching { l(id) } + for (l in endpointListeners) runCatchingRecoverable { l(id) } } if (changed) fireChanged() return changed diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServersTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServersTest.kt index fe68c8ad1..1f950d2eb 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServersTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServersTest.kt @@ -242,6 +242,43 @@ class AutomaticServersTest { } } + /** Guarded like the change listeners: the process failing is not a relist that failed. */ + @Test + fun `an endpoint listener that throws an OutOfMemoryError reaches the caller`() { + var current = listOf(endpoint()) + AutomaticServers.install { current } + val listener: (String) -> Unit = { throw OutOfMemoryError("relisting a relaunched app") } + AutomaticServers.addEndpointListener(listener) + try { + current = listOf(endpoint(port = 4001)) + + assertThrows(OutOfMemoryError::class.java) { AutomaticServers.refresh() } + } finally { + AutomaticServers.removeEndpointListener(listener) + } + } + + /** The other half of that guard: a host whose plugin-api differs costs only the one listener. */ + @Test + fun `an endpoint listener that throws a linkage error costs only its own call`() { + var current = listOf(endpoint()) + AutomaticServers.install { current } + val asked = mutableListOf() + val failing: (String) -> Unit = { throw AbstractMethodError("ToolSourceRegistry.notifyToolsChanged") } + val working: (String) -> Unit = { asked += it } + AutomaticServers.addEndpointListener(failing) + AutomaticServers.addEndpointListener(working) + try { + current = listOf(endpoint(port = 4001)) + + assertTrue(AutomaticServers.refresh()) + assertEquals(listOf(AutomaticServers.idFor("com.example.app")), asked) + } finally { + AutomaticServers.removeEndpointListener(failing) + AutomaticServers.removeEndpointListener(working) + } + } + @Test fun `an entry that disappears has its health and cached tools forgotten`() { var current = listOf(endpoint()) From f95d21e6852d02d37a01accd919945c9a5afcad6 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Wed, 18 Nov 2026 17:49:25 -0800 Subject: [PATCH 23/90] ADFA-7139 AI-Agent-MCP: deactivate stops the scope even when the host cannot remove its listener deactivate() called context.removePluginLifecycleListener first, inside a try that catches Exception only. A host whose plugin-api differs from this plugin's answers that call with a LinkageError (AbstractMethodError, NoSuchMethodError), which skipped every later step: the activation's scope kept running, its probe kept refreshing every 20 s, and the sessions, the tool catalogue and the automatic entries were never released. An Exception from the same call skipped them too, ending in the catch's "deactivation failed". The removal now goes through runCatchingRecoverable, as dispose()'s already does, and a failure is logged as a warning. The rest of the deactivation runs either way. Any other Error, an OutOfMemoryError above all, still propagates. Test: with removePluginLifecycleListener throwing AbstractMethodError, deactivate stops the activation's scope, clears the automatic entries and the cached tools, and lets nothing escape. Without the fix it fails with "the activation's scope must be stopped". Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../plugins/aiagentmcp/plugin/McpPlugin.kt | 5 ++- .../plugin/McpPluginHostErrorTest.kt | 45 +++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt index a4db642fd..aa0763890 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt @@ -253,7 +253,10 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { } override fun deactivate(): Boolean = try { - context.removePluginLifecycleListener(aiCoreLifecycle) + // Guarded like dispose's: a host whose plugin-api differs answers with a LinkageError, and + // one escaping here would skip every step below, leaving the scope and its probe running. + runCatchingRecoverable { context.removePluginLifecycleListener(aiCoreLifecycle) } + .onFailure { e -> context.logger.warn("McpPlugin: could not remove the lifecycle listener", e) } McpServerStore.removeChangeListener(settingsChanged) AutomaticServers.removeChangeListener(settingsChanged) McpServerHealth.removeChangeListener(healthChanged) diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginHostErrorTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginHostErrorTest.kt index 33fb9d1a4..2b9f30e7a 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginHostErrorTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginHostErrorTest.kt @@ -10,10 +10,13 @@ import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion. import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences import com.itsaky.androidide.plugins.aiagentmcp.tools.McpToolCatalog import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import com.itsaky.androidide.plugins.services.DebuggerEndpoint import com.itsaky.androidide.plugins.services.DebuggerEndpointService import com.itsaky.androidide.plugins.services.SharedServices import com.itsaky.androidide.plugins.services.ToolSourceRegistry +import io.mockk.Runs import io.mockk.every +import io.mockk.just import io.mockk.mockk import io.mockk.mockkObject import io.mockk.unmockkObject @@ -25,6 +28,7 @@ import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import org.junit.After import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test @@ -62,6 +66,14 @@ class McpPluginHostErrorTest { private fun fake(token: String, vararg tools: org.json.JSONObject) = FakeMcpServer(token, tools.toList()).also { servers += it } + private fun awaitUntil(what: String, condition: () -> Boolean) { + val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10) + while (!condition()) { + check(System.nanoTime() < deadline) { "timed out waiting until $what" } + Thread.sleep(10) + } + } + /** Runs [block], turning an Error that escapes it into this test's failure. */ private fun survives(what: String, block: () -> T): T = try { block() @@ -130,6 +142,39 @@ class McpPluginHostErrorTest { } } + /** + * The removal comes first in deactivate, so an Error from it used to skip every later step: the + * scope and its 20 s probe kept running, and nothing was released. + */ + @Test + fun `a listener removal that throws a linkage error still stops the scope and releases the connections`() { + val app = fake("t1", tool("query", true)) + val service = mockk { + every { endpoints } returns listOf(DebuggerEndpoint("com.example.app", app.port, "t1", 0L)) + } + every { context.services.get(DebuggerEndpointService::class.java) } returns service + val id = AutomaticServers.idFor("com.example.app") + assertTrue(plugin.activate()) + val job = requireNotNull(plugin.scopeJob) + awaitUntil("the activation listed the tools") { McpToolCatalog.tools(id).isNotEmpty() } + every { context.removePluginLifecycleListener(any()) } throws + AbstractMethodError("PluginContext.removePluginLifecycleListener") + + val escaped = try { + plugin.deactivate() + null + } catch (e: Error) { + e + } finally { + every { context.removePluginLifecycleListener(any()) } just Runs + } + + assertTrue("the activation's scope must be stopped", job.isCancelled) + assertTrue("the automatic entries must be released", AutomaticServers.servers().isEmpty()) + assertTrue("the cached tools must be released", McpToolCatalog.tools(id).isEmpty()) + assertNull("deactivate let $escaped escape", escaped) + } + @Test fun `an error that escapes a coroutine stops at the backstop, not at the IDE's handler`() { val reached = CopyOnWriteArrayList() From 121f19fe627795f3442c4c1e1e01aec6f0645d18 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 19 Nov 2026 10:54:05 -0800 Subject: [PATCH 24/90] ADFA-7139 AI-Agent-MCP: an unreachable app's reason says what to do When an app's SQLite debugger entry cannot be reached, the reason the Agent tab shows now says what to do with the app, named by its application ID: - A SocketTimeoutException, from the connect or the read: "The app did not answer. If the app is in the background, Android may have paused it. Bring the app to the front and try again." On a Galaxy Note 20, Samsung's FreecessController froze an app about 13 minutes after it left the screen, and the connect then timed out after 15000 ms. - A ConnectException, nothing listening on the port: "The app is not running with the SQLite debugger. Open the app again from Code on the Go." The app's process has ended, or the app was rebuilt without the SQLite debugger. Told apart by exception type, the cause chain included, never by message: Android's HttpURLConnection writes "failed to connect to ... after 15000ms" for a refusal and a timeout alike. An HTTP status or a JSON-RPC error is an answer and keeps its own reason, and every failure of a server added by hand keeps the generic one. A tool call that fails the same way returns the same sentence. README and both help pages list the two reasons. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- plugins/AI-Agent-MCP/README.md | 15 ++ plugins/AI-Agent-MCP/ai-agent-mcp.html | 6 + .../src/main/assets/docs/index.html | 7 + .../aiagentmcp/errors/McpErrorFormatter.kt | 58 ++++++- .../settings/McpSettingsViewModel.kt | 2 +- .../aiagentmcp/tools/McpToolCatalog.kt | 2 +- .../plugins/aiagentmcp/tools/McpToolSource.kt | 2 +- .../src/main/res/values/strings.xml | 4 + .../errors/McpErrorFormatterTest.kt | 4 +- .../aiagentmcp/tools/AppEndpointReasonTest.kt | 160 ++++++++++++++++++ 10 files changed, 252 insertions(+), 8 deletions(-) create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/AppEndpointReasonTest.kt diff --git a/plugins/AI-Agent-MCP/README.md b/plugins/AI-Agent-MCP/README.md index 8a1461e13..75ab7eb5c 100644 --- a/plugins/AI-Agent-MCP/README.md +++ b/plugins/AI-Agent-MCP/README.md @@ -60,6 +60,21 @@ points the entry at `http://127.0.0.1:/mcp`. A relaunched app gets a new port and token, and the plugin reads them again after a refused connection. An app that has not reported yet has no entry, and no error is shown. +When the entry cannot reach its app, the reason the Agent tab shows says what to +do, told apart by exception type (`SocketTimeoutException` or `ConnectException`, +anywhere in the cause chain): + +- **No answer** (a socket timeout): "The app did not answer. If + the app is in the background, Android may have paused it. Bring the app to the + front and try again." Some phones freeze an app in the background: a Galaxy + Note 20 froze one about 13 minutes after it left the screen. +- **Refused** (nothing listens on the port): "The app is not + running with the SQLite debugger. Open the app again from Code on the Go." The + app's process has ended, or the app was rebuilt without the SQLite debugger. + +Any other failure of the entry, and every failure of a server you add yourself, +keeps the generic reason, such as "Could not reach : ". + Each app's tools are told apart for the model. Their names start with `db_` and the first seven characters of the application ID's last segment (`db_notes_query` for `com.example.notes`, `db_myappli_query` for diff --git a/plugins/AI-Agent-MCP/ai-agent-mcp.html b/plugins/AI-Agent-MCP/ai-agent-mcp.html index ac29bb103..aaca2e012 100644 --- a/plugins/AI-Agent-MCP/ai-agent-mcp.html +++ b/plugins/AI-Agent-MCP/ai-agent-mcp.html @@ -188,6 +188,12 @@

    Troubleshooting

    Stored rather than the value, so typing replaces it. Tools missing from the AgentCheck the server is enabled, at least one tool is switched on, and AI Core is installed and active. + "The app … did not answer"The SQLite debugger entry's app + gave no answer. Android may pause an app in the background: bring the app + to the front and try again. + "The app … is not running with the SQLite debugger"The app + has stopped, or it was rebuilt without the SQLite debugger. Open the app + again from Code on the Go. diff --git a/plugins/AI-Agent-MCP/src/main/assets/docs/index.html b/plugins/AI-Agent-MCP/src/main/assets/docs/index.html index 8cead601b..7f4380192 100644 --- a/plugins/AI-Agent-MCP/src/main/assets/docs/index.html +++ b/plugins/AI-Agent-MCP/src/main/assets/docs/index.html @@ -142,6 +142,13 @@

    Troubleshooting

    least one tool is switched on, and AI Core is installed and active.
  • Everything times out on mobile data — some servers are slow to handshake; try again on Wi-Fi before assuming the URL is wrong.
  • +
  • "The app … did not answer" — the SQLite debugger entry's app gave + no answer. Android may pause an app in the background: bring the app to the + front and try again.
  • +
  • "The app … is not running with the SQLite debugger" — nothing + answers on the app's SQLite debugger port: the app has stopped, or it was + rebuilt without the SQLite debugger. Open the app again from Code on the + Go.
diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpErrorFormatter.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpErrorFormatter.kt index 3a4072cfc..73fb04dfd 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpErrorFormatter.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpErrorFormatter.kt @@ -3,13 +3,16 @@ package com.itsaky.androidide.plugins.aiagentmcp.errors import android.content.Context import com.itsaky.androidide.plugins.aiagentmcp.R import com.itsaky.androidide.plugins.aiagentmcp.client.McpProtocolException +import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticServers import com.itsaky.androidide.plugins.aiagentmcp.security.UnavailableSecretException import com.itsaky.androidide.plugins.aiagentmcp.security.UnreadableSecretException +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServer import com.itsaky.androidide.plugins.aiagentmcp.transport.McpCleartextException import com.itsaky.androidide.plugins.aiagentmcp.transport.McpCredential import com.itsaky.androidide.plugins.aiagentmcp.transport.McpHttpException import com.itsaky.androidide.plugins.aiagentmcp.transport.McpRedirectException import java.io.InterruptedIOException +import java.net.ConnectException import java.net.SocketTimeoutException import java.net.UnknownHostException import javax.net.ssl.SSLException @@ -78,6 +81,18 @@ sealed interface McpFailure { /** Everything else, including failures that never reached the network. */ data class Failed(val reason: String?) : McpFailure + + /** + * The SQLite debugger of the app [applicationId] did not answer before a socket timeout. Android + * may have paused the app in the background, and a paused app answers nothing. + */ + data class AppNotAnswering(val applicationId: String) : McpFailure + + /** + * Nothing listens on the port stored for the app [applicationId]: its process ended, or it was + * rebuilt without the SQLite debugger. + */ + data class AppNotListening(val applicationId: String) : McpFailure } /** @@ -88,6 +103,9 @@ sealed interface McpFailure { */ object McpErrorFormatter { + /** How far down a cause chain [classify] looks, which also ends a chain that loops. */ + private const val MAX_CAUSES = 8 + /** * Reduces [error] to what the user needs to know. * @param error the failure, from any layer. @@ -109,19 +127,47 @@ object McpErrorFormatter { else -> McpFailure.Failed(error.message) } + /** + * Reduces [error] on [server] to what the user needs to know. As [classify], except on an + * entry built from an app's stored SQLite debugger endpoint, where a socket timeout or a + * refused connection says what to do with that app. + * + * Told apart by exception type, the cause chain included, never by message: Android's + * `HttpURLConnection` writes "failed to connect to ... after 15000ms" for both. + * + * @param error the failure, from any layer. + * @param server the server it came from. + * @return the classification. + */ + fun classify(error: Throwable, server: McpServer): McpFailure { + val failure = classify(error) + if (!server.automatic) return failure + // An HTTP status or a JSON-RPC error is an answer, so the app is running and listening. + if (failure != McpFailure.TimedOut && failure !is McpFailure.Failed) return failure + val applicationId = AutomaticServers.applicationIdOf(server.id) + val cause = generateSequence(error) { it.cause }.take(MAX_CAUSES) + .firstOrNull { it is SocketTimeoutException || it is ConnectException } + return when (cause) { + is SocketTimeoutException -> McpFailure.AppNotAnswering(applicationId) + is ConnectException -> McpFailure.AppNotListening(applicationId) + else -> failure + } + } + /** * The sentence to show for [error]. * @param context this plugin's context, for its own `strings.xml`; null falls back to the * untranslated shape, which beats showing the user nothing. - * @param serverName the server's label, so a user with several knows which one failed. + * @param server the server that failed. Its label names it, so a user with several knows + * which one; the two reasons that say what to do with an app name its application ID. * @param error the failure. * @return one sentence. */ - fun format(context: Context?, serverName: String, error: Throwable): String { - val failure = classify(error) + fun format(context: Context?, server: McpServer, error: Throwable): String { + val serverName = server.name if (context == null) return "$serverName: ${error.message ?: error.javaClass.simpleName}" - return when (failure) { + return when (val failure = classify(error, server)) { McpFailure.BadRequest -> context.getString(R.string.mcp_error_bad_request, serverName) is McpFailure.TokenRefused -> refused(context, serverName, failure.credential) is McpFailure.Forbidden -> forbidden(context, serverName, failure.credential) @@ -148,6 +194,10 @@ object McpErrorFormatter { is McpFailure.Failed -> failure.reason ?.let { context.getString(R.string.mcp_error_failed_reason, serverName, it) } ?: context.getString(R.string.mcp_error_failed, serverName) + is McpFailure.AppNotAnswering -> + context.getString(R.string.mcp_error_app_not_answering, failure.applicationId) + is McpFailure.AppNotListening -> + context.getString(R.string.mcp_error_app_not_listening, failure.applicationId) } } diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt index 45e8d164f..eaf2e2051 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt @@ -287,7 +287,7 @@ class McpSettingsViewModel( val context = getContext()?.androidContext // The cached tools: a failed reconnect must not blank out the switches. ConnectResult( - message = McpErrorFormatter.format(context, server.name, e), + message = McpErrorFormatter.format(context, server, e), log = McpTranscript.log( exchanges.snapshot(), e, McpTranscriptStrings(context), exchanges::redact, ), diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt index c80b8a219..0542243f9 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt @@ -98,7 +98,7 @@ object McpToolCatalog { if (!isConfigured(server.id)) return val context = McpPlugin.getContext()?.androidContext val refused = failure is McpFailure.TokenRefused || failure is McpFailure.Forbidden - McpServerHealth.degraded(server.id, McpErrorFormatter.format(context, server.name, error), refused) + McpServerHealth.degraded(server.id, McpErrorFormatter.format(context, server, error), refused) } private fun isConfigured(serverId: String): Boolean = diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt index 98cfbce1e..f14835b56 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt @@ -178,7 +178,7 @@ class McpToolSource : Log.w(TAG, "Tool '${tool.name}' on '${server.name}' failed", e) McpToolCatalog.recordFailure(server, e) val context = McpPlugin.getContext()?.androidContext - Outcome(false, "", McpErrorFormatter.format(context, server.name, e)) + Outcome(false, "", McpErrorFormatter.format(context, server, e)) } finally { running -= callId cancelled -= callId diff --git a/plugins/AI-Agent-MCP/src/main/res/values/strings.xml b/plugins/AI-Agent-MCP/src/main/res/values/strings.xml index b28ff7f18..78cc70520 100644 --- a/plugins/AI-Agent-MCP/src/main/res/values/strings.xml +++ b/plugins/AI-Agent-MCP/src/main/res/values/strings.xml @@ -84,6 +84,10 @@ %1$s\'s saved credentials could not be read just now. They are still stored — try again in a moment. Could not reach %1$s. Could not reach %1$s: %2$s + + The app %1$s did not answer. If the app is in the background, Android may have paused it. Bring the app to the front and try again. + + The app %1$s is not running with the SQLite debugger. Open the app again from Code on the Go. \'%1$s\' is no longer offered by any configured MCP server. diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpErrorFormatterTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpErrorFormatterTest.kt index 76a8cccf0..bd31476f0 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpErrorFormatterTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpErrorFormatterTest.kt @@ -3,6 +3,7 @@ package com.itsaky.androidide.plugins.aiagentmcp.errors import com.itsaky.androidide.plugins.aiagentmcp.client.McpProtocolException import com.itsaky.androidide.plugins.aiagentmcp.security.UnavailableSecretException import com.itsaky.androidide.plugins.aiagentmcp.security.UnreadableSecretException +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServer import com.itsaky.androidide.plugins.aiagentmcp.transport.McpCleartextException import com.itsaky.androidide.plugins.aiagentmcp.transport.McpCredential import com.itsaky.androidide.plugins.aiagentmcp.transport.McpHttpException @@ -123,7 +124,8 @@ class McpErrorFormatterTest { @Test fun givenNoPluginContext_whenFormatted_thenTheUserStillGetsASentence() { - val message = McpErrorFormatter.format(null, "Docs", IOException("socket closed")) + val server = McpServer(id = "docs", name = "Docs", url = "https://docs.example/mcp") + val message = McpErrorFormatter.format(null, server, IOException("socket closed")) assertTrue(message.contains("Docs")) assertTrue(message.contains("socket closed")) diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/AppEndpointReasonTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/AppEndpointReasonTest.kt new file mode 100644 index 000000000..8b395ef7c --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/AppEndpointReasonTest.kt @@ -0,0 +1,160 @@ +package com.itsaky.androidide.plugins.aiagentmcp.tools + +import android.content.Context +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.R +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticEndpoint +import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticServers +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServer +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.aiagentmcp.transport.McpHttpException +import io.mockk.every +import io.mockk.mockk +import java.io.File +import java.io.IOException +import java.net.ConnectException +import java.net.InetAddress +import java.net.ServerSocket +import java.net.SocketTimeoutException +import javax.xml.parsers.DocumentBuilderFactory +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Before +import org.junit.Test +import org.w3c.dom.Element + +/** + * The reason the Agent tab shows when an app's SQLite debugger entry cannot be reached says what + * to do with the app. Read from [McpServerHealth], where the Agent tab gets it, in the words of + * this plugin's own strings.xml. + */ +class AppEndpointReasonTest { + + private val app = "com.example.probe" + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + every { context.androidContext } returns stringsXmlContext() + plugin = McpPlugin().also { it.initialize(context) } + } + + @After + fun tearDown() { + AutomaticServers.install(null) + McpConnections.closeAll() + McpToolCatalog.clear() + McpServerHealth.clear() + plugin.dispose() + } + + @Test + fun `a timed-out connection to an app says Android may have paused it`() { + val server = appEntry(33425) + val paused = "The app com.example.probe did not answer. If the app is in the background, " + + "Android may have paused it. Bring the app to the front and try again." + + // What Android's HttpURLConnection threw on a Galaxy Note 20 for an app frozen in the background. + McpToolCatalog.recordFailure( + server, + SocketTimeoutException( + "failed to connect to /127.0.0.1 (port 33425) from /127.0.0.1 (port 56874) after 15000ms", + ), + ) + assertEquals(paused, reason(server)) + + // Where the system accepts the connection for a paused app, it is the read that times out. + McpToolCatalog.recordFailure(server, SocketTimeoutException("Read timed out")) + assertEquals(paused, reason(server)) + } + + @Test + fun `a refused connection to an app says to open it again from Code on the Go`() { + // A port that was free a moment ago: nothing listens there, as after the app's process died. + val port = ServerSocket(0, 1, InetAddress.getLoopbackAddress()).use { it.localPort } + val server = appEntry(port) + + runCatching { McpToolCatalog.connect(server) } + + assertEquals( + "The app com.example.probe is not running with the SQLite debugger. " + + "Open the app again from Code on the Go.", + reason(server), + ) + } + + @Test + fun `a refusal wrapped in another exception still says to open the app again`() { + val server = appEntry(33425) + + McpToolCatalog.recordFailure( + server, + IOException("request failed", ConnectException("Failed to connect to /127.0.0.1:33425")), + ) + + assertEquals( + "The app com.example.probe is not running with the SQLite debugger. " + + "Open the app again from Code on the Go.", + reason(server), + ) + } + + @Test + fun `a server added by hand keeps the generic reason for a refusal and a timeout`() { + val server = McpServerStore.saveDetails(McpServerStore.newServer("Docs", "http://127.0.0.1:33425/mcp")) + + McpToolCatalog.recordFailure(server, ConnectException("Failed to connect to /127.0.0.1:33425")) + assertEquals("Could not reach Docs: Failed to connect to /127.0.0.1:33425", reason(server)) + + McpToolCatalog.recordFailure(server, SocketTimeoutException("Read timed out")) + assertEquals("Docs did not answer in time. It may be slow or offline.", reason(server)) + } + + @Test + fun `any other failure of an app keeps the generic reason`() { + val server = appEntry(33425) + + McpToolCatalog.recordFailure(server, IOException("socket closed")) + assertEquals("Could not reach SQLite debugger (com.example.probe): socket closed", reason(server)) + + McpToolCatalog.recordFailure(server, McpHttpException(500, "")) + assertEquals("SQLite debugger (com.example.probe) reported a server error (HTTP 500).", reason(server)) + + // A 504 is an answer: the app is running, so it is not the paused-app reason. + McpToolCatalog.recordFailure(server, McpHttpException(504, "")) + assertEquals( + "SQLite debugger (com.example.probe) did not answer in time. It may be slow or offline.", + reason(server), + ) + } + + /** The automatic entry for [app], listening on [port] as far as Code on the Go knows. */ + private fun appEntry(port: Int): McpServer { + AutomaticServers.install({ listOf(AutomaticEndpoint(app, port, "t1")) }) + return AutomaticServers.servers().single() + } + + private fun reason(server: McpServer): String? = McpServerHealth.of(server.id)?.message + + /** A Context answering `getString` from this plugin's strings.xml, so the shipped words are checked. */ + private fun stringsXmlContext(): Context { + val names = R.string::class.java.fields.associate { it.getInt(null) to it.name } + val nodes = DocumentBuilderFactory.newInstance().newDocumentBuilder() + .parse(File("src/main/res/values/strings.xml")) + .getElementsByTagName("string") + val texts = (0 until nodes.length).map { nodes.item(it) as Element } + .associate { it.getAttribute("name") to it.textContent.replace("\\'", "'") } + val text = { id: Int -> texts.getValue(names.getValue(id)) } + return mockk(relaxed = true) { + every { getString(any()) } answers { text(firstArg()) } + every { getString(any(), *anyVararg()) } answers { + String.format(text(firstArg()), *secondArg>()) + } + } + } +} From e95ac1fc151d8d706b043d1d4c7f93a7c59449ee Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 19 Nov 2026 13:38:41 -0800 Subject: [PATCH 25/90] ADFA-7139 AI-Agent-MCP: each listener is registered once, by activate CodeRabbit, #166 thread 4634051365. activate added settingsChanged to AutomaticServers and McpServerStore, and healthChanged to McpServerHealth, on every call, and each activation's coroutine added relistAutomatic in startDebuggerEntry. All four used CopyOnWriteArrayList.add, so a host that activates twice left two copies of each and one deactivate removed one: the agent was told the tools changed after the plugin was off, and each endpoint change started two listings while it was on. The add methods of the three registries now use addIfAbsent. activate registers relistAutomatic beside the change listeners, and deactivate and dispose remove it with them. startDebuggerEntry adds and removes no listener, so a late first read of an ended activation cannot remove the listener of the activation that replaced it: the race addIfAbsent alone would have opened. Registered before the install, relistAutomatic would be told of every entry the install's first read finds, and refreshAll lists those same entries straight after; AutomaticServers.install's first read therefore tells no endpoint listener, which keeps each entry listed once at activation. Tests: McpPluginListenerTest (two activations register each of the four listeners once, and one deactivation removes them all; counted through new changeListenerCount seams), AutomaticServersTest (the install's first read tells no endpoint listener and a later change does), and McpPluginDebuggerStartTest, whose two tests now expect startDebuggerEntry to leave the endpoint-listener count alone. With only this fix reverted: - McpPluginListenerTest: "AutomaticServers change listeners after two activations expected:<1> but was:<2>" - AutomaticServersTest: "the install's read told the listener expected:<[]> but was:<[debugger:com.example.app, debugger:com.example.other]>" - McpPluginDebuggerStartTest, the live activation: "expected:<1> but was:<2>" Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../aiagentmcp/debugger/AutomaticServers.kt | 34 +++++++-- .../plugins/aiagentmcp/plugin/McpPlugin.kt | 25 ++++--- .../aiagentmcp/settings/McpServerStore.kt | 11 ++- .../aiagentmcp/tools/McpServerHealth.kt | 11 ++- .../debugger/AutomaticServersTest.kt | 24 +++++++ .../plugin/McpPluginDebuggerStartTest.kt | 10 +-- .../plugin/McpPluginListenerTest.kt | 71 +++++++++++++++++++ 7 files changed, 161 insertions(+), 25 deletions(-) create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginListenerTest.kt diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt index 643762385..a89fb1107 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt @@ -89,6 +89,11 @@ object AutomaticServers { /** * As [install], for a source that may be superseded while its first read is blocked. * + * The first read tells no endpoint listener (see [addEndpointListener]): whoever installs a + * source lists every entry straight after, as the plugin's activation does with + * `McpToolCatalog.refreshAll`, and a listener told of each entry would list it a second time. + * Change listeners are told as on any read. + * * @param keepGoing false once the activation installing [source] is over. The first read blocks * and cannot be cancelled, so an activation that ended during it must neither keep [source] * nor publish what it read: deactivation has already cleared everything, and a later @@ -99,7 +104,7 @@ object AutomaticServers { if (!keepGoing()) return this.source = source } - refresh(keepGoing) + readEndpoints(keepGoing, tellEndpointListeners = false) } /** Adapts the host's service. A host without the service, or without the permission, is no source. */ @@ -107,23 +112,32 @@ object AutomaticServers { read().map { AutomaticEndpoint(it.applicationId, it.port, it.token) } } + /** + * Registers [listener], called after the set of entries, a port, a token or a tool list + * changed. Adding one already registered does nothing, so a host that activates the plugin + * twice still gets one call per change, and one [removeChangeListener] takes it out. + */ fun addChangeListener(listener: () -> Unit) { - listeners.add(listener) + listeners.addIfAbsent(listener) } fun removeChangeListener(listener: () -> Unit) { listeners.remove(listener) } + /** How many change listeners are registered; a test seam for a listener registered twice. */ + internal val changeListenerCount: Int get() = listeners.size + /** * Registers [listener], called with the id of an entry that appeared or whose port or token - * changed, so the owner can list its tools at once instead of at the next probe. + * changed, so the owner can list its tools at once instead of at the next probe. Adding one + * already registered does nothing, as for [addChangeListener]. * * Guarded like the change listeners: an Exception or a LinkageError from [listener] costs only * that call, and any other Error propagates to [refresh]'s caller; see [runCatchingRecoverable]. */ fun addEndpointListener(listener: (String) -> Unit) { - endpointListeners.add(listener) + endpointListeners.addIfAbsent(listener) } fun removeEndpointListener(listener: (String) -> Unit) { @@ -149,7 +163,15 @@ object AutomaticServers { * @param keepGoing checked after the read, before anything is stored. * @return true when the set of entries, a port or a token changed. */ - fun refresh(keepGoing: () -> Boolean = { true }): Boolean { + fun refresh(keepGoing: () -> Boolean = { true }): Boolean = + readEndpoints(keepGoing, tellEndpointListeners = true) + + /** + * [refresh] itself. + * + * @param tellEndpointListeners false for [install]'s first read; see there. + */ + private fun readEndpoints(keepGoing: () -> Boolean, tellEndpointListeners: Boolean): Boolean { val (read, ticket) = synchronized(this) { val current = source ?: return false current to ++readsStarted @@ -201,7 +223,7 @@ object AutomaticServers { for (id in moved) { // A refused credential is not final for this entry: the new one has not been tried. McpServerHealth.credentialChanged(id) - for (l in endpointListeners) runCatchingRecoverable { l(id) } + if (tellEndpointListeners) for (l in endpointListeners) runCatchingRecoverable { l(id) } } if (changed) fireChanged() return changed diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt index aa0763890..fd18dfa80 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt @@ -201,7 +201,9 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { /** * Lists an automatic entry's tools as soon as its endpoint appears or changes, so a relaunched - * app's next call does not wait for the probe's cadence. + * app's next call does not wait for the probe's cadence. Registered by [activate] beside the + * change listeners, and removed with them. The activation's own install of the endpoints tells + * it nothing (see [AutomaticServers.install]): the `refreshAll` that follows lists those entries. */ private val relistAutomatic: (String) -> Unit = { id -> scope.launch { @@ -227,8 +229,13 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { val active = swapScope(newScope()) activationJob = active.coroutineContext[Job] toolSource = McpToolSource() + // Here, not on the coroutine below: a lifecycle call registers and removes every listener, + // so a late coroutine of an activation that has ended cannot add one, or remove the next + // activation's. The add methods ignore a listener already registered, so a host that + // activates twice still registers each once. McpServerStore.addChangeListener(settingsChanged) AutomaticServers.addChangeListener(settingsChanged) + AutomaticServers.addEndpointListener(relistAutomatic) McpServerHealth.addChangeListener(healthChanged) context.addPluginLifecycleListener(aiCoreLifecycle) @@ -259,14 +266,12 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { .onFailure { e -> context.logger.warn("McpPlugin: could not remove the lifecycle listener", e) } McpServerStore.removeChangeListener(settingsChanged) AutomaticServers.removeChangeListener(settingsChanged) + AutomaticServers.removeEndpointListener(relistAutomatic) McpServerHealth.removeChangeListener(healthChanged) unregisterToolSource() // Before the connections are closed: an in-flight refresh would otherwise repopulate the // catalogue and the session map straight after they were cleared. stopScope() - // After the scope ends, not before: startDebuggerEntry adds this listener and then checks - // the scope, so one added late is removed by that check and one added early is removed here. - AutomaticServers.removeEndpointListener(relistAutomatic) releaseConnections() true } catch (e: Exception) { @@ -278,10 +283,10 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { runCatchingRecoverable { context.removePluginLifecycleListener(aiCoreLifecycle) } McpServerStore.removeChangeListener(settingsChanged) AutomaticServers.removeChangeListener(settingsChanged) + AutomaticServers.removeEndpointListener(relistAutomatic) McpServerHealth.removeChangeListener(healthChanged) unregisterToolSource() stopScope() - AutomaticServers.removeEndpointListener(relistAutomatic) releaseConnections() pluginContext = null context.logger.info("McpPlugin: disposed") @@ -332,20 +337,18 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { } /** - * Installs the host's endpoints and starts listening for changes, unless the activation ends first. + * Installs the host's endpoints, unless the activation ends first. * * The host's database read blocks and cancellation cannot interrupt it, so [keepGoing] is - * consulted around it. The listener is re-checked after it is added: [deactivate] ends the scope - * before it removes the listener, so one added in between is seen here and taken out again. + * consulted before it and, inside [AutomaticServers.install], after it. No listener is added + * or removed here: [activate] registers [relistAutomatic] and [deactivate] removes it, so this + * call, which can outlive its activation, cannot touch the listener a later activation relies on. * * @param keepGoing false once this activation is over. */ internal fun startDebuggerEntry(keepGoing: () -> Boolean) { if (!keepGoing()) return installDebuggerEndpoints(keepGoing) - if (!keepGoing()) return - AutomaticServers.addEndpointListener(relistAutomatic) - if (!keepGoing()) AutomaticServers.removeEndpointListener(relistAutomatic) } /** diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStore.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStore.kt index a6c33fb01..2efd47458 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStore.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStore.kt @@ -49,9 +49,13 @@ object McpServerStore { */ private val lock = Any() - /** Registers [listener], called after any change to the servers or their toggles. */ + /** + * Registers [listener], called after any change to the servers or their toggles. Adding one + * already registered does nothing, so a host that activates the plugin twice still gets one + * call per change, and one [removeChangeListener] takes it out. + */ fun addChangeListener(listener: () -> Unit) { - listeners.add(listener) + listeners.addIfAbsent(listener) } /** Removes a listener added by [addChangeListener]. */ @@ -59,6 +63,9 @@ object McpServerStore { listeners.remove(listener) } + /** How many change listeners are registered; a test seam for a listener registered twice. */ + internal val changeListenerCount: Int get() = listeners.size + /** * Every configured server, in the order they were added. * @return the servers; empty before any is configured, or when the stored blob is unreadable. diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpServerHealth.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpServerHealth.kt index f068df2b5..bf487a067 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpServerHealth.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpServerHealth.kt @@ -79,9 +79,13 @@ object McpServerHealth { fireChanged() } - /** Registers [listener], called after any server's health changes. */ + /** + * Registers [listener], called after any server's health changes. Adding one already + * registered does nothing, so a host that activates the plugin twice still gets one call per + * change, and one [removeChangeListener] takes it out. + */ fun addChangeListener(listener: () -> Unit) { - listeners.add(listener) + listeners.addIfAbsent(listener) } /** Removes a listener added by [addChangeListener]. */ @@ -89,6 +93,9 @@ object McpServerHealth { listeners.remove(listener) } + /** How many change listeners are registered; a test seam for a listener registered twice. */ + internal val changeListenerCount: Int get() = listeners.size + /** Stores [health], telling the listeners only when it differs from what was there. */ private fun set(serverId: String, health: Health) { if (byServer.put(serverId, health) != health) fireChanged() diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServersTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServersTest.kt index 1f950d2eb..0807382cd 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServersTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServersTest.kt @@ -104,6 +104,30 @@ class AutomaticServersTest { assertEquals(listOf(AutomaticServers.idFor("com.example.app")), asked) } + /** + * The plugin registers its endpoint listener on activation, before it installs the source, and + * lists every entry itself straight after the install. A listener told of each entry by the + * install's read would list each one a second time. + */ + @Test + fun `the install's first read tells no endpoint listener and a later change does`() { + var current = listOf(endpoint(), endpoint(app = "com.example.other", port = 4001)) + val asked = mutableListOf() + val listener: (String) -> Unit = { asked += it } + AutomaticServers.addEndpointListener(listener) + try { + AutomaticServers.install { current } + assertEquals(2, AutomaticServers.servers().size) + assertEquals("the install's read told the listener", emptyList(), asked) + + current = listOf(endpoint(port = 4002, token = "t2"), endpoint(app = "com.example.other", port = 4001)) + AutomaticServers.refresh() + assertEquals(listOf(AutomaticServers.idFor("com.example.app")), asked) + } finally { + AutomaticServers.removeEndpointListener(listener) + } + } + @Test fun `a relaunch lets the probe ask an entry that had refused its credential`() { var current = listOf(endpoint()) diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginDebuggerStartTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginDebuggerStartTest.kt index 596ef7272..6179ef778 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginDebuggerStartTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginDebuggerStartTest.kt @@ -18,7 +18,9 @@ import org.junit.Test /** * An activation that ends during the host's blocking first read of the debugger endpoints must - * leave no source and no listener behind: nothing removes them after [McpPlugin.deactivate]. + * leave no source behind: nothing removes it after [McpPlugin.deactivate]. Nor does the read add + * or remove a listener: [McpPlugin.activate] owns that, so a late read cannot take away the + * listener of the activation that replaced its own. */ class McpPluginDebuggerStartTest { @@ -55,7 +57,7 @@ class McpPluginDebuggerStartTest { } @Test - fun `an activation that ends during the first read installs nothing and adds no listener`() { + fun `an activation that ends during the first read installs nothing and touches no listener`() { val listeners = AutomaticServers.endpointListenerCount val active = AtomicBoolean(true) val start = Thread { plugin.startDebuggerEntry { active.get() } }.also { it.start() } @@ -70,12 +72,12 @@ class McpPluginDebuggerStartTest { } @Test - fun `a live activation installs the entry and the listener once`() { + fun `a live activation installs the entry and leaves the listener to activate`() { val listeners = AutomaticServers.endpointListenerCount release.countDown() plugin.startDebuggerEntry { true } assertEquals(1, AutomaticServers.servers().size) - assertEquals(listeners + 1, AutomaticServers.endpointListenerCount) + assertEquals(listeners, AutomaticServers.endpointListenerCount) } } diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginListenerTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginListenerTest.kt new file mode 100644 index 000000000..e38801add --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginListenerTest.kt @@ -0,0 +1,71 @@ +package com.itsaky.androidide.plugins.aiagentmcp.plugin + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticServers +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpServerHealth +import io.mockk.every +import io.mockk.mockk +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Before +import org.junit.Test + +/** + * The plugin's four listeners, registered once however often the host activates it. + * + * The host can activate twice without a deactivation in between. A listener added twice and + * removed once stays registered after [McpPlugin.deactivate]: a change to the servers then tells + * the agent the tools changed although the plugin is off, and while it is on each endpoint change + * starts two tool listings. That the first endpoint read, which can outlive its activation, adds + * or removes no listener is [McpPluginDebuggerStartTest]'s. + */ +class McpPluginListenerTest { + + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + } + + @After + fun tearDown() { + plugin.dispose() + } + + /** Each registry's listener count, in a fixed order, so the assertions can name the registry. */ + private fun counts() = listOf( + AutomaticServers.changeListenerCount, + AutomaticServers.endpointListenerCount, + McpServerStore.changeListenerCount, + McpServerHealth.changeListenerCount, + ) + + private fun assertCounts(message: String, expected: List) { + val names = listOf( + "AutomaticServers change listeners", + "AutomaticServers endpoint listeners", + "McpServerStore change listeners", + "McpServerHealth change listeners", + ) + val actual = counts() + for (i in names.indices) assertEquals("${names[i]} $message", expected[i], actual[i]) + } + + @Test + fun `two activations register each listener once and one deactivation removes them all`() { + val before = counts() + + plugin.activate() + plugin.activate() + // Counted as soon as activate returns: it registers every listener before it launches anything. + assertCounts("after two activations", before.map { it + 1 }) + + plugin.deactivate() + assertCounts("after the deactivation", before) + } +} From dbb1a13f591acecd74f74810341e25d36b00dc6f Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 19 Nov 2026 13:38:41 -0800 Subject: [PATCH 26/90] ADFA-7139 AI-Agent-MCP: a cancel during the session lookup stops the call CodeRabbit, #166 thread 4634051375. runTool checked the cancel flag, then looked up its session (McpConnections.session reads the token and digests it), and only then published the session to liveSessions. A cancel in that window set the flag but found no session to drop, and callTool sent the request anyway. The flag is read again inside the try, after the session is published. Either the worker sees the flag, or the cancel sets it after that read and then finds the session to drop. McpToolSource gets an internal constructor taking its executor, so a test can wait for a call's worker to finish instead of polling for something it might still send. Test: CancelDuringSessionLookupTest lands the cancel in the token read the lookup makes, then waits for the worker. With only the re-check reverted: "the call reached the server after it was cancelled: [Seen(httpMethod=POST, authorization=null)] expected:<3> but was:<4>" Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../plugins/aiagentmcp/tools/McpToolSource.kt | 33 ++++-- .../tools/CancelDuringSessionLookupTest.kt | 102 ++++++++++++++++++ 2 files changed, 124 insertions(+), 11 deletions(-) create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/CancelDuringSessionLookupTest.kt diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt index f14835b56..2ebe880de 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt @@ -27,11 +27,17 @@ private const val TAG = "$LOG_PREFIX.McpToolSource" * Only tools the user switched on are offered: one popular GitHub server advertises around ninety, * which would exhaust a phone-sized context window on its own, so the toggle defaults to off and * this class never widens it. + * + * @param executor where remote calls run; see [newExecutor]. A seam, so a test can wait for a + * call's worker to finish rather than poll for something it might still send. */ -class McpToolSource : - ToolSourceRegistry.StatusReportingToolSource, +class McpToolSource internal constructor( + private val executor: ExecutorService, +) : ToolSourceRegistry.StatusReportingToolSource, ToolSourceRegistry.GroupedToolSource { + constructor() : this(newExecutor()) + /** Calls in flight, so a stopped agent run can drop the socket instead of waiting it out. */ private val inFlight = ConcurrentHashMap>() @@ -50,18 +56,11 @@ class McpToolSource : /** * Running calls that were cancelled. The session drop in [cancel] reaches only a request in * flight; one landing between the two attempts of the endpoint retry finds no session, so the - * retry reads this before it sends anything. + * retry reads this before it sends anything. So does one landing while an attempt looks its + * session up, which is why the attempt reads it again once the session is in [liveSessions]. */ private val cancelled: MutableSet = ConcurrentHashMap.newKeySet() - /** - * Remote calls run here rather than on the common pool: an MCP call blocks on a socket for as - * long as the read timeout, and the common pool is sized for CPU work. - */ - private val executor: ExecutorService = Executors.newCachedThreadPool { runnable -> - Thread(runnable, "mcp-tool-call").apply { isDaemon = true } - } - override fun getProviderId(): String = McpPlugin.PLUGIN_ID override fun getDisplayName(): String = DISPLAY_NAME @@ -162,6 +161,10 @@ class McpToolSource : val session = McpConnections.session(target) liveSessions[callId] = session try { + // Again, now the session is published: a cancel that landed during the lookup + // found no session to drop, and only its flag can stop the request. One landing + // after this read finds the session and drops it. + if (callId in cancelled) throw InterruptedIOException("Tool call $callId was cancelled") session.callTool(tool.name, arguments) } finally { liveSessions.remove(callId) @@ -347,5 +350,13 @@ class McpToolSource : private companion object { /** Shown wherever tool provenance is surfaced. */ const val DISPLAY_NAME = "MCP servers" + + /** + * Remote calls run here rather than on the common pool: an MCP call blocks on a socket for + * as long as the read timeout, and the common pool is sized for CPU work. + */ + fun newExecutor(): ExecutorService = Executors.newCachedThreadPool { runnable -> + Thread(runnable, "mcp-tool-call").apply { isDaemon = true } + } } } diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/CancelDuringSessionLookupTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/CancelDuringSessionLookupTest.kt new file mode 100644 index 000000000..0b43ed407 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/CancelDuringSessionLookupTest.kt @@ -0,0 +1,102 @@ +package com.itsaky.androidide.plugins.aiagentmcp.tools + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import com.itsaky.androidide.plugins.services.ToolSourceRegistry +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * A cancel that lands while a call looks up its session must stop the call. + * + * The lookup sits between the call's check of the cancel flag and the moment its session becomes + * reachable from [McpToolSource.cancel]. A cancel in that window sets the flag but finds no session + * to drop, so only a second read of the flag, once the session is published, keeps the request + * from going out. The test lands the cancel there for certain: the lookup reads the server's token, + * and the first read after the test arms it cancels the call. + */ +class CancelDuringSessionLookupTest { + + private val executor = Executors.newSingleThreadExecutor() + private val source = McpToolSource(executor) + private val armed = AtomicBoolean(false) + private lateinit var server: FakeMcpServer + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + // The Keystore is not there on the JVM; this server has no secrets. Reading its token is + // also where the call looks up its session, so that is where the cancel lands. + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } answers { + if (armed.getAndSet(false)) source.cancel(CALL_ID) + KeystoreSecretStore.Stored.Absent + } + every { McpServerStore.headers(any()) } returns emptyMap() + server = FakeMcpServer("", listOf(tool("search", true))) + } + + @After + fun tearDown() { + source.close() + McpConnections.closeAll() + McpToolCatalog.clear() + server.stop() + plugin.dispose() + unmockkObject(McpServerStore) + } + + @Test + fun `a cancel that lands while the call looks up its session sends nothing`() { + val docs = McpServerStore.saveDetails( + McpServerStore.newServer("Docs", "http://127.0.0.1:${server.port}/mcp") + ) + McpToolCatalog.connect(docs) + McpServerStore.setToolEnabled(docs.id, "search", true) + val name = source.listTools().single().name + val before = server.requests.size + + armed.set(true) + source.invoke( + mockk { + every { toolName } returns name + every { arguments } returns emptyMap() + every { callId } returns CALL_ID + } + ) + // Waits for the worker itself, so whatever it was going to send has been sent. + executor.shutdown() + assertTrue("the call never finished", executor.awaitTermination(10, TimeUnit.SECONDS)) + + assertFalse("the call never looked up its session", armed.get()) + assertEquals( + "the call reached the server after it was cancelled: ${server.requests.drop(before)}", + before, + server.requests.size, + ) + } + + private companion object { + const val CALL_ID = "call-1" + } +} From dfe1b0190370a3a85585537646b6f531434f563a Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 19 Nov 2026 13:38:41 -0800 Subject: [PATCH 27/90] ADFA-7139 AI-Agent-MCP: SQLite debugger tool prefixes are distinct whatever the row order CodeRabbit, #166 thread 4634051382. appPrefixes could still give two apps one prefix: com.a.db's fallback db_ec81 is com.c.ec81's plain prefix, and com.a177.notes and com.a282.notes both fall back to notes_5599. The tool names then collided, and disambiguate numbered the second one in row order, so a reordered read moved db_ec81_query to the other app. Each app now takes the first of four forms that is its own: db_ and seven characters of the segment; five characters and 4 hex digits of the digest; one character and 8 hex digits; db_ and a number in application-ID order. A form is an app's own when no other app still choosing wants it and no app has settled on it, and every app settles on one form before any takes the next. So the prefixes are distinct, a fallback never takes another app's plain prefix, and each depends on the set of IDs alone. No existing name changes; only an app in such a collision gets a new one. The KDoc and the README say so; the in-IDE help never described the scheme. Tests: McpToolTextTest (a fallback equal to another app's plain prefix, two apps whose 16-bit digests agree, two whose 32-bit digests agree, each also reversed) and AppToolNamesTest (the db_ec81 case end to end, in both row orders). With only the old appPrefixes body restored: - the fallback against a plain prefix: expected: but was: - 16-bit digests that agree: expected: but was: - 32-bit digests that agree: expected:<[db_1]> but was:<[notes_459b]> - AppToolNamesTest: expected: but was: Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- plugins/AI-Agent-MCP/README.md | 8 ++- .../plugins/aiagentmcp/tools/McpToolText.kt | 60 +++++++++++++------ .../aiagentmcp/debugger/AppToolNamesTest.kt | 24 ++++++++ .../aiagentmcp/tools/McpToolTextTest.kt | 42 +++++++++++++ 4 files changed, 114 insertions(+), 20 deletions(-) diff --git a/plugins/AI-Agent-MCP/README.md b/plugins/AI-Agent-MCP/README.md index 75ab7eb5c..93d21fcae 100644 --- a/plugins/AI-Agent-MCP/README.md +++ b/plugins/AI-Agent-MCP/README.md @@ -80,8 +80,12 @@ the first seven characters of the application ID's last segment (`db_notes_query` for `com.example.notes`, `db_myappli_query` for `com.example.myapplication`); when two apps would share that prefix, both use the first five characters of the segment and four hex digits derived from the full -application ID (`notes_3fa1_query`), so a name never depends on which app was -read first. Each description starts with the application ID, as +application ID (`notes_3fa1_query`). If that prefix is still another app's, as +when two apps' digits agree or the prefix equals another app's `db_` prefix, the +app uses the segment's first character and eight hex digits (`n_3fa1c2d4_query`), +and past that `db_` and a number in application-ID order (`db_1_query`). An app +keeps the first prefix that no other app shares, so the names never depend on +which app was read first. Each description starts with the application ID, as "com.example.notes (SQLite debugger): ...", and the approval dialog shows it. Servers you add yourself keep the name prefix taken from their label. diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolText.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolText.kt index faa798dbe..0141dd6a2 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolText.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolText.kt @@ -43,37 +43,61 @@ object McpToolText { * The name prefix of each SQLite debugger entry, told apart by app. * * The server label cannot do it: every entry is labelled "SQLite debugger (...)", and the - * first [MAX_PREFIX_LENGTH] characters of that are the same for all of them. The prefix is - * `db_` and the first seven characters of the application ID's last segment. Entries whose - * prefix would still be shared (`com.a.notes` and `com.b.notes`) all take the first five - * characters of the segment and four hex digits of a digest of the full application ID - * instead. Both forms depend only on the set of application IDs, never on their order, and - * fit [MAX_PREFIX_LENGTH]. + * first [MAX_PREFIX_LENGTH] characters of that are the same for all of them. Each app takes the + * first of these forms that is its own: + * 1. `db_` and the first seven characters of the application ID's last segment (`db_notes`); + * 2. the first five characters of the segment and four hex digits of a digest of the full + * application ID (`notes_3fa1`), when another app would share form 1 (`com.a.notes` and + * `com.b.notes`); + * 3. the segment's first character and eight hex digits of that digest (`n_3fa1c2d4`); + * 4. `db_` and a number, counted in application-ID order (`db_1`). + * + * A form is an app's own when no other app still choosing would take the same prefix and no + * app has already settled on it; every app settles on form 1 before any takes form 2, and so + * on. So the prefixes are distinct, and no app's later form takes another's earlier one, as + * `com.a.db`'s form 2, `db_ec81`, would take the form 1 of `com.c.ec81`. Each depends only on + * the set of application IDs, never on the order they were read in, so two listings of the same + * apps give every app the same name. Each fits [MAX_PREFIX_LENGTH]. * * @param applicationIds the application ID of every entry. * @return the prefix by application ID. */ fun appPrefixes(applicationIds: Collection): Map { - val ids = applicationIds.distinct() - val plain = ids.associateWith { id -> - "db_" + segment(id).take(MAX_PREFIX_LENGTH - 3).trim('_') - } - val shared = plain.values.groupingBy { it }.eachCount() - return ids.associateWith { id -> - if (shared.getValue(plain.getValue(id)) == 1) { - plain.getValue(id) - } else { - segment(id).take(5).trim('_') + "_" + digest(id) + val prefixes = mutableMapOf() + // Sorted, so the numbering of form 4 follows the IDs rather than the order they came in. + var choosing = applicationIds.toSortedSet().toList() + for (form in appPrefixForms) { + val wanted = choosing.associateWith { form(it) } + val wanting = wanted.values.groupingBy { it }.eachCount() + val settled = prefixes.values.toSet() + for ((id, prefix) in wanted) { + if (wanting.getValue(prefix) == 1 && prefix !in settled) prefixes[id] = prefix } + choosing = choosing.filter { it !in prefixes } } + // Form 4: only apps whose digests agree in 32 bits get here. + var number = 1 + for (id in choosing) { + while ("db_$number" in prefixes.values) number++ + prefixes[id] = "db_$number" + } + return prefixes } + /** Forms 1 to 3 of [appPrefixes], each a function of one application ID alone. */ + private val appPrefixForms: List<(String) -> String> = listOf( + { id -> "db_" + segment(id).take(MAX_PREFIX_LENGTH - 3).trim('_') }, + { id -> segment(id).take(5).trim('_') + "_" + digest(id, 2) }, + { id -> segment(id).take(1) + "_" + digest(id, 4) }, + ) + private fun segment(applicationId: String): String = identifier(applicationId.substringAfterLast('.')).ifEmpty { "app" } - private fun digest(text: String): String = + /** The first [bytes] bytes of the SHA-256 of [text], in hex. */ + private fun digest(text: String, bytes: Int): String = java.security.MessageDigest.getInstance("SHA-256").digest(text.toByteArray()) - .take(2).joinToString("") { "%02x".format(it) } + .take(bytes).joinToString("") { "%02x".format(it) } /** * A free variant of [name], numbered when two tools ended up sharing one exposed name. diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AppToolNamesTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AppToolNamesTest.kt index 48b210049..82e3b051b 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AppToolNamesTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AppToolNamesTest.kt @@ -117,6 +117,30 @@ class AppToolNamesTest { assertEquals(forward, byApp()) } + /** + * `com.a.db` and `com.d.db` share `db_db`, and `com.a.db`'s digest form is `db_ec81`, the plain + * prefix of `com.c.ec81`. Were both to take it, the numbering that keeps tool names apart would + * give `_2` to whichever app was read second, and a reordered read would hand `db_ec81_query` + * to the other app's database. + */ + @Test + fun `an app whose digest prefix is another app's plain prefix keeps its names whatever the row order`() { + val apps = listOf("com.a.db", "com.d.db", "com.c.ec81") + connectAll(*apps.map { it to fake(it, tool("query", true)) }.toTypedArray()) + val forward = byApp() + assertEquals(apps.toSet(), forward.keys) + assertEquals("db_ec81_query", forward.getValue("com.c.ec81").first) + assertEquals(3, forward.values.map { it.first }.toSet().size) + + AutomaticServers.install(null) + McpToolCatalog.clear() + servers.forEach { it.stop() } + servers.clear() + connectAll(*apps.map { it to fake(it, tool("query", true)) }.toTypedArray(), reversed = true) + + assertEquals(forward, byApp()) + } + @Test fun `an app listed between two reads of the server list cannot break the listing`() { connectAll( diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolTextTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolTextTest.kt index a7a0c6374..0aad7de40 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolTextTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolTextTest.kt @@ -74,6 +74,48 @@ class McpToolTextTest { assertEquals(prefixes, McpToolText.appPrefixes(ids.reversed())) } + @Test + fun givenAFallbackEqualToAnotherAppsPlainPrefix_whenPrefixed_thenThePlainPrefixKeepsIt() { + // com.a.db and com.d.db share db_db; com.a.db's digest form is db_ec81, com.c.ec81's plain one. + val ids = listOf("com.a.db", "com.d.db", "com.c.ec81") + val prefixes = McpToolText.appPrefixes(ids) + + assertEquals("db_ec81", prefixes.getValue("com.c.ec81")) + assertEquals("db_f048", prefixes.getValue("com.d.db")) + assertEquals("d_ec8102c6", prefixes.getValue("com.a.db")) + assertDistinct(prefixes) + assertEquals(prefixes, McpToolText.appPrefixes(ids.reversed())) + } + + @Test + fun givenTwoAppsWhoseShortDigestsAgree_whenPrefixed_thenTheLongDigestTellsThemApart() { + // Both are db_notes, and both are notes_5599 by the four-digit digest. + val ids = listOf("com.a177.notes", "com.a282.notes", "com.example.shop") + val prefixes = McpToolText.appPrefixes(ids) + + assertEquals("db_shop", prefixes.getValue("com.example.shop")) + assertEquals("n_55990d5b", prefixes.getValue("com.a177.notes")) + assertEquals("n_5599fbc8", prefixes.getValue("com.a282.notes")) + assertDistinct(prefixes) + assertEquals(prefixes, McpToolText.appPrefixes(ids.reversed())) + } + + @Test + fun givenTwoAppsWhoseLongDigestsAgree_whenPrefixed_thenTheyAreNumberedInIdOrder() { + // Both are notes_459b and n_459bb758: the first four bytes of their digests agree. + val ids = listOf("com.pa09e.notes", "com.p182b6.notes") + val prefixes = McpToolText.appPrefixes(ids) + + assertEquals("db_1", prefixes.getValue("com.p182b6.notes")) + assertEquals("db_2", prefixes.getValue("com.pa09e.notes")) + assertEquals(prefixes, McpToolText.appPrefixes(ids.reversed())) + } + + private fun assertDistinct(prefixes: Map) { + assertEquals("two apps share a prefix: $prefixes", prefixes.size, prefixes.values.toSet().size) + assertTrue("a prefix is too long: $prefixes", prefixes.values.all { it.length <= 10 }) + } + @Test fun givenAnAppIdWithNothingUsable_whenPrefixed_thenItStillGetsAName() { assertEquals("db_app", McpToolText.appPrefixes(listOf("com.example.***")).getValue("com.example.***")) From 3c8dba8b10fdaa86a6abe37827969d82ac699c48 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 19 Nov 2026 13:38:41 -0800 Subject: [PATCH 28/90] ADFA-7139 AI-Agent-MCP: the cancel-between-attempts test cancels only after invoke returns CodeRabbit, #166 thread 4634051394. invoke stores the call's future only after its worker has started, so the test's cancel could land first, find no future, and leave an ordinary failure outcome behind; assertTrue(future.isCompletedExceptionally) then failed. Holding invoke's store until the cancel had landed made a copy of the old test fail: java.lang.AssertionError at the assertTrue(future.isCompletedExceptionally) line, right after the check that the hook had forced the order passed. The cancel now waits on a latch released when invoke returns, and the bounded sleep loop at the end gives way to waiting for the worker through McpToolSource's executor seam. The same hook run against the new test cannot force that order (its wait timed out) and the test passes. Test only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../debugger/CancelBetweenAttemptsTest.kt | 21 ++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/CancelBetweenAttemptsTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/CancelBetweenAttemptsTest.kt index 08134d1d6..2773fc34c 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/CancelBetweenAttemptsTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/CancelBetweenAttemptsTest.kt @@ -15,6 +15,8 @@ import io.mockk.every import io.mockk.mockk import io.mockk.mockkObject import io.mockk.unmockkObject +import java.util.concurrent.CountDownLatch +import java.util.concurrent.Executors import java.util.concurrent.TimeUnit import org.junit.After import org.junit.Assert.assertEquals @@ -28,7 +30,8 @@ class CancelBetweenAttemptsTest { private val app = "com.example.app" private val servers = mutableListOf() - private val source = McpToolSource() + private val executor = Executors.newSingleThreadExecutor() + private val source = McpToolSource(executor) private lateinit var plugin: McpPlugin @Before @@ -73,8 +76,15 @@ class CancelBetweenAttemptsTest { val first = fake("t1", tool("list_databases", true)) var stored = listOf(AutomaticEndpoint(app, first.port, "t1")) var cancelOnRead = false + // invoke stores the call's future only after its worker has started, and a cancel that + // landed first would find no future to cancel: the outcome would come back as an ordinary + // failure, which is not what this test is about. So the cancel waits for invoke to return. + val invoked = CountDownLatch(1) AutomaticServers.install { - if (cancelOnRead) source.cancel("call-1") + if (cancelOnRead) { + check(invoked.await(10, TimeUnit.SECONDS)) { "invoke never returned" } + source.cancel("call-1") + } stored } McpToolCatalog.connect(AutomaticServers.servers().single()) @@ -87,11 +97,12 @@ class CancelBetweenAttemptsTest { stored = listOf(AutomaticEndpoint(app, second.port, "t2")) cancelOnRead = true val future = invoke(name) + invoked.countDown() // The agent's future is cancelled with the call; the worker behind it is what must stop. - // Bounded wait: without the check the retry reaches the new endpoint within milliseconds. - val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(2) - while (second.requests.isEmpty() && System.nanoTime() < deadline) Thread.sleep(20) + // Waits for the worker itself, so whatever it was going to send has been sent. + executor.shutdown() + assertTrue("the call never finished", executor.awaitTermination(10, TimeUnit.SECONDS)) assertTrue(future.isCompletedExceptionally) assertTrue("the retry was sent anyway: ${second.requests}", second.requests.isEmpty()) } From 254bf02144c3ee4070bf7b7f9151b24c37daabaf Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 19 Nov 2026 13:38:41 -0800 Subject: [PATCH 29/90] ADFA-7139 AI-Agent-MCP: a failed activation leaves no scope or listener behind From the review in ADFA-7131 (G5). activate called context.addPluginLifecycleListener unguarded after it had started its scope and registered its listeners, and caught only an Exception. A host whose plugin-api differs answers with an AbstractMethodError, which escaped, and the host need not call deactivate after a failed activate: the scope and the listeners were left behind. An Exception from a later host call was caught but left them behind too. The add is guarded like its removal in deactivate (f95d21e6): a failure costs only the re-registration when AI Core activates later. activate also catches a LinkageError, and both catches undo the activation through teardown, now the one path deactivate, dispose and a failed activate share. Tests (McpPluginHostErrorTest): a lifecycle listener the host cannot add costs only that listener; an activation that fails at a later host call, with a linkage error or with an exception, leaves no scope and no listener behind. With only this fix reverted: - "activate let java.lang.AbstractMethodError: PluginContext.addPluginLifecycleListener escape" - "activate let java.lang.AbstractMethodError: PluginLogger.info escape" - the exception case: "the failed activation's scope must be stopped" Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../plugins/aiagentmcp/plugin/McpPlugin.kt | 60 ++++++++++++------ .../plugin/McpPluginHostErrorTest.kt | 61 +++++++++++++++++++ 2 files changed, 103 insertions(+), 18 deletions(-) diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt index fd18dfa80..5a6f94fa3 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt @@ -237,7 +237,11 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { AutomaticServers.addChangeListener(settingsChanged) AutomaticServers.addEndpointListener(relistAutomatic) McpServerHealth.addChangeListener(healthChanged) - context.addPluginLifecycleListener(aiCoreLifecycle) + // Guarded like the removal in teardown: a host whose plugin-api differs answers with a + // LinkageError. That costs only the re-registration when AI Core activates later; with AI + // Core already active, the registration below still works. + runCatchingRecoverable { context.addPluginLifecycleListener(aiCoreLifecycle) } + .onFailure { e -> context.logger.warn("McpPlugin: could not add the lifecycle listener", e) } if (!registerToolSource()) { context.logger.info("McpPlugin: AI Core is not active yet; will register when it is") @@ -255,24 +259,29 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { } true } catch (e: Exception) { - context.logger.error("McpPlugin: activation failed", e) - false + activationFailed(e) + } catch (e: LinkageError) { + // A host call outside the guards above, from a host whose plugin-api differs. + activationFailed(e) + } + + /** + * Undoes a failed [activate] and logs why. + * + * The host need not call [deactivate] after an activation that failed, so nothing else would + * stop the scope it had started or remove the listeners it had registered by then. + * + * @param e what ended the activation. + * @return false, for [activate] to return. + */ + private fun activationFailed(e: Throwable): Boolean { + teardown() + runCatchingRecoverable { context.logger.error("McpPlugin: activation failed", e) } + return false } override fun deactivate(): Boolean = try { - // Guarded like dispose's: a host whose plugin-api differs answers with a LinkageError, and - // one escaping here would skip every step below, leaving the scope and its probe running. - runCatchingRecoverable { context.removePluginLifecycleListener(aiCoreLifecycle) } - .onFailure { e -> context.logger.warn("McpPlugin: could not remove the lifecycle listener", e) } - McpServerStore.removeChangeListener(settingsChanged) - AutomaticServers.removeChangeListener(settingsChanged) - AutomaticServers.removeEndpointListener(relistAutomatic) - McpServerHealth.removeChangeListener(healthChanged) - unregisterToolSource() - // Before the connections are closed: an in-flight refresh would otherwise repopulate the - // catalogue and the session map straight after they were cleared. - stopScope() - releaseConnections() + teardown() true } catch (e: Exception) { context.logger.error("McpPlugin: deactivation failed", e) @@ -280,16 +289,31 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { } override fun dispose() { + teardown() + pluginContext = null + context.logger.info("McpPlugin: disposed") + } + + /** + * Stops what [activate] started: the lifecycle and change listeners, the tool source's + * registration, the scope with its work, and the connections. The one teardown path, shared by + * [deactivate], [dispose] and a failed [activate], so the three cannot drift apart. Safe to run + * on an activation that got only part of the way, and on none at all. + */ + private fun teardown() { + // Guarded: a host whose plugin-api differs answers with a LinkageError, and one escaping + // here would skip every step below, leaving the scope and its probe running. runCatchingRecoverable { context.removePluginLifecycleListener(aiCoreLifecycle) } + .onFailure { e -> context.logger.warn("McpPlugin: could not remove the lifecycle listener", e) } McpServerStore.removeChangeListener(settingsChanged) AutomaticServers.removeChangeListener(settingsChanged) AutomaticServers.removeEndpointListener(relistAutomatic) McpServerHealth.removeChangeListener(healthChanged) unregisterToolSource() + // Before the connections are closed: an in-flight refresh would otherwise repopulate the + // catalogue and the session map straight after they were cleared. stopScope() releaseConnections() - pluginContext = null - context.logger.info("McpPlugin: disposed") } /** diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginHostErrorTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginHostErrorTest.kt index 2b9f30e7a..620025764 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginHostErrorTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginHostErrorTest.kt @@ -1,6 +1,7 @@ package com.itsaky.androidide.plugins.aiagentmcp.plugin import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.PluginLogger import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticEndpoint import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticServers @@ -8,6 +9,7 @@ import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpServerHealth import com.itsaky.androidide.plugins.aiagentmcp.tools.McpToolCatalog import com.itsaky.androidide.plugins.security.KeystoreSecretStore import com.itsaky.androidide.plugins.services.DebuggerEndpoint @@ -28,6 +30,7 @@ import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import org.junit.After import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Before @@ -175,6 +178,64 @@ class McpPluginHostErrorTest { assertNull("deactivate let $escaped escape", escaped) } + /** Every listener registry the plugin registers with, so a test can see one left behind. */ + private fun listenerCounts() = mapOf( + "AutomaticServers change" to AutomaticServers.changeListenerCount, + "AutomaticServers endpoint" to AutomaticServers.endpointListenerCount, + "McpServerStore change" to McpServerStore.changeListenerCount, + "McpServerHealth change" to McpServerHealth.changeListenerCount, + ) + + /** + * The lifecycle listener is added after the scope has started and the change listeners are in. + * The Error used to escape activate, which caught only an Exception, and the host need not call + * deactivate after a failed activate: the scope and the listeners were left behind. Now the + * failure costs only the listener, as its removal's does in deactivate. + */ + @Test + fun `a lifecycle listener the host cannot add costs only that listener`() { + every { context.addPluginLifecycleListener(any()) } throws + AbstractMethodError("PluginContext.addPluginLifecycleListener") + val before = listenerCounts() + + val activated = survives("activate") { plugin.activate() } + + assertTrue("the activation must carry on", activated) + assertTrue("the activation's scope must be live", requireNotNull(plugin.scopeJob).isActive) + assertEquals(before.mapValues { it.value + 1 }, listenerCounts()) + plugin.deactivate() + assertEquals(before, listenerCounts()) + } + + @Test + fun `an activation that fails with a linkage error leaves no scope and no listener behind`() { + assertFailedActivationLeavesNothing(AbstractMethodError("PluginLogger.info")) + } + + @Test + fun `an activation that fails with an exception leaves no scope and no listener behind`() { + assertFailedActivationLeavesNothing(IllegalStateException("PluginLogger.info")) + } + + /** + * Fails an activation after it has started its scope and registered its listeners, at the one + * host call left unguarded by then: the note that AI Core is not active yet. + * @param failure what that call throws. + */ + private fun assertFailedActivationLeavesNothing(failure: Throwable) { + val logger = mockk(relaxed = true) + every { context.logger } returns logger + every { context.getPluginService(any(), ToolSourceRegistry::class.java) } returns null + every { logger.info(match { it.contains("AI Core is not active") }) } throws failure + val before = listenerCounts() + + val activated = survives("activate") { plugin.activate() } + + assertFalse("a failed activation must say so", activated) + assertTrue("the failed activation's scope must be stopped", requireNotNull(plugin.activationJob).isCancelled) + assertEquals("listeners left behind", before, listenerCounts()) + } + @Test fun `an error that escapes a coroutine stops at the backstop, not at the IDE's handler`() { val reached = CopyOnWriteArrayList() From 38561dfecf1791295a63ce33a01608b62acacf06 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 19 Nov 2026 13:38:41 -0800 Subject: [PATCH 30/90] ADFA-7139 AI-Agent-MCP: a 202 body is drained through a fixed buffer From the review in ADFA-7131 (low). McpHttpClient read a 202's body with readBytes inside a bare runCatching: a huge body was held whole in memory, and an OutOfMemoryError from it was swallowed, the case ac56d6ee set out to stop (its message listed this site as safe). drain reads the body to its end through a fixed buffer, keeps its first 32K characters for the connection log (twice what the log shows, so the redactor sees a credential whole at the cut) and counts the rest, under runCatchingRecoverable, so an OutOfMemoryError propagates. The exchange record counts the dropped characters with those its own cap leaves out. Tests (McpHttpClientDrainTest): a 10 MiB body is read to its end but only its start is kept; an OutOfMemoryError while draining reaches the caller; an IOException is a failure the caller survives; and a 202 with a 100 KiB body, over loopback, is recorded capped with the rest counted. With only the old read restored: - "expected java.lang.OutOfMemoryError to be thrown, but nothing was thrown" - "characters kept expected:<100> but was:<10485760>" Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../aiagentmcp/transport/McpExchangeTrace.kt | 9 ++ .../aiagentmcp/transport/McpHttpClient.kt | 49 ++++++++- .../transport/McpHttpClientDrainTest.kt | 103 ++++++++++++++++++ 3 files changed, 159 insertions(+), 2 deletions(-) create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClientDrainTest.kt diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpExchangeTrace.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpExchangeTrace.kt index 6b2719ea6..4bde49d47 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpExchangeTrace.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpExchangeTrace.kt @@ -39,6 +39,15 @@ internal class McpExchangeTrace( responseBody = McpExchange.Body.capped(redactor.scrub(body)) } + /** + * As [received], for a body kept only in part: [dropped] more characters came after [body] + * and were read and thrown away; the record counts them with what its own cap leaves out. + */ + fun received(body: String, dropped: Long) { + val kept = McpExchange.Body.capped(redactor.scrub(body)) + responseBody = kept.copy(omitted = (kept.omitted + dropped).coerceAtMost(Int.MAX_VALUE.toLong()).toInt()) + } + /** * The finished record. * @param failure what ended the request early, or null when it ran to the end. diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt index 67c67f8f3..baa046fa7 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt @@ -1,9 +1,11 @@ package com.itsaky.androidide.plugins.aiagentmcp.transport import android.util.Log +import com.itsaky.androidide.plugins.aiagentmcp.errors.runCatchingRecoverable import com.itsaky.androidide.plugins.aiagentmcp.logging.LOG_PREFIX import java.io.BufferedReader import java.io.IOException +import java.io.InputStream import java.net.HttpURLConnection import java.net.URL import org.json.JSONObject @@ -46,8 +48,51 @@ open class McpHttpClient( /** Same-origin redirects followed before giving up, so a redirect loop cannot spin. */ private const val MAX_REDIRECTS = 5 + + /** + * Characters of a drained body kept for the connection log: twice what the log shows, so + * a credential the redactor has to find is whole even where the log's own cut falls. + */ + private const val DRAINED_CHARS_KEPT = 2 * McpExchange.Body.MAX_CHARS + + /** + * Reads a body to its end through a fixed buffer, keeping only its first [keep] characters. + * + * For a 202, which should carry no body: one left unread keeps the socket out of the pool, + * and a server that sends a huge one must not cost Code on the Go, whose process this + * plugin runs in, its memory. A read that fails with an Exception or a LinkageError is + * returned as a failure, which the caller survives by not reusing the socket; any other + * Error, an OutOfMemoryError above all, propagates. + * + * @param keep how many characters to keep. + * @param open opens the body; called inside the guard, since opening it can fail too. + * @return what was kept and how much was dropped, or the recoverable failure. + */ + internal fun drain(keep: Int = DRAINED_CHARS_KEPT, open: () -> InputStream): Result = + runCatchingRecoverable { + open().reader(Charsets.UTF_8).use { reader -> + val kept = StringBuilder() + val buffer = CharArray(8 * 1024) + var dropped = 0L + while (true) { + val read = reader.read(buffer) + if (read < 0) break + val room = (keep - kept.length).coerceIn(0, read) + kept.append(buffer, 0, room) + dropped += read - room + } + Drained(kept.toString(), dropped) + } + } } + /** + * What [drain] read. + * @property text the body's first characters. + * @property dropped how many characters came after [text] and were read and thrown away. + */ + internal class Drained(val text: String, val dropped: Long) + /** * One answer to a POST. * @property document the JSON-RPC document the server replied with, or null for `202 Accepted`, @@ -115,8 +160,8 @@ open class McpHttpClient( // than ignored, since a body left unread keeps the socket out of the pool. if (conn.responseCode == HttpURLConnection.HTTP_ACCEPTED) { // A half-read body is neither pooled nor closed, so only a whole drain counts. - val drained = runCatching { conn.inputStream.use { it.readBytes() } } - drained.getOrNull()?.let { trace.received(String(it, Charsets.UTF_8)) } + val drained = drain { conn.inputStream } + drained.getOrNull()?.let { trace.received(it.text, it.dropped) } reusable = drained.isSuccess return Response(null, assignedSession) } diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClientDrainTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClientDrainTest.kt new file mode 100644 index 000000000..2a1912582 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClientDrainTest.kt @@ -0,0 +1,103 @@ +package com.itsaky.androidide.plugins.aiagentmcp.transport + +import com.sun.net.httpserver.HttpServer +import java.io.IOException +import java.io.InputStream +import java.net.InetSocketAddress +import java.util.Arrays +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The body of a `202 Accepted`, which should be empty, is read to its end so its socket can be + * reused, through a fixed buffer: a server answering a notification with a huge body must not cost + * Code on the Go its memory, and an OutOfMemoryError while reading one is the process failing, not + * the read, so it reaches the IDE's uncaught-exception handler. + */ +class McpHttpClientDrainTest { + + /** [size] bytes of `a`, made as they are read; records how far it was read and whether it was closed. */ + private class GeneratedBody(private val size: Long) : InputStream() { + var position = 0L + var closed = false + + override fun read(): Int = if (position < size) 'a'.code.also { position++ } else -1 + + override fun read(b: ByteArray, off: Int, len: Int): Int { + if (position >= size) return -1 + val n = minOf(len.toLong(), size - position).toInt() + Arrays.fill(b, off, off + n, 'a'.code.toByte()) + position += n + return n + } + + override fun close() { + closed = true + } + } + + @Test + fun `a large body is read to its end but only its start is kept`() { + val size = 10L * 1024 * 1024 + val body = GeneratedBody(size) + + val drained = McpHttpClient.drain(keep = 100) { body }.getOrThrow() + + assertEquals("characters kept", 100, drained.text.length) + assertEquals("characters dropped", size - 100, drained.dropped) + assertEquals("the body was not read to its end", size, body.position) + assertTrue("the body was not closed", body.closed) + } + + @Test + fun `an OutOfMemoryError while draining reaches the caller`() { + val body = object : InputStream() { + override fun read(): Int = throw OutOfMemoryError("reading a 202 body") + } + + assertThrows(OutOfMemoryError::class.java) { McpHttpClient.drain { body } } + } + + @Test + fun `a read that fails with an IOException is a failure the caller survives`() { + val body = object : InputStream() { + override fun read(): Int = throw IOException("connection reset") + } + + assertTrue(McpHttpClient.drain { body }.isFailure) + } + + /** The drain as [McpHttpClient.post] uses it: the record shows the start and counts the rest. */ + @Test + fun `a 202 with a large body is recorded capped with the rest counted`() { + val size = 100 * 1024 + val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply { + createContext("/mcp") { exchange -> + exchange.requestBody.use { it.readBytes() } + exchange.sendResponseHeaders(202, size.toLong()) + exchange.responseBody.use { it.write(ByteArray(size) { 'a'.code.toByte() }) } + } + start() + } + try { + var recorded: McpExchange? = null + val response = McpHttpClient().post( + "http://127.0.0.1:${server.address.port}/mcp", + "", + JSONObject().put("jsonrpc", "2.0").put("method", "notifications/initialized"), + exchangeListener = { exchange, _ -> recorded = exchange }, + ) + + assertNull(response.document) + val body = requireNotNull(recorded?.responseBody) + assertEquals(McpExchange.Body.MAX_CHARS, body.text.length) + assertEquals(size - McpExchange.Body.MAX_CHARS, body.omitted) + } finally { + server.stop(0) + } + } +} From a4d901cdfe1848747aad8c8271cb61acf07f24ac Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 19 Nov 2026 13:38:41 -0800 Subject: [PATCH 31/90] ADFA-7139 AI-Agent-MCP: runCatchingRecoverable rethrows a cancellation From the review in ADFA-7131 (low). CancellationException is an Exception, so runCatchingRecoverable kept it as a failure. No block passed to it suspends today, so nothing broke, but a coroutine that kept its own cancellation as one more failure would carry on with work nobody wants. It is now rethrown first; the KDoc says why. Tests (RecoverableTest): a cancellation is rethrown; an Exception and a LinkageError are kept as failures; an OutOfMemoryError is let through. With only the rethrow removed: "expected java.util.concurrent.CancellationException to be thrown, but nothing was thrown" Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../plugins/aiagentmcp/errors/Recoverable.kt | 8 +++++ .../aiagentmcp/errors/RecoverableTest.kt | 33 +++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/RecoverableTest.kt diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/Recoverable.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/Recoverable.kt index 9493ebb70..d9c698ba7 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/Recoverable.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/Recoverable.kt @@ -1,5 +1,7 @@ package com.itsaky.androidide.plugins.aiagentmcp.errors +import kotlin.coroutines.cancellation.CancellationException + /** * As [runCatching], but catching only what this plugin can recover from: an [Exception], or a * [LinkageError], which is how a host whose plugin-api differs from this plugin's fails a call @@ -9,11 +11,17 @@ package com.itsaky.androidide.plugins.aiagentmcp.errors * all: it means the process is failing, not one call, and the IDE's uncaught-exception handler has * to see it rather than this plugin quietly carrying on. * + * So does a [CancellationException], although it is an Exception: it is how a coroutine learns it + * was cancelled, and a coroutine that kept it as one more failure would carry on with work nobody + * wants. No block passed here suspends today; this keeps the first one that does honest. + * * @param block the work, usually one that reaches the host directly or through a listener. * @return its value, or the recoverable failure it threw. */ internal inline fun runCatchingRecoverable(block: () -> T): Result = try { Result.success(block()) +} catch (e: CancellationException) { + throw e } catch (e: Exception) { Result.failure(e) } catch (e: LinkageError) { diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/RecoverableTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/RecoverableTest.kt new file mode 100644 index 000000000..ecb910426 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/RecoverableTest.kt @@ -0,0 +1,33 @@ +package com.itsaky.androidide.plugins.aiagentmcp.errors + +import kotlin.coroutines.cancellation.CancellationException +import org.junit.Assert.assertEquals +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Test + +/** What [runCatchingRecoverable] keeps as a failure and what it lets through. */ +class RecoverableTest { + + @Test + fun `a cancellation is rethrown, not kept as a failure`() { + val thrown = assertThrows(CancellationException::class.java) { + runCatchingRecoverable { throw CancellationException("the coroutine was cancelled") } + } + + assertEquals("the coroutine was cancelled", thrown.message) + } + + @Test + fun `an exception and a linkage error are kept as failures`() { + assertTrue(runCatchingRecoverable { throw IllegalStateException("a host call") }.isFailure) + assertTrue(runCatchingRecoverable { throw AbstractMethodError("a host call") }.isFailure) + } + + @Test + fun `an OutOfMemoryError is let through`() { + assertThrows(OutOfMemoryError::class.java) { + runCatchingRecoverable { throw OutOfMemoryError("the process") } + } + } +} From 57b43126820857deb8de9514ce865f17ef799b74 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 19 Nov 2026 13:38:41 -0800 Subject: [PATCH 32/90] ADFA-7139 AI-Agent-MCP: refresh's KDoc says what a fatal Error from a listener skips From the review in ADFA-7131 (low). An Error that propagates from an endpoint or change listener, or from closing a gone entry's session, does so after refresh has stored the new entries, so the steps still to run for that read are skipped and no later read repeats them. The KDoc now says so, and why that is accepted: the Error is the process failing on its way to the IDE's uncaught-exception handler. Documentation only; no test. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../plugins/aiagentmcp/debugger/AutomaticServers.kt | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt index a89fb1107..e40fbc38a 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt @@ -158,7 +158,12 @@ object AutomaticServers { * * A read that fails with an Exception or a LinkageError leaves the entries as they were; any * other Error, an OutOfMemoryError above all, propagates to the caller. So does one from a - * change or endpoint listener. + * change or endpoint listener, or from closing the session of an entry that went away. Such an + * Error comes after the new entries are stored, so it skips what was still to run for this + * read: the remaining endpoint listeners, the reset of a refused credential for the remaining + * moved entries, and the change listeners. No later read repeats them, since it finds those + * entries unchanged. That is accepted rather than guarded against: the Error is the process + * failing, and the IDE's uncaught-exception handler, which it is on its way to, ends it. * * @param keepGoing checked after the read, before anything is stored. * @return true when the set of entries, a port or a token changed. From 6f95b2aeecd4405eb72230a719459cec64057c47 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 19 Nov 2026 18:16:48 -0800 Subject: [PATCH 33/90] ADFA-7139 AI-Agent-MCP: register a tool call before it is scheduled so a cancel always finds it A cancel landing after the worker started and before its first line set no flag and found no session, so the request still went out. invoke now registers the call before supplyAsync, and exactly one party removes the entry (the worker, the completion callback when the call finished without the worker, or invoke when scheduling threw). The cancel flag lives on the call, so it cannot outlive it. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../plugins/aiagentmcp/tools/McpToolSource.kt | 145 +++++++++----- .../tools/CancelAfterWorkerStartsTest.kt | 185 ++++++++++++++++++ 2 files changed, 285 insertions(+), 45 deletions(-) create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/CancelAfterWorkerStartsTest.kt diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt index 2ebe880de..8653315bd 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt @@ -18,6 +18,7 @@ import java.util.concurrent.CompletableFuture import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ExecutorService import java.util.concurrent.Executors +import java.util.concurrent.atomic.AtomicBoolean private const val TAG = "$LOG_PREFIX.McpToolSource" @@ -30,9 +31,23 @@ private const val TAG = "$LOG_PREFIX.McpToolSource" * * @param executor where remote calls run; see [newExecutor]. A seam, so a test can wait for a * call's worker to finish rather than poll for something it might still send. + * @param beforeWork runs on the worker thread with the call's id, before the worker does anything + * else. A seam, so a test can land a cancel at the one point after the worker has started. + * + * A call is owned from the moment [invoke] accepts it, not from the moment its worker starts, so a + * [cancel] always finds it. The ownership rule, for every entry: + * - [calls]: [invoke] adds the entry before it schedules the worker. Exactly one party then removes + * it, whichever wins [Call.claimed]: the worker, in [runTool]'s `finally`, or [invoke]'s + * completion callback when the call finished without the worker (cancelled before it ran), or + * [invoke] itself when scheduling threw. The loser does nothing, and a worker that loses sends + * nothing. + * - [inFlight]: [invoke] adds it once the future exists; the future's completion removes it. + * - [liveSessions]: the attempt that opened the session adds it and removes it when the request + * ends; [cancel] removes it too, to drop the socket. */ class McpToolSource internal constructor( private val executor: ExecutorService, + private val beforeWork: (String) -> Unit = {}, ) : ToolSourceRegistry.StatusReportingToolSource, ToolSourceRegistry.GroupedToolSource { @@ -50,16 +65,28 @@ class McpToolSource internal constructor( */ private val liveSessions = ConcurrentHashMap() - /** Calls whose worker is running, so [cancel] knows whether a flag will ever be read. */ - private val running: MutableSet = ConcurrentHashMap.newKeySet() + /** + * Every accepted call that has not finished, so [cancel] knows a call exists whatever its worker + * has reached. See the class KDoc for who removes an entry. + */ + private val calls = ConcurrentHashMap() /** - * Running calls that were cancelled. The session drop in [cancel] reaches only a request in - * flight; one landing between the two attempts of the endpoint retry finds no session, so the - * retry reads this before it sends anything. So does one landing while an attempt looks its - * session up, which is why the attempt reads it again once the session is in [liveSessions]. + * One accepted call. + * + * [cancelled] is what a cancel leaves for the worker. The session drop in [cancel] reaches only + * a request in flight; one landing between the two attempts of the endpoint retry, during a + * session lookup, or before the worker's first line finds no session, so the worker reads this + * before it sends anything, and again once its session is in [liveSessions]. It lives on the + * call, so it goes with the call and a late cancel cannot leave a stray flag behind. + * + * [claimed] is the cleanup ownership: the first party to set it, the worker as it starts or the + * completion callback as it finds the call finished without one, is the only one to clean up. */ - private val cancelled: MutableSet = ConcurrentHashMap.newKeySet() + private class Call { + @Volatile var cancelled = false + val claimed = AtomicBoolean(false) + } override fun getProviderId(): String = McpPlugin.PLUGIN_ID @@ -115,17 +142,37 @@ class McpToolSource internal constructor( Outcome(false, "", string(R.string.mcp_error_tool_gone, invocation.toolName)) ) - val future = CompletableFuture.supplyAsync( - { runTool(invocation.callId, target.first, target.second, invocation.arguments) }, - executor, - ) - inFlight[invocation.callId] = future - return future.whenComplete { _, _ -> inFlight.remove(invocation.callId) } + val callId = invocation.callId + // Before the worker is scheduled, so a cancel landing at any point after this finds the call. + val call = Call() + calls[callId] = call + val future = try { + CompletableFuture.supplyAsync( + { + beforeWork(callId) + runTool(callId, call, target.first, target.second, invocation.arguments) + }, + executor, + ) + } catch (e: Throwable) { + // Scheduling failed (a rejected task, a shut-down executor): no worker will ever run. + calls.remove(callId, call) + throw e + } + inFlight[callId] = future + return future.whenComplete { _, _ -> + inFlight.remove(callId) + // Finished without the worker (cancelled before it ran): nobody else will clean up. + if (call.claimed.compareAndSet(false, true)) calls.remove(callId, call) + } } + /** How many accepted calls have not finished; for a test to prove nothing is left behind. */ + internal fun pendingCalls(): Int = calls.size + override fun cancel(callId: String) { + calls[callId]?.cancelled = true inFlight.remove(callId)?.cancel(true) - if (callId in running) cancelled += callId // The worker is blocked on a socket read, where an interrupt does nothing; dropping the // connection is what actually ends it. Only this call's, so a concurrent call against // another server keeps its socket. @@ -137,11 +184,13 @@ class McpToolSource internal constructor( executor.shutdownNow() inFlight.clear() liveSessions.clear() + calls.clear() } /** * Runs one remote tool. * @param callId the agent's id for this call, so [cancel] can reach the session it is using. + * @param call the call's entry, registered by [invoke] before this was scheduled. * @param server the server that owns it. * @param tool the tool, as the server described it. * @param arguments the agent's arguments. @@ -149,42 +198,48 @@ class McpToolSource internal constructor( */ private fun runTool( callId: String, + call: Call, server: McpServer, tool: McpTool, arguments: Map, - ): ToolSourceRegistry.ToolOutcome = try { - running += callId - val result = McpToolCatalog.retry.call(server) { target -> - // Cancelled between two attempts (or before the first): nothing is sent. Signalled as - // an interrupted read, which is how a dropped connection already reports a cancel. - if (callId in cancelled) throw InterruptedIOException("Tool call $callId was cancelled") - val session = McpConnections.session(target) - liveSessions[callId] = session - try { - // Again, now the session is published: a cancel that landed during the lookup - // found no session to drop, and only its flag can stop the request. One landing - // after this read finds the session and drops it. - if (callId in cancelled) throw InterruptedIOException("Tool call $callId was cancelled") - session.callTool(tool.name, arguments) - } finally { - liveSessions.remove(callId) + ): ToolSourceRegistry.ToolOutcome { + // Lost: the call finished (cancelled) before this worker began, and the completion callback + // has cleaned up. The result is discarded, so send nothing. + if (!call.claimed.compareAndSet(false, true)) { + return Outcome(false, "", string(R.string.mcp_error_cancelled, server.name)) + } + return try { + val result = McpToolCatalog.retry.call(server) { target -> + // Cancelled between two attempts (or before the first): nothing is sent. Signalled as + // an interrupted read, which is how a dropped connection already reports a cancel. + if (call.cancelled) throw InterruptedIOException("Tool call $callId was cancelled") + val session = McpConnections.session(target) + liveSessions[callId] = session + try { + // Again, now the session is published: a cancel that landed during the lookup + // found no session to drop, and only its flag can stop the request. One landing + // after this read finds the session and drops it. + if (call.cancelled) throw InterruptedIOException("Tool call $callId was cancelled") + session.callTool(tool.name, arguments) + } finally { + liveSessions.remove(callId) + } } + // A reply of any kind, a tool's own failure included, means the server is answering. + McpServerHealth.available(server.id) + Outcome(result.success, result.text, result.errorMessage) + } catch (e: Throwable) { + // Throwable, unlike the other host-facing catches in this plugin: this runs inside + // CompletableFuture.supplyAsync, which catches every Throwable itself, so narrowing this + // would not bring an OutOfMemoryError to the IDE's handler. It would only hand AI Core an + // exceptionally completed future in place of the failure outcome it expects. + Log.w(TAG, "Tool '${tool.name}' on '${server.name}' failed", e) + McpToolCatalog.recordFailure(server, e) + val context = McpPlugin.getContext()?.androidContext + Outcome(false, "", McpErrorFormatter.format(context, server, e)) + } finally { + calls.remove(callId, call) } - // A reply of any kind, a tool's own failure included, means the server is answering. - McpServerHealth.available(server.id) - Outcome(result.success, result.text, result.errorMessage) - } catch (e: Throwable) { - // Throwable, unlike the other host-facing catches in this plugin: this runs inside - // CompletableFuture.supplyAsync, which catches every Throwable itself, so narrowing this - // would not bring an OutOfMemoryError to the IDE's handler. It would only hand AI Core an - // exceptionally completed future in place of the failure outcome it expects. - Log.w(TAG, "Tool '${tool.name}' on '${server.name}' failed", e) - McpToolCatalog.recordFailure(server, e) - val context = McpPlugin.getContext()?.androidContext - Outcome(false, "", McpErrorFormatter.format(context, server, e)) - } finally { - running -= callId - cancelled -= callId } /** diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/CancelAfterWorkerStartsTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/CancelAfterWorkerStartsTest.kt new file mode 100644 index 000000000..dc488af3b --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/CancelAfterWorkerStartsTest.kt @@ -0,0 +1,185 @@ +package com.itsaky.androidide.plugins.aiagentmcp.tools + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import com.itsaky.androidide.plugins.services.ToolSourceRegistry +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import java.util.concurrent.CompletableFuture +import java.util.concurrent.CancellationException +import java.util.concurrent.CountDownLatch +import java.util.concurrent.ExecutionException +import java.util.concurrent.ExecutorService +import java.util.concurrent.Executors +import java.util.concurrent.RejectedExecutionException +import java.util.concurrent.TimeUnit +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Before +import org.junit.Test + +/** + * A cancel must always find the call it cancels, whatever its worker has reached, and a call must + * leave nothing registered however it ends. + * + * The worker's first instructions used to be the only place a call became known to + * [McpToolSource.cancel]; one landing before them set no flag and found no session, and the + * request went out. The calls are now registered before they are scheduled. These tests force the + * orders with latches: no sleeps, and every wait ends on a latch or on the executor terminating. + */ +class CancelAfterWorkerStartsTest { + + private val delegate = Executors.newSingleThreadExecutor() + private lateinit var server: FakeMcpServer + private lateinit var plugin: McpPlugin + private lateinit var name: String + private var requestsBefore = 0 + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } returns KeystoreSecretStore.Stored.Absent + every { McpServerStore.headers(any()) } returns emptyMap() + server = FakeMcpServer("", listOf(tool("search", true))) + val docs = McpServerStore.saveDetails( + McpServerStore.newServer("Docs", "http://127.0.0.1:${server.port}/mcp") + ) + McpToolCatalog.connect(docs) + McpServerStore.setToolEnabled(docs.id, "search", true) + name = McpToolSource(delegate).listTools().single().name + requestsBefore = server.requests.size + } + + @After + fun tearDown() { + delegate.shutdownNow() + McpConnections.closeAll() + McpToolCatalog.clear() + server.stop() + plugin.dispose() + unmockkObject(McpServerStore) + } + + private fun invoke(source: McpToolSource): CompletableFuture = + source.invoke( + mockk { + every { toolName } returns name + every { arguments } returns emptyMap() + every { callId } returns CALL_ID + } + ) + + private fun awaitWorkers() { + delegate.shutdown() + assertTrue("the worker never finished", delegate.awaitTermination(10, TimeUnit.SECONDS)) + } + + /** The future [McpToolSource.invoke] returns completes with the scheduled future's cancellation. */ + private fun assertEndedCancelled(future: CompletableFuture<*>) { + assertTrue("the call did not end", future.isDone) + val failure = try { + future.get(10, TimeUnit.SECONDS) + null + } catch (e: CancellationException) { + e + } catch (e: ExecutionException) { + e.cause + } + assertTrue("the call did not end cancelled: $failure", failure is CancellationException) + } + + private fun assertNothingSent() = assertEquals( + "the call reached the server after it was cancelled: ${server.requests.drop(requestsBefore)}", + requestsBefore, + server.requests.size, + ) + + @Test + fun `a cancel that lands after the worker started and before its first line sends nothing`() { + val started = CountDownLatch(1) + val proceed = CountDownLatch(1) + val source = McpToolSource(delegate) { + started.countDown() + assertTrue("the test never released the worker", proceed.await(10, TimeUnit.SECONDS)) + } + + val future = invoke(source) + assertTrue("the worker never started", started.await(10, TimeUnit.SECONDS)) + source.cancel(CALL_ID) + proceed.countDown() + awaitWorkers() + + assertNothingSent() + assertEndedCancelled(future) + assertEquals("a cancelled call left its registration behind", 0, source.pendingCalls()) + } + + @Test + fun `a call cancelled before its worker runs sends nothing and leaves no registration`() { + val release = CountDownLatch(1) + val held = object : ExecutorService by delegate { + override fun execute(command: Runnable) = delegate.execute { + assertTrue("the test never released the worker", release.await(10, TimeUnit.SECONDS)) + command.run() + } + } + val source = McpToolSource(held) + + val future = invoke(source) + source.cancel(CALL_ID) + assertEquals("a call cancelled before it ran kept its registration", 0, source.pendingCalls()) + release.countDown() + awaitWorkers() + + assertNothingSent() + assertEndedCancelled(future) + assertEquals(0, source.pendingCalls()) + } + + @Test + fun `a normal call leaves no registration behind`() { + val source = McpToolSource(delegate) + + val outcome = invoke(source).get(10, TimeUnit.SECONDS) + + assertTrue("the call failed: ${outcome.errorMessage}", outcome.isSuccess) + assertTrue("the call never reached the server", server.requests.size > requestsBefore) + assertEquals("a finished call left its registration behind", 0, source.pendingCalls()) + } + + @Test + fun `a call whose scheduling throws leaves no registration behind`() { + val rejecting = object : ExecutorService by delegate { + override fun execute(command: Runnable) = throw RejectedExecutionException("full") + } + val source = McpToolSource(rejecting) + + try { + invoke(source) + fail("scheduling should have thrown") + } catch (expected: RejectedExecutionException) { + assertFalse(expected.message.isNullOrEmpty()) + } + + assertEquals("a call that was never scheduled kept its registration", 0, source.pendingCalls()) + assertNothingSent() + } + + private companion object { + const val CALL_ID = "call-1" + } +} From 769bb4c2dba80ecbd302f41afb7c9180c7c0173a Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 19 Nov 2026 22:36:34 -0800 Subject: [PATCH 34/90] ADFA-7139 AI-Agent-MCP: a cancel and the exchange listener no longer swallow an OutOfMemoryError From the review in ADFA-7139 (low). Three bare runCatching calls caught every Throwable: McpToolSource.cancel around the session drop, McpSession.cancel around the disconnect, and the exchangeListener call in the finally of McpHttpClient.post. They now use runCatchingRecoverable, the plugin's rule: an Exception or a LinkageError is survived, any other Error propagates to the IDE's uncaught-exception handler. Tests (McpHttpClientListenerFailureTest): a listener that throws an Exception still lets the reply through; an OutOfMemoryError from the listener reaches the caller. With only the listener's runCatching restored: "expected java.lang.OutOfMemoryError to be thrown, but nothing was thrown" Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../plugins/aiagentmcp/client/McpSession.kt | 9 ++- .../plugins/aiagentmcp/tools/McpToolSource.kt | 6 +- .../aiagentmcp/transport/McpHttpClient.kt | 6 +- .../McpHttpClientListenerFailureTest.kt | 62 +++++++++++++++++++ 4 files changed, 78 insertions(+), 5 deletions(-) create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClientListenerFailureTest.kt diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSession.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSession.kt index 9371499da..ab625daf0 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSession.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSession.kt @@ -189,9 +189,14 @@ class McpSession( } } - /** Drops the connection a call is blocked on, so a stopped agent run does not wait it out. */ + /** + * Drops the connection a call is blocked on, so a stopped agent run does not wait it out. + * + * A disconnect that fails with an Exception or a LinkageError is survived, since the call is + * being abandoned anyway; any other Error, an OutOfMemoryError above all, propagates. + */ fun cancel() { - runCatching { liveConnection?.disconnect() } + runCatchingRecoverable { liveConnection?.disconnect() } } /** diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt index 8653315bd..798f2cff2 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt @@ -7,6 +7,7 @@ import com.itsaky.androidide.plugins.aiagentmcp.client.McpTool import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticServers import com.itsaky.androidide.plugins.aiagentmcp.debugger.McpServers import com.itsaky.androidide.plugins.aiagentmcp.errors.McpErrorFormatter +import com.itsaky.androidide.plugins.aiagentmcp.errors.runCatchingRecoverable import com.itsaky.androidide.plugins.aiagentmcp.R import com.itsaky.androidide.plugins.aiagentmcp.logging.LOG_PREFIX import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin @@ -175,8 +176,9 @@ class McpToolSource internal constructor( inFlight.remove(callId)?.cancel(true) // The worker is blocked on a socket read, where an interrupt does nothing; dropping the // connection is what actually ends it. Only this call's, so a concurrent call against - // another server keeps its socket. - liveSessions.remove(callId)?.let { runCatching { it.cancel() } } + // another server keeps its socket. An Exception or a LinkageError from the drop is survived; + // any other Error propagates. + liveSessions.remove(callId)?.let { runCatchingRecoverable { it.cancel() } } } /** Ends the executor, for the plugin shutting down. */ diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt index baa046fa7..5d4995c8d 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt @@ -111,6 +111,7 @@ open class McpHttpClient( * @param protocolVersion the negotiated revision, or null before `initialize` has answered. * @param onConnected receives the live connection, so a caller can disconnect it to cancel. * @param exchangeListener receives each request made and what came back, redirects included. + * An Exception or a LinkageError it throws is dropped; any other Error propagates. * @return the reply document and any session id the server sent. * @throws McpHttpException on a non-2xx answer, carrying the server's error body. */ @@ -186,7 +187,10 @@ open class McpHttpClient( throw e } finally { if (!reusable) conn.disconnect() - runCatching { exchangeListener.onExchange(trace.toExchange(failure), redactor) } + // The connection log is a convenience: a listener failing with an Exception or a + // LinkageError costs only its record. Any other Error, an OutOfMemoryError above + // all, is the process failing and propagates. + runCatchingRecoverable { exchangeListener.onExchange(trace.toExchange(failure), redactor) } } if (++hops > MAX_REDIRECTS) { diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClientListenerFailureTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClientListenerFailureTest.kt new file mode 100644 index 000000000..6cf440510 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClientListenerFailureTest.kt @@ -0,0 +1,62 @@ +package com.itsaky.androidide.plugins.aiagentmcp.transport + +import com.sun.net.httpserver.HttpServer +import java.net.InetSocketAddress +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertThrows +import org.junit.Before +import org.junit.Test + +/** + * The exchange listener feeds the connection log, a convenience: one that fails with an Exception + * costs only its record, and the request's reply still reaches the caller. An OutOfMemoryError + * from it is the process failing, not the listener, so it reaches the IDE's uncaught-exception + * handler rather than being swallowed with the record. + */ +class McpHttpClientListenerFailureTest { + + private val reply = """{"jsonrpc":"2.0","id":1,"result":{}}""" + private lateinit var server: HttpServer + + @Before + fun startServer() { + server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply { + createContext("/mcp") { exchange -> + exchange.requestBody.use { it.readBytes() } + val bytes = reply.toByteArray() + exchange.responseHeaders.add("Content-Type", "application/json") + exchange.sendResponseHeaders(200, bytes.size.toLong()) + exchange.responseBody.use { it.write(bytes) } + } + start() + } + } + + @After + fun stopServer() { + server.stop(0) + } + + private fun postWith(listener: McpExchangeListener) = McpHttpClient().post( + "http://127.0.0.1:${server.address.port}/mcp", + "", + JSONObject().put("jsonrpc", "2.0").put("id", 1).put("method", "ping"), + exchangeListener = listener, + ) + + @Test + fun `a listener that throws an Exception costs only its record`() { + val response = postWith { _, _ -> throw IllegalStateException("the log is full") } + + assertEquals(reply, response.document) + } + + @Test + fun `an OutOfMemoryError from the listener reaches the caller`() { + assertThrows(OutOfMemoryError::class.java) { + postWith { _, _ -> throw OutOfMemoryError("recording an exchange") } + } + } +} From 84be92dbbde0865d3fffc335116c18c06d5976a2 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 19 Nov 2026 22:57:06 -0800 Subject: [PATCH 35/90] ADFA-7139 AI-Agent-MCP: a cancel stops only its own call's connection, and stops it before the request goes out From the review in ADFA-7139: F03 (medium) and F04 (low), one change. F03: between the worker's second read of the cancel flag and onConnected, send() reads the credentials, which decrypts the token through the Keystore. A cancel landing there found the session and called session.cancel(), which dropped nothing because liveConnection was still null, and nothing read the flag again, so the tools/call went out. F04: every call to a server, the 20 s probe's listing and relistAutomatic shared the session's one liveConnection. A cancel dropped whichever request had published last, and any request's finally cleared the field while another was still running. Stopping a run while the probe listed the same server dropped the probe's socket (the server was marked DEGRADED) and the cancelled call ran on to its 60 s timeout. The connection is now tracked per call. McpCallHandle holds a call's cancel flag and its current request's connection, and McpToolSource's Call owns one. callTool -> call -> send hands it to post's onConnected, which publishes the connection and then reads the flag, throwing InterruptedIOException before anything is written; cancel() sets the flag and then takes the connection. The `initialize` request goes through the handle too; notifications/initialized does not, so a cancel cannot leave a session marked initialized whose server was never told. Listings pass no handle, so no call's cancel reaches them. McpSession.cancel(), liveConnection and McpToolSource.liveSessions are gone. The ownership rule of 6f95b2ae (one cleanup owner per calls entry, through Call.claimed) is unchanged; the KDoc, README layout and the in-app page say what a cancel now reaches. Tests: - CancelDuringCredentialsReadTest (the review's scenario): a cancel that lands while the tools/call request reads its credentials sends nothing. - SameServerCancelTest: cancelling call A while call B to the same server is in flight leaves B successful and sends nothing for A; cancelling A while the probe's listing of the same server is in flight leaves the listing successful and the server not degraded, and sends nothing for A. - McpCallHandleTest: the handshake both ways round, a detached connection is not dropped, and the disconnect's catch follows the plugin's rule. With only McpSession.kt and McpToolSource.kt restored to their previous versions: "the call reached the server after it was cancelled: [Seen(httpMethod=POST, authorization=null)] expected:<3> but was:<4>" "B was never cancelled but failed: " "the listing was never cancelled but failed: java.net.SocketException: Socket closed" With McpCallHandle.attach's flag check and its runCatchingRecoverable replaced (by `if (false)` and runCatching): "expected java.io.InterruptedIOException to be thrown, but nothing was thrown" "expected java.lang.OutOfMemoryError to be thrown, but nothing was thrown" The existing cancel tests (CancelAfterWorkerStartsTest, CancelDuringSessionLookupTest, CancelBetweenAttemptsTest) stay green. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- plugins/AI-Agent-MCP/README.md | 3 +- plugins/AI-Agent-MCP/ai-agent-mcp.html | 3 +- .../aiagentmcp/client/McpCallHandle.kt | 75 ++++++ .../plugins/aiagentmcp/client/McpSession.kt | 80 ++++-- .../plugins/aiagentmcp/tools/McpToolSource.kt | 69 ++--- .../aiagentmcp/client/McpCallHandleTest.kt | 82 ++++++ .../tools/CancelDuringCredentialsReadTest.kt | 113 ++++++++ .../tools/CancelDuringSessionLookupTest.kt | 10 +- .../aiagentmcp/tools/SameServerCancelTest.kt | 241 ++++++++++++++++++ 9 files changed, 600 insertions(+), 76 deletions(-) create mode 100644 plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpCallHandle.kt create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpCallHandleTest.kt create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/CancelDuringCredentialsReadTest.kt create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/SameServerCancelTest.kt diff --git a/plugins/AI-Agent-MCP/README.md b/plugins/AI-Agent-MCP/README.md index 93d21fcae..54299ae1b 100644 --- a/plugins/AI-Agent-MCP/README.md +++ b/plugins/AI-Agent-MCP/README.md @@ -131,7 +131,8 @@ Two dependencies were deliberately not taken: parallel with no ordering - `transport/` — `JsonRpc` framing, `SseChunk` line parsing, `McpHttpClient` - `client/` — `McpSession` (handshake, `tools/list`, `tools/call`), - `McpConnections` (one session per server) + `McpConnections` (one session per server, shared by every call and listing), + `McpCallHandle` (one tool call's cancel: its flag and its own connection) - `tools/` — `McpToolSource` (the `ToolSourceRegistry.ToolSource`), `McpToolCatalog` (what each server last advertised), `McpToolText` (sanitising) - `settings/` — server CRUD, per-tool toggles, the settings pane diff --git a/plugins/AI-Agent-MCP/ai-agent-mcp.html b/plugins/AI-Agent-MCP/ai-agent-mcp.html index aaca2e012..5ad195893 100644 --- a/plugins/AI-Agent-MCP/ai-agent-mcp.html +++ b/plugins/AI-Agent-MCP/ai-agent-mcp.html @@ -93,7 +93,8 @@

Technical architecture

McpToolSourceThe tool source AI Core sees. Publishes the enabled tools of the enabled servers, runs a call on its own thread pool, and drops that call's own connection when an Agent run is - stopped, leaving any concurrent call against another server alone. + stopped. Any other call, and the health check's listing, is left alone, + whether it is against the same server or another. McpToolCatalogWhat each server last advertised, held in memory. The Agent reads its tool list on a UI-adjacent path, so that list is answered from memory and never blocks on the network. diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpCallHandle.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpCallHandle.kt new file mode 100644 index 000000000..dbca4d218 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpCallHandle.kt @@ -0,0 +1,75 @@ +package com.itsaky.androidide.plugins.aiagentmcp.client + +import android.util.Log +import com.itsaky.androidide.plugins.aiagentmcp.errors.runCatchingRecoverable +import com.itsaky.androidide.plugins.aiagentmcp.logging.LOG_PREFIX +import java.io.InterruptedIOException +import java.net.HttpURLConnection +import java.util.concurrent.atomic.AtomicReference + +private const val TAG = "$LOG_PREFIX.McpCallHandle" + +/** + * One tool call's way to be stopped: its cancel flag and the connection its current request uses. + * + * Per call, not per session. Every call to a server, the health probe's listing and the relisting + * of a SQLite debugger entry share one [McpSession]; a connection slot on the session held whichever + * request had published last, so a cancel dropped another request's socket (the probe's listing + * was then marked degraded) and the cancelled call ran on to its timeout. A listing passes no + * handle, so no call's cancel can reach it. + * + * The handshake, the same one the tool worker uses with its flag: a request publishes its + * connection and then reads the flag ([attach]); [cancel] sets the flag and then takes the + * connection. Both sides are volatile, so however the two interleave, one sees the other: either + * the request finds the flag before it sends anything, or the cancel finds the connection and + * drops it. A cancel that lands before the request has a connection at all, while it reads its + * credentials from the Keystore for instance, is caught by the first. + */ +class McpCallHandle { + + @Volatile private var cancelled = false + + private val connection = AtomicReference(null) + + /** Whether [cancel] has been called. */ + val isCancelled: Boolean get() = cancelled + + /** + * Stops the call: a request not yet sent never is, and one in flight loses its socket. + * + * A disconnect that fails with an Exception or a LinkageError is survived, since the call is + * being abandoned anyway; any other Error, an OutOfMemoryError above all, propagates. + */ + fun cancel() { + cancelled = true + connection.getAndSet(null)?.let { conn -> + runCatchingRecoverable { conn.disconnect() } + .onFailure { e -> Log.d(TAG, "Dropping a cancelled call's connection failed: $e") } + } + } + + /** + * Publishes [conn] as the connection this call's current request uses, then reads the flag. + * + * Called before anything is written to [conn], so a cancelled call sends nothing. + * + * @param conn the request's connection, opened but not yet connected. + * @throws InterruptedIOException when the call was cancelled, which is how a dropped connection + * reports a cancel too. + */ + internal fun attach(conn: HttpURLConnection) { + connection.set(conn) + if (cancelled) { + connection.compareAndSet(conn, null) + throw InterruptedIOException("The tool call was cancelled before its request was sent") + } + } + + /** + * Forgets the connection once its request has ended, so a late [cancel] does not disconnect a + * connection whose socket may have gone back to the pool. + */ + internal fun detach() { + connection.set(null) + } +} diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSession.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSession.kt index ab625daf0..d86ff47d2 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSession.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSession.kt @@ -22,6 +22,11 @@ private const val TAG = "$LOG_PREFIX.McpSession" * Every call is blocking and belongs off the main thread; the callers are a background executor * (tool invocation) and the settings pane's IO dispatcher (Connect). * + * The session is shared: every tool call to its server, the health probe's listing and the + * relisting of a SQLite debugger entry use it, at the same time. So it holds no connection of its + * own for a cancel to drop; a tool call brings an [McpCallHandle], and only that call's requests + * are published to it. + * * @param endpoint the server's MCP URL. * @param credentials read once per request; see [McpCredentials] for why they are not held here. * @param http the transport; injectable so the protocol can be exercised without a socket. @@ -69,9 +74,6 @@ class McpSession( @Volatile private var initialized = false - /** The connection a call is currently using, so [cancel] can drop it mid-flight. */ - @Volatile private var liveConnection: HttpURLConnection? = null - /** Who is watching the exchanges made on each thread; see [recording]. */ private val recorder = ThreadLocal() @@ -84,8 +86,21 @@ class McpSession( * * @throws IOException when the server cannot be reached or refuses the handshake. */ + fun initialize() = initialize(handle = null) + + /** + * As [initialize], with the `initialize` request published to [handle], so a call cancelled + * while it waits on the handshake stops waiting. A cancelled handshake is not recorded, and the + * next caller repeats it. + * + * `notifications/initialized` is sent without the handle: once the server has answered, the + * handshake is finished for every caller, and a session marked initialized whose server was + * never told so would have each later request answered "not initialized". + * + * @param handle the calling tool call's, or null for a listing. + */ @Synchronized - fun initialize() { + private fun initialize(handle: McpCallHandle?) { if (initialized) return val params = JSONObject().apply { @@ -100,7 +115,7 @@ class McpSession( ) } - val result = call(METHOD_INITIALIZE, params) + val result = call(METHOD_INITIALIZE, params, handle) negotiatedVersion = result.optString("protocolVersion").takeIf { it.isNotBlank() } ?: PREFERRED_PROTOCOL_VERSION serverName = result.optJSONObject("serverInfo")?.optString("name")?.takeIf { it.isNotBlank() } @@ -144,11 +159,19 @@ class McpSession( * * @param name the tool's own name, as the server listed it. * @param arguments the call arguments. + * @param handle this call's own, so a cancel stops this call's requests and no one else's; + * null for a call nothing will cancel. * @return the outcome, successful or not. * @throws IOException when the server cannot be reached. + * @throws java.io.InterruptedIOException when [handle] was cancelled; a request not yet sent + * is not sent. */ - fun callTool(name: String, arguments: Map): McpCallResult { - initialize() + fun callTool( + name: String, + arguments: Map, + handle: McpCallHandle? = null, + ): McpCallResult { + initialize(handle) val params = JSONObject().apply { put("name", name) @@ -156,7 +179,7 @@ class McpSession( } val result = try { - call("tools/call", params) + call("tools/call", params, handle) } catch (e: McpProtocolException) { // A protocol-level error for a single call is the tool failing, not the session dying. return McpCallResult(false, "", e.message ?: "The server rejected the call.") @@ -189,16 +212,6 @@ class McpSession( } } - /** - * Drops the connection a call is blocked on, so a stopped agent run does not wait it out. - * - * A disconnect that fails with an Exception or a LinkageError is survived, since the call is - * being abandoned anyway; any other Error, an OutOfMemoryError above all, propagates. - */ - fun cancel() { - runCatchingRecoverable { liveConnection?.disconnect() } - } - /** * Ends the server-side session, if there is one, and forgets the handshake. * @@ -249,15 +262,20 @@ class McpSession( * * @param method the MCP method. * @param params its parameters, or null. + * @param handle the calling tool call's, or null for a listing. * @return the `result` object. * @throws McpProtocolException when the server answers a JSON-RPC error. * @throws IOException on transport failure or a reply that is not one. */ - private fun call(method: String, params: JSONObject? = null): JSONObject { + private fun call( + method: String, + params: JSONObject? = null, + handle: McpCallHandle? = null, + ): JSONObject { val envelope = JsonRpc.request(nextId.getAndIncrement().toString(), method, params) val response = try { - send(envelope) + send(envelope, handle) } catch (e: McpHttpException) { val retryable = e.statusCode == HttpURLConnection.HTTP_NOT_FOUND && sessionId != null && @@ -266,8 +284,8 @@ class McpSession( Log.i(TAG, "Session expired; re-initializing before retrying $method") sessionId = null initialized = false - initialize() - send(envelope) + initialize(handle) + send(envelope, handle) } else { throw e } @@ -288,12 +306,18 @@ class McpSession( return reply.result ?: JSONObject() } - /** POSTs one envelope, tracking the connection so [cancel] can reach it. */ - private fun send(envelope: JSONObject): McpHttpClient.Response { + /** + * POSTs one envelope. + * + * @param handle the calling tool call's: its connection is published there before anything is + * sent, and the request is refused if the call was cancelled meanwhile, while the credentials + * were read for instance. Null for a listing, which no call's cancel reaches. + */ + private fun send(envelope: JSONObject, handle: McpCallHandle? = null): McpHttpClient.Response { // Read here rather than held on the session, so the plaintext lives for one request. val current = credentials() - // Cleared in a finally: a call that threw would otherwise leave [cancel] holding a - // connection that is already closed, and the next cancel would reach nothing live. + // Forgotten in a finally, so a late cancel does not disconnect a connection whose request + // has ended and whose socket may be back in the pool. val response = try { http.post( url = endpoint, @@ -302,11 +326,11 @@ class McpSession( sessionId = sessionId, protocolVersion = negotiatedVersion, extraHeaders = current.headers, - onConnected = { liveConnection = it }, + onConnected = { conn -> handle?.attach(conn) }, exchangeListener = recorder.get() ?: McpExchangeListener.NONE, ) } finally { - liveConnection = null + handle?.detach() } response.sessionId?.let { sessionId = it } return response diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt index 798f2cff2..7b497a64a 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt @@ -1,13 +1,12 @@ package com.itsaky.androidide.plugins.aiagentmcp.tools import android.util.Log +import com.itsaky.androidide.plugins.aiagentmcp.client.McpCallHandle import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections -import com.itsaky.androidide.plugins.aiagentmcp.client.McpSession import com.itsaky.androidide.plugins.aiagentmcp.client.McpTool import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticServers import com.itsaky.androidide.plugins.aiagentmcp.debugger.McpServers import com.itsaky.androidide.plugins.aiagentmcp.errors.McpErrorFormatter -import com.itsaky.androidide.plugins.aiagentmcp.errors.runCatchingRecoverable import com.itsaky.androidide.plugins.aiagentmcp.R import com.itsaky.androidide.plugins.aiagentmcp.logging.LOG_PREFIX import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin @@ -43,8 +42,11 @@ private const val TAG = "$LOG_PREFIX.McpToolSource" * [invoke] itself when scheduling threw. The loser does nothing, and a worker that loses sends * nothing. * - [inFlight]: [invoke] adds it once the future exists; the future's completion removes it. - * - [liveSessions]: the attempt that opened the session adds it and removes it when the request - * ends; [cancel] removes it too, to drop the socket. + * + * A cancel reaches a call through its [Call.handle] alone: the flag the worker reads, and the + * connection the call's current request is using. Not through its session, which every call to + * that server, the health probe's listing and a SQLite debugger entry's relisting share; see + * [McpCallHandle] for the handshake that keeps a cancelled call from sending anything. */ class McpToolSource internal constructor( private val executor: ExecutorService, @@ -54,18 +56,9 @@ class McpToolSource internal constructor( constructor() : this(newExecutor()) - /** Calls in flight, so a stopped agent run can drop the socket instead of waiting it out. */ + /** Each accepted call's future, so a cancel completes it at once rather than when its worker ends. */ private val inFlight = ConcurrentHashMap>() - /** - * The session each in-flight call is using. - * - * Per call rather than "every session there is": two tools can be in flight against different - * servers at once, and cancelling both would report the survivor to the model as a transport - * failure for a call nobody cancelled. - */ - private val liveSessions = ConcurrentHashMap() - /** * Every accepted call that has not finished, so [cancel] knows a call exists whatever its worker * has reached. See the class KDoc for who removes an entry. @@ -75,17 +68,18 @@ class McpToolSource internal constructor( /** * One accepted call. * - * [cancelled] is what a cancel leaves for the worker. The session drop in [cancel] reaches only - * a request in flight; one landing between the two attempts of the endpoint retry, during a - * session lookup, or before the worker's first line finds no session, so the worker reads this - * before it sends anything, and again once its session is in [liveSessions]. It lives on the - * call, so it goes with the call and a late cancel cannot leave a stray flag behind. + * [handle] is what a cancel reaches: its flag, which the worker reads before it looks up a + * session (so a cancel between the two attempts of the endpoint retry, or before the worker's + * first line, sends nothing), and the connection of the call's current request, which each + * request publishes and then checks the flag against before it sends anything. It lives on the + * call, so it goes with the call and a late cancel cannot leave a stray flag behind, nor reach + * another call's or a listing's connection. * * [claimed] is the cleanup ownership: the first party to set it, the worker as it starts or the * completion callback as it finds the call finished without one, is the only one to clean up. */ private class Call { - @Volatile var cancelled = false + val handle = McpCallHandle() val claimed = AtomicBoolean(false) } @@ -172,26 +166,23 @@ class McpToolSource internal constructor( internal fun pendingCalls(): Int = calls.size override fun cancel(callId: String) { - calls[callId]?.cancelled = true + // Sets the flag and drops the call's connection: the worker is blocked on a socket read, + // where an interrupt does nothing, so dropping the connection is what actually ends it. + // Only this call's, so another call or a listing against the same server keeps its socket. + calls[callId]?.handle?.cancel() inFlight.remove(callId)?.cancel(true) - // The worker is blocked on a socket read, where an interrupt does nothing; dropping the - // connection is what actually ends it. Only this call's, so a concurrent call against - // another server keeps its socket. An Exception or a LinkageError from the drop is survived; - // any other Error propagates. - liveSessions.remove(callId)?.let { runCatchingRecoverable { it.cancel() } } } /** Ends the executor, for the plugin shutting down. */ fun close() { executor.shutdownNow() inFlight.clear() - liveSessions.clear() calls.clear() } /** * Runs one remote tool. - * @param callId the agent's id for this call, so [cancel] can reach the session it is using. + * @param callId the agent's id for this call, named in the failure a cancel leaves. * @param call the call's entry, registered by [invoke] before this was scheduled. * @param server the server that owns it. * @param tool the tool, as the server described it. @@ -212,20 +203,16 @@ class McpToolSource internal constructor( } return try { val result = McpToolCatalog.retry.call(server) { target -> - // Cancelled between two attempts (or before the first): nothing is sent. Signalled as - // an interrupted read, which is how a dropped connection already reports a cancel. - if (call.cancelled) throw InterruptedIOException("Tool call $callId was cancelled") - val session = McpConnections.session(target) - liveSessions[callId] = session - try { - // Again, now the session is published: a cancel that landed during the lookup - // found no session to drop, and only its flag can stop the request. One landing - // after this read finds the session and drops it. - if (call.cancelled) throw InterruptedIOException("Tool call $callId was cancelled") - session.callTool(tool.name, arguments) - } finally { - liveSessions.remove(callId) + // Cancelled between two attempts (or before the first): nothing is looked up or sent. + // Signalled as an interrupted read, which is how a dropped connection already + // reports a cancel. + if (call.handle.isCancelled) { + throw InterruptedIOException("Tool call $callId was cancelled") } + // A cancel landing from here on, during the session lookup or while a request reads + // its credentials, is caught by the handle: each request publishes its connection + // there and reads the flag again before it sends anything. + McpConnections.session(target).callTool(tool.name, arguments, call.handle) } // A reply of any kind, a tool's own failure included, means the server is answering. McpServerHealth.available(server.id) diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpCallHandleTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpCallHandleTest.kt new file mode 100644 index 000000000..68d236368 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpCallHandleTest.kt @@ -0,0 +1,82 @@ +package com.itsaky.androidide.plugins.aiagentmcp.client + +import java.io.InterruptedIOException +import java.net.HttpURLConnection +import java.net.URL +import org.junit.Assert.assertEquals +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The handshake between a request and a cancel, either way round: a request that publishes its + * connection after the cancel sends nothing, and a cancel after the request published drops that + * connection and no other. + */ +class McpCallHandleTest { + + /** A connection that never connects; counts its disconnects, or fails them with [failure]. */ + private class FakeConnection(private val failure: Throwable? = null) : + HttpURLConnection(URL("http://127.0.0.1/mcp")) { + var disconnects = 0 + + override fun disconnect() { + failure?.let { throw it } + disconnects++ + } + + override fun usingProxy() = false + + override fun connect() = Unit + } + + @Test + fun `a request attached after the cancel is refused before it sends anything`() { + val handle = McpCallHandle() + handle.cancel() + + assertThrows(InterruptedIOException::class.java) { handle.attach(FakeConnection()) } + } + + @Test + fun `a cancel after the request attached drops its connection`() { + val handle = McpCallHandle() + val conn = FakeConnection() + handle.attach(conn) + + handle.cancel() + + assertEquals(1, conn.disconnects) + assertTrue(handle.isCancelled) + } + + @Test + fun `a cancel after the request ended drops nothing`() { + val handle = McpCallHandle() + val conn = FakeConnection() + handle.attach(conn) + handle.detach() + + handle.cancel() + + assertEquals("a finished request's connection may be back in the pool", 0, conn.disconnects) + } + + @Test + fun `a disconnect that fails with an Exception is survived`() { + val handle = McpCallHandle() + handle.attach(FakeConnection(IllegalStateException("already closed"))) + + handle.cancel() + + assertTrue(handle.isCancelled) + } + + @Test + fun `an OutOfMemoryError from the disconnect reaches the caller`() { + val handle = McpCallHandle() + handle.attach(FakeConnection(OutOfMemoryError("disconnecting"))) + + assertThrows(OutOfMemoryError::class.java) { handle.cancel() } + } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/CancelDuringCredentialsReadTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/CancelDuringCredentialsReadTest.kt new file mode 100644 index 000000000..3587e7611 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/CancelDuringCredentialsReadTest.kt @@ -0,0 +1,113 @@ +package com.itsaky.androidide.plugins.aiagentmcp.tools + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import com.itsaky.androidide.plugins.services.ToolSourceRegistry +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicInteger +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * A cancel that lands while a request reads its credentials must stop the call. + * + * Reading them decrypts the token through the Keystore, after the worker's own read of the cancel + * flag and before the request has a connection a cancel could drop. A cancel there used to find the + * session, drop nothing, and leave the `tools/call` to go out; each request now publishes its + * connection to the call's handle and reads the flag again before it sends anything. + * + * The test lands the cancel there for certain. Once armed, the worker reads the server's token + * twice: first while it looks up its session, then while the `tools/call` request reads its + * credentials, and that second read cancels the call. + */ +class CancelDuringCredentialsReadTest { + + private val executor = Executors.newSingleThreadExecutor() + private val source = McpToolSource(executor) + private val armed = AtomicBoolean(false) + private val reads = AtomicInteger(0) + private lateinit var server: FakeMcpServer + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + // The Keystore is not there on the JVM; this server has no secrets. + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } answers { + if (armed.get() && reads.incrementAndGet() == CREDENTIALS_READ) { + armed.set(false) + source.cancel(CALL_ID) + } + KeystoreSecretStore.Stored.Absent + } + every { McpServerStore.headers(any()) } returns emptyMap() + server = FakeMcpServer("", listOf(tool("search", true))) + } + + @After + fun tearDown() { + source.close() + McpConnections.closeAll() + McpToolCatalog.clear() + server.stop() + plugin.dispose() + unmockkObject(McpServerStore) + } + + @Test + fun `a cancel that lands while the request reads its credentials sends nothing`() { + val docs = McpServerStore.saveDetails( + McpServerStore.newServer("Docs", "http://127.0.0.1:${server.port}/mcp") + ) + McpToolCatalog.connect(docs) + McpServerStore.setToolEnabled(docs.id, "search", true) + val name = source.listTools().single().name + val before = server.requests.size + + armed.set(true) + source.invoke( + mockk { + every { toolName } returns name + every { arguments } returns emptyMap() + every { callId } returns CALL_ID + } + ) + // Waits for the worker itself, so whatever it was going to send has been sent. + executor.shutdown() + assertTrue("the call never finished", executor.awaitTermination(10, TimeUnit.SECONDS)) + + assertFalse("the call never read its credentials", armed.get()) + assertEquals( + "the call reached the server after it was cancelled: ${server.requests.drop(before)}", + before, + server.requests.size, + ) + assertEquals("a cancelled call left its registration behind", 0, source.pendingCalls()) + } + + private companion object { + const val CALL_ID = "call-1" + + /** The session lookup reads the token first; the `tools/call` request's read is second. */ + const val CREDENTIALS_READ = 2 + } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/CancelDuringSessionLookupTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/CancelDuringSessionLookupTest.kt index 0b43ed407..0a93b7bcc 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/CancelDuringSessionLookupTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/CancelDuringSessionLookupTest.kt @@ -26,11 +26,11 @@ import org.junit.Test /** * A cancel that lands while a call looks up its session must stop the call. * - * The lookup sits between the call's check of the cancel flag and the moment its session becomes - * reachable from [McpToolSource.cancel]. A cancel in that window sets the flag but finds no session - * to drop, so only a second read of the flag, once the session is published, keeps the request - * from going out. The test lands the cancel there for certain: the lookup reads the server's token, - * and the first read after the test arms it cancels the call. + * The lookup sits between the worker's check of the cancel flag and the call's first request. A + * cancel in that window sets the flag but finds no connection to drop, so only a later read of the + * flag, once the request has published its connection to the call's handle, keeps the request from + * going out. The test lands the cancel there for certain: the lookup reads the server's token, and + * the first read after the test arms it cancels the call. */ class CancelDuringSessionLookupTest { diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/SameServerCancelTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/SameServerCancelTest.kt new file mode 100644 index 000000000..003a0c494 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/SameServerCancelTest.kt @@ -0,0 +1,241 @@ +package com.itsaky.androidide.plugins.aiagentmcp.tools + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServer +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import com.itsaky.androidide.plugins.services.ToolSourceRegistry +import com.sun.net.httpserver.HttpServer +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import java.net.InetSocketAddress +import java.util.concurrent.CompletableFuture +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.CountDownLatch +import java.util.concurrent.ExecutorService +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicInteger +import org.json.JSONArray +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * Cancelling one tool call stops that call and nothing else on the same server. + * + * Every call to a server, the health probe's listing and a SQLite debugger entry's relisting share + * one session. The session used to hold one connection for a cancel to drop: whichever request had + * published last. Cancelling call A while call B, or the probe, was in flight dropped B's or the + * probe's socket instead (the probe then marked the server degraded), and A's own request went out + * and ran to its timeout. Each call now publishes its requests to its own handle. + * + * A is cancelled while its `tools/call` request reads its credentials, the point at which it has + * no connection of its own yet and the other request's is the session's latest. Every wait ends on + * a latch or a worker finishing; nothing sleeps. + */ +class SameServerCancelTest { + + private val pool = Executors.newFixedThreadPool(2) + + /** Ended latches, one per worker in the order the calls were invoked. */ + private val workerEnded = List(2) { CountDownLatch(1) } + private val scheduled = AtomicInteger(0) + private val executor = object : ExecutorService by pool { + override fun execute(command: Runnable) { + val ended = workerEnded[scheduled.getAndIncrement()] + pool.execute { + try { + command.run() + } finally { + ended.countDown() + } + } + } + } + private val source = McpToolSource(executor) + + private val armed = AtomicBoolean(false) + private val reads = AtomicInteger(0) + + /** Which calls' `tools/call` reached the server, by their `who` argument. */ + private val calls = CopyOnWriteArrayList() + + /** Held: B's `tools/call` stays in flight until [release]. */ + private val bArrived = CountDownLatch(1) + + /** Held when set: the next `tools/list` stays in flight until [release]. */ + private val holdListing = AtomicBoolean(false) + private val listingArrived = CountDownLatch(1) + private val release = CountDownLatch(1) + + private val handlers = Executors.newCachedThreadPool() + private lateinit var http: HttpServer + private lateinit var plugin: McpPlugin + private lateinit var docs: McpServer + private lateinit var name: String + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + // Once armed, A reads the token twice: for its session lookup, then for its tools/call + // request's credentials, which is where A is cancelled. + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } answers { + if (armed.get() && reads.incrementAndGet() == CREDENTIALS_READ) { + armed.set(false) + source.cancel(CALL_A) + } + KeystoreSecretStore.Stored.Absent + } + every { McpServerStore.headers(any()) } returns emptyMap() + http = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply { + // Concurrent, so a held request does not hold the others behind it. + executor = handlers + createContext("/mcp") { exchange -> answer(exchange) } + start() + } + docs = McpServerStore.saveDetails( + McpServerStore.newServer("Docs", "http://127.0.0.1:${http.address.port}/mcp") + ) + McpToolCatalog.connect(docs) + McpServerStore.setToolEnabled(docs.id, "search", true) + name = source.listTools().single().name + } + + @After + fun tearDown() { + release.countDown() + source.close() + pool.shutdownNow() + McpConnections.closeAll() + McpToolCatalog.clear() + http.stop(0) + handlers.shutdownNow() + plugin.dispose() + unmockkObject(McpServerStore) + } + + /** The MCP methods this test needs, holding B's call and, when asked, one listing. */ + private fun answer(exchange: com.sun.net.httpserver.HttpExchange) { + if (exchange.requestMethod == "DELETE") { + exchange.sendResponseHeaders(200, -1) + exchange.close() + return + } + val request = JSONObject(exchange.requestBody.use { String(it.readBytes()) }) + val id = request.opt("id") + if (id == null) { + exchange.sendResponseHeaders(202, -1) + exchange.close() + return + } + val result = when (request.getString("method")) { + "initialize" -> JSONObject().put("protocolVersion", "2025-03-26") + "tools/list" -> { + if (holdListing.getAndSet(false)) { + listingArrived.countDown() + release.await(10, TimeUnit.SECONDS) + } + JSONObject().put("tools", JSONArray(listOf(tool("search", true)))) + } + "tools/call" -> { + val who = request.getJSONObject("params").getJSONObject("arguments").optString("who") + calls += who + if (who == CALL_B) { + bArrived.countDown() + release.await(10, TimeUnit.SECONDS) + } + JSONObject().put( + "content", + JSONArray().put(JSONObject().put("type", "text").put("text", "ok $who")), + ) + } + else -> JSONObject() + } + val bytes = JSONObject().put("jsonrpc", "2.0").put("id", id).put("result", result) + .toString().toByteArray() + exchange.responseHeaders.add("Content-Type", "application/json") + // A dropped client is what the old code did to B; the write failing then is expected. + runCatching { + exchange.sendResponseHeaders(200, bytes.size.toLong()) + exchange.responseBody.use { it.write(bytes) } + } + exchange.close() + } + + private fun invoke(id: String): CompletableFuture = + source.invoke( + mockk { + every { toolName } returns name + every { arguments } returns mapOf("who" to id) + every { callId } returns id + } + ) + + @Test + fun `cancelling a call leaves another call to the same server alone and sends nothing`() { + val b = invoke(CALL_B) + assertTrue("B never reached the server", bArrived.await(10, TimeUnit.SECONDS)) + + armed.set(true) + invoke(CALL_A) + assertTrue("A's worker never finished", workerEnded[1].await(10, TimeUnit.SECONDS)) + release.countDown() + val outcome = b.get(10, TimeUnit.SECONDS) + + assertFalse("A was never cancelled", armed.get()) + assertTrue("B was never cancelled but failed: ${outcome.errorMessage}", outcome.isSuccess) + assertEquals("A was cancelled but its request went out", listOf(CALL_B), calls.toList()) + } + + @Test + fun `cancelling a call leaves the probe's listing of the same server alone`() { + holdListing.set(true) + // The probe's own call, on a thread of its own as the probe's coroutine would be. + var listing: Result? = null + val probe = Thread { listing = runCatching { McpToolCatalog.connect(docs) } }.apply { start() } + assertTrue("the listing never reached the server", listingArrived.await(10, TimeUnit.SECONDS)) + + armed.set(true) + invoke(CALL_A) + assertTrue("A's worker never finished", workerEnded[0].await(10, TimeUnit.SECONDS)) + release.countDown() + probe.join(10_000) + + assertFalse("A was never cancelled", armed.get()) + val result = requireNotNull(listing) { "the listing never finished" } + assertTrue( + "the listing was never cancelled but failed: ${result.exceptionOrNull()}", + result.isSuccess, + ) + assertNotEquals( + "a cancelled call marked the server degraded", + McpServerHealth.State.DEGRADED, + McpServerHealth.of(docs.id)?.state, + ) + assertEquals("A was cancelled but its request went out", emptyList(), calls.toList()) + } + + private companion object { + const val CALL_A = "a" + const val CALL_B = "b" + + /** The session lookup reads the token first; the `tools/call` request's read is second. */ + const val CREDENTIALS_READ = 2 + } +} From 89fd92e8598056d28dec61da0e07d41d6981b6a1 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 19 Nov 2026 23:36:02 -0800 Subject: [PATCH 36/90] ADFA-7139 AI-Agent-MCP: a second activate keeps the registered tool source From the review in ADFA-7139 (low, latent). A second activate() replaced toolSource with a new McpToolSource. registered was already true, so the new one was never registered; AI Core kept the first, deactivate unregistered the new one (AI Core's registry matches by identity), and the first stayed registered and was never closed. activate now keeps the existing source (toolSource ?: McpToolSource()). teardown() already closes it and clears the field, so the activation after a deactivate, or after a failed activate, still builds a fresh one, and a second activate cancels none of the first one's calls in flight. Test (DoubleActivateToolSourceTest, the review's scenario): activate, activate, deactivate against a registry that unregisters by identity leaves no source registered, and only one was ever registered. With only the `?:` removed: "tool sources still registered after deactivate expected:<0> but was:<1>" Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../plugins/aiagentmcp/plugin/McpPlugin.kt | 11 +++- .../plugin/DoubleActivateToolSourceTest.kt | 64 +++++++++++++++++++ 2 files changed, 74 insertions(+), 1 deletion(-) create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/DoubleActivateToolSourceTest.kt diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt index 5a6f94fa3..b641ba774 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt @@ -49,6 +49,11 @@ private const val TAG = "$LOG_PREFIX.McpPlugin" class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { private lateinit var context: PluginContext + + /** + * The tool source registered with AI Core: built by the first [activate], kept by a second, and + * closed and cleared by [teardown]. + */ private var toolSource: McpToolSource? = null /** True once [toolSource] is registered with AI Core, so re-registration is idempotent. */ @@ -228,7 +233,11 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { // a concurrent lifecycle call has since installed. val active = swapScope(newScope()) activationJob = active.coroutineContext[Job] - toolSource = McpToolSource() + // Kept by a second activate: it is the one registered with AI Core, whose registry + // unregisters by identity, and [registered] is already true, so a replacement would never be + // registered while this one stayed registered and was never closed. [teardown] closes it and + // clears the field, so the activation after a deactivate builds a fresh one. + toolSource = toolSource ?: McpToolSource() // Here, not on the coroutine below: a lifecycle call registers and removes every listener, // so a late coroutine of an activation that has ended cannot add one, or remove the next // activation's. The add methods ignore a listener already registered, so a host that diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/DoubleActivateToolSourceTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/DoubleActivateToolSourceTest.kt new file mode 100644 index 000000000..a2c31fe21 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/DoubleActivateToolSourceTest.kt @@ -0,0 +1,64 @@ +package com.itsaky.androidide.plugins.aiagentmcp.plugin + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.services.SharedServices +import com.itsaky.androidide.plugins.services.ToolSourceRegistry +import io.mockk.every +import io.mockk.mockk +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Test + +/** + * A host that activates the plugin twice and then deactivates it leaves no tool source registered. + * + * The second activation used to build a new tool source. The first was already registered, so the + * new one never was, and deactivation unregistered the new one: AI Core's registry matches by + * identity, so the first stayed registered, and it was never closed. The registry here matches the + * same way. + */ +class DoubleActivateToolSourceTest { + + /** What the registry holds now. */ + private val registered = mutableListOf() + + /** Every source ever registered, in order. */ + private val everRegistered = mutableListOf() + + private val registry = mockk(relaxed = true) { + every { registerToolSource(any()) } answers { + val source = firstArg() + registered.removeAll { it.providerId == source.providerId } + registered += source + everRegistered += source + } + every { unregisterToolSource(any()) } answers { + val source = firstArg() + registered.removeAll { it === source } + } + } + + @After + fun tearDown() { + SharedServices.unregister(ToolSourceRegistry::class.java) + } + + @Test + fun `activate, activate, deactivate leaves no tool source registered`() { + SharedServices.register(ToolSourceRegistry::class.java, registry) + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + val plugin = McpPlugin().also { it.initialize(context) } + try { + plugin.activate() + plugin.activate() + plugin.deactivate() + + assertEquals("tool sources still registered after deactivate", 0, registered.size) + assertEquals("the second activation registered another source", 1, everRegistered.size) + } finally { + plugin.dispose() + } + } +} From e11abdd1c5f46b37fb2c85d49dba46ef22bf1967 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Thu, 19 Nov 2026 23:36:02 -0800 Subject: [PATCH 37/90] ADFA-7139 AI-Agent-MCP: the drain of a 202 body stops after a fixed budget From the review in ADFA-7139 (low, latent). drain() read a 202 body until EOF. A server answering notifications/initialized with a body that never ends held the read, and with it initialize(), which is @Synchronized, and every health check and call waiting on that session. drain() now stops once it has dropped DRAIN_BUDGET_CHARS (1 Mi characters, about 1 MiB of ASCII) past the characters it keeps, and returns a DrainBudgetException as its failure, so post() leaves the connection unreusable and disconnects it; post() logs any drain failure. The KDoc says the budget bounds how much is read, not how long (a body trickled slower than the read timeout can still hold the read until it has sent the budget), and that a JSON reply and an error body are still read whole with readText(), which is unchanged. Tests (McpHttpClientDrainTest): - a body past the budget is abandoned without being read to its end; - over a real socket, a 202 whose body never ends returns within the budget and the next request arrives on a new connection; - the control: a 202 with no body leaves its socket for the next request; - the large-body test now uses a body within the budget (half of it). With only the budget check removed: "a body past the budget was read to its end: 67108864 bytes" "test timed out after 30000 milliseconds" (the endless 202) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../aiagentmcp/transport/McpHttpClient.kt | 44 +++++++- .../transport/McpHttpClientDrainTest.kt | 100 +++++++++++++++++- 2 files changed, 136 insertions(+), 8 deletions(-) diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt index 5d4995c8d..b2bb79cd5 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt @@ -55,20 +55,43 @@ open class McpHttpClient( */ private const val DRAINED_CHARS_KEPT = 2 * McpExchange.Body.MAX_CHARS + /** + * Characters of a 202 body read and thrown away, past the ones kept, before the drain gives + * up on it: about 1 MiB of ASCII. Far more than any server sends by mistake, and little + * enough that a body which never ends costs a moment rather than the call. + */ + internal const val DRAIN_BUDGET_CHARS = 1L shl 20 + /** * Reads a body to its end through a fixed buffer, keeping only its first [keep] characters. * * For a 202, which should carry no body: one left unread keeps the socket out of the pool, * and a server that sends a huge one must not cost Code on the Go, whose process this - * plugin runs in, its memory. A read that fails with an Exception or a LinkageError is - * returned as a failure, which the caller survives by not reusing the socket; any other - * Error, an OutOfMemoryError above all, propagates. + * plugin runs in, its memory. Nor its time: a body that runs on past [budget] dropped + * characters is abandoned as a failure. A server streaming one forever would otherwise hold + * the read, and with it `initialize`, which is synchronized, and every health check behind + * it. A read that fails with an Exception or a LinkageError is returned as a failure too. + * The caller survives either by not reusing the socket; any other Error, an OutOfMemoryError + * above all, propagates. + * + * The budget bounds how much is read, not how long it takes: a server that trickles a body + * slower than the read timeout can still hold the read until it has sent [budget]. + * + * Only a 202 is bounded this way. A JSON reply and an error body are read whole, with + * `readText()`: each is the document the caller needs. * * @param keep how many characters to keep. + * @param budget how many characters past [keep] may be read and dropped before the body is + * abandoned. * @param open opens the body; called inside the guard, since opening it can fail too. - * @return what was kept and how much was dropped, or the recoverable failure. + * @return what was kept and how much was dropped, or the failure: a recoverable read + * failure, or a [DrainBudgetException] for a body that ran past [budget]. */ - internal fun drain(keep: Int = DRAINED_CHARS_KEPT, open: () -> InputStream): Result = + internal fun drain( + keep: Int = DRAINED_CHARS_KEPT, + budget: Long = DRAIN_BUDGET_CHARS, + open: () -> InputStream, + ): Result = runCatchingRecoverable { open().reader(Charsets.UTF_8).use { reader -> val kept = StringBuilder() @@ -80,6 +103,11 @@ open class McpHttpClient( val room = (keep - kept.length).coerceIn(0, read) kept.append(buffer, 0, room) dropped += read - room + if (dropped > budget) { + throw DrainBudgetException( + "A 202 body ran past ${kept.length + budget} characters; abandoned it" + ) + } } Drained(kept.toString(), dropped) } @@ -93,6 +121,9 @@ open class McpHttpClient( */ internal class Drained(val text: String, val dropped: Long) + /** A 202 body that ran past [DRAIN_BUDGET_CHARS]; its socket is disconnected, not reused. */ + internal class DrainBudgetException(message: String) : IOException(message) + /** * One answer to a POST. * @property document the JSON-RPC document the server replied with, or null for `202 Accepted`, @@ -163,6 +194,9 @@ open class McpHttpClient( // A half-read body is neither pooled nor closed, so only a whole drain counts. val drained = drain { conn.inputStream } drained.getOrNull()?.let { trace.received(it.text, it.dropped) } + drained.exceptionOrNull()?.let { e -> + Log.w(TAG, "Not reusing the connection after its 202 body: ${e.message}") + } reusable = drained.isSuccess return Response(null, assignedSession) } diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClientDrainTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClientDrainTest.kt index 2a1912582..7464c3ae7 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClientDrainTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClientDrainTest.kt @@ -7,6 +7,7 @@ import java.net.InetSocketAddress import java.util.Arrays import org.json.JSONObject import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotEquals import org.junit.Assert.assertNull import org.junit.Assert.assertThrows import org.junit.Assert.assertTrue @@ -16,7 +17,8 @@ import org.junit.Test * The body of a `202 Accepted`, which should be empty, is read to its end so its socket can be * reused, through a fixed buffer: a server answering a notification with a huge body must not cost * Code on the Go its memory, and an OutOfMemoryError while reading one is the process failing, not - * the read, so it reaches the IDE's uncaught-exception handler. + * the read, so it reaches the IDE's uncaught-exception handler. A body that runs past the drain's + * budget is abandoned and its socket disconnected, so one that never ends cannot hold the handshake. */ class McpHttpClientDrainTest { @@ -41,8 +43,8 @@ class McpHttpClientDrainTest { } @Test - fun `a large body is read to its end but only its start is kept`() { - val size = 10L * 1024 * 1024 + fun `a large body within the budget is read to its end but only its start is kept`() { + val size = McpHttpClient.DRAIN_BUDGET_CHARS / 2 val body = GeneratedBody(size) val drained = McpHttpClient.drain(keep = 100) { body }.getOrThrow() @@ -53,6 +55,23 @@ class McpHttpClientDrainTest { assertTrue("the body was not closed", body.closed) } + @Test + fun `a body past the budget is abandoned without being read to its end`() { + val keep = 100 + val budget = 64L * 1024 + val body = GeneratedBody(64L * 1024 * 1024) + + val drained = McpHttpClient.drain(keep = keep, budget = budget) { body } + + assertTrue( + "a body past the budget was read to its end: ${body.position} bytes", + drained.exceptionOrNull() is McpHttpClient.DrainBudgetException, + ) + // The reader buffers ahead of what the drain has counted, by at most a buffer or two. + assertTrue("read ${body.position} bytes", body.position <= keep + budget + 64 * 1024) + assertTrue("the body was not closed", body.closed) + } + @Test fun `an OutOfMemoryError while draining reaches the caller`() { val body = object : InputStream() { @@ -71,6 +90,81 @@ class McpHttpClientDrainTest { assertTrue(McpHttpClient.drain { body }.isFailure) } + /** + * A 202 whose body never ends: the POST returns once the drain's budget is spent, and the next + * request arrives on a new connection, so the abandoned socket was disconnected rather than + * pooled. Timed out rather than left to hang, should the drain read forever. + */ + @Test(timeout = 30_000) + fun `a 202 whose body never ends returns within the budget and its socket is not reused`() { + val ports = java.util.concurrent.CopyOnWriteArrayList() + val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply { + createContext("/mcp") { exchange -> + ports += exchange.remoteAddress.port + val request = JSONObject(exchange.requestBody.use { String(it.readBytes()) }) + if (request.optString("method") == "notifications/initialized") { + // Chunked, with no end: written until the client goes away. + exchange.sendResponseHeaders(202, 0) + val chunk = ByteArray(8 * 1024) { 'a'.code.toByte() } + runCatching { exchange.responseBody.use { out -> while (true) out.write(chunk) } } + } else { + val bytes = JSONObject().put("jsonrpc", "2.0").put("id", 1) + .put("result", JSONObject()).toString().toByteArray() + exchange.responseHeaders.add("Content-Type", "application/json") + exchange.sendResponseHeaders(200, bytes.size.toLong()) + exchange.responseBody.use { it.write(bytes) } + } + exchange.close() + } + start() + } + try { + val url = "http://127.0.0.1:${server.address.port}/mcp" + val client = McpHttpClient() + + val accepted = client.post( + url, + "", + JSONObject().put("jsonrpc", "2.0").put("method", "notifications/initialized"), + ) + client.post(url, "", JSONObject().put("jsonrpc", "2.0").put("id", 1).put("method", "ping")) + + assertNull(accepted.document) + assertEquals("requests seen", 2, ports.size) + assertNotEquals("the abandoned socket was reused", ports[0], ports[1]) + } finally { + server.stop(0) + } + } + + /** The control for the test above: a 202 with no body leaves its socket for the next request. */ + @Test + fun `a 202 with no body leaves its socket for the next request`() { + val ports = java.util.concurrent.CopyOnWriteArrayList() + val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply { + createContext("/mcp") { exchange -> + ports += exchange.remoteAddress.port + exchange.requestBody.use { it.readBytes() } + exchange.sendResponseHeaders(202, -1) + exchange.close() + } + start() + } + try { + val url = "http://127.0.0.1:${server.address.port}/mcp" + val client = McpHttpClient() + val notification = JSONObject().put("jsonrpc", "2.0").put("method", "notifications/initialized") + + client.post(url, "", notification) + client.post(url, "", notification) + + assertEquals("requests seen", 2, ports.size) + assertEquals("a drained 202 did not leave its socket for reuse", ports[0], ports[1]) + } finally { + server.stop(0) + } + } + /** The drain as [McpHttpClient.post] uses it: the record shows the start and counts the rest. */ @Test fun `a 202 with a large body is recorded capped with the rest counted`() { From 28c1922cabdeee722e5f669a83a97971bb43c426 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Fri, 20 Nov 2026 08:01:10 -0800 Subject: [PATCH 38/90] ADFA-7139 AI-Agent-MCP: a SQLite debugger entry's tools are stored under the lock that checks its endpoint McpToolCatalog.list asked AutomaticServers.recordTools to check the endpoint a listing came from, then wrote the tools to its own map after that lock was released. A listing of the old endpoint could pass its check, a relaunch could replace the endpoint and the new endpoint's listing could record, and the old listing then wrote its stale tools over the new ones. The agent was offered the old process's tools until the next listing. recordTools already stores the list in the entry's State, beside the endpoint, under the same lock as the check. McpToolCatalog.tools now answers an automatic entry from there (AutomaticServers.tools), and the listing no longer writes a second copy. ReplacedEndpointListingTest holds the old listing in the change listener its own record calls, lets the new endpoint list, then releases it. Without the fix: "the replaced endpoint's listing overwrote the new endpoint's tools expected:<[new_tool]> but was:<[old_tool]>". Reported by CodeRabbit in review 5989292051 (McpToolCatalog.kt:123). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- plugins/AI-Agent-MCP/README.md | 5 +- plugins/AI-Agent-MCP/ai-agent-mcp.html | 4 +- .../aiagentmcp/debugger/AutomaticServers.kt | 22 +++- .../aiagentmcp/tools/McpToolCatalog.kt | 11 +- .../debugger/ReplacedEndpointListingTest.kt | 110 ++++++++++++++++++ 5 files changed, 145 insertions(+), 7 deletions(-) create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReplacedEndpointListingTest.kt diff --git a/plugins/AI-Agent-MCP/README.md b/plugins/AI-Agent-MCP/README.md index 54299ae1b..9bc630297 100644 --- a/plugins/AI-Agent-MCP/README.md +++ b/plugins/AI-Agent-MCP/README.md @@ -134,7 +134,10 @@ Two dependencies were deliberately not taken: `McpConnections` (one session per server, shared by every call and listing), `McpCallHandle` (one tool call's cancel: its flag and its own connection) - `tools/` — `McpToolSource` (the `ToolSourceRegistry.ToolSource`), - `McpToolCatalog` (what each server last advertised), `McpToolText` (sanitising) + `McpToolCatalog` (what each server last advertised; a SQLite debugger entry's + list is kept beside its endpoint in `debugger/AutomaticServers`, under the lock + that checks the endpoint, so a listing of a replaced endpoint cannot overwrite + the new one's), `McpToolText` (sanitising) - `settings/` — server CRUD, per-tool toggles, the settings pane - `errors/` — HTTP and JSON-RPC failures reduced to one translated sentence - `security/SecureTokenStore.kt` — this plugin's Keystore alias, over the IDE's `KeystoreSecretStore` diff --git a/plugins/AI-Agent-MCP/ai-agent-mcp.html b/plugins/AI-Agent-MCP/ai-agent-mcp.html index 5ad195893..066c9e781 100644 --- a/plugins/AI-Agent-MCP/ai-agent-mcp.html +++ b/plugins/AI-Agent-MCP/ai-agent-mcp.html @@ -97,7 +97,9 @@

Technical architecture

whether it is against the same server or another. McpToolCatalogWhat each server last advertised, held in memory. The Agent reads its tool list on a UI-adjacent path, so that - list is answered from memory and never blocks on the network. + list is answered from memory and never blocks on the network. A SQLite + debugger entry's list is kept beside its endpoint, so a listing of an + endpoint a relaunch replaced cannot overwrite the new one's. McpSessionOne protocol conversation per server: initialize, tools/list, tools/call, session lifetime, and one clean re-handshake when a server drops a diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt index e40fbc38a..0a4ca85e2 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt @@ -47,6 +47,11 @@ object AutomaticServers { const val ID_PREFIX = "debugger:" + /** + * One entry: its endpoint and the tools that endpoint listed. Kept together, and replaced + * together under this object's lock, so a list can only ever be stored beside the endpoint it + * came from; see [recordTools]. + */ private class State(val endpoint: AutomaticEndpoint, val tools: List = emptyList()) @Volatile private var states: Map = emptyMap() @@ -255,14 +260,25 @@ object AutomaticServers { /** The endpoint now stored for [serverId], or null when it has no entry. */ fun endpoint(serverId: String): AutomaticEndpoint? = states[serverId]?.endpoint + /** + * The tools [serverId] last listed, as [recordTools] stored them; `McpToolCatalog.tools` + * answers an automatic entry from here. + * + * @return them, empty before its first listing or when it has no entry (any more). + */ + fun tools(serverId: String): List = states[serverId]?.tools.orEmpty() + fun urlFor(endpoint: AutomaticEndpoint) = "http://127.0.0.1:${endpoint.port}/mcp" /** - * Remembers what the server listed. + * Remembers what the server listed. The only writer of an automatic entry's tools, which + * [tools] and [servers] both read. * * @param origin the endpoint the list was fetched from. A list from an endpoint that has since - * been replaced belongs to the old process and is dropped; the check and the write share one - * lock, so a refresh cannot slip between them. + * been replaced belongs to the old process and is dropped. The check and the write share one + * lock, so neither a refresh nor the replacement endpoint's own listing can slip between + * them: an old listing that passed its check before a relaunch stores its list beside the old + * endpoint, which the relaunch's read then carries over until the new process lists. * @return false when the list was dropped (no entry any more, or [origin] is out of date). */ fun recordTools(serverId: String, origin: AutomaticEndpoint, tools: List): Boolean { diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt index 0542243f9..8603dbf55 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt @@ -26,9 +26,14 @@ private const val TAG = "$LOG_PREFIX.McpToolCatalog" * The agent reads the tool list on a UI-adjacent path and the contract forbids blocking on the * network there, so the list has to be answered from memory. This is that memory: filled by an * explicit [connect] — on activation, on Connect, after an edit — and read by the source. + * + * A SQLite debugger entry's list is not held here but beside its endpoint in [AutomaticServers], + * which checks the endpoint and stores the list under one lock: a copy here, written after that + * lock was let go, could be overwritten by a listing of an endpoint that has since been replaced. */ object McpToolCatalog { + /** The tools of the user's own servers; an automatic entry's are in [AutomaticServers]. */ private val toolsByServer = ConcurrentHashMap>() /** Re-reads an automatic entry's endpoint and tries once more when the stored one is stale. */ @@ -43,7 +48,9 @@ object McpToolCatalog { * @param serverId the server. * @return its tools, empty before the first successful connection. */ - fun tools(serverId: String): List = toolsByServer[serverId].orEmpty() + fun tools(serverId: String): List = + if (AutomaticServers.isAutomatic(serverId)) AutomaticServers.tools(serverId) + else toolsByServer[serverId].orEmpty() /** * What one handshake-and-list answered. @@ -123,13 +130,13 @@ object McpToolCatalog { } } if (server.automatic) { + // Stored by recordTools alone, beside the endpoint it checks, under the same lock. val current = origin != null && AutomaticServers.urlFor(origin) == server.url && AutomaticServers.recordTools(server.id, origin, tools) if (!current) { Log.i(TAG, "Dropping a tool list from an endpoint '${server.name}' has since left") return Listing(session.serverName, tools) } - toolsByServer[server.id] = tools } else { toolsByServer[server.id] = tools McpServerStore.setKnownTools(server.id, tools.map { it.name }) diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReplacedEndpointListingTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReplacedEndpointListingTest.kt new file mode 100644 index 000000000..78195a7a9 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReplacedEndpointListingTest.kt @@ -0,0 +1,110 @@ +package com.itsaky.androidide.plugins.aiagentmcp.debugger + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpToolCatalog +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicReference +import kotlin.concurrent.thread +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * Two listings of one SQLite debugger entry can overlap: the probe's, of the endpoint it read, and + * the relisting a relaunch starts, of the endpoint that replaced it. Whichever records last, the + * tools the agent is offered are the ones the current endpoint listed. + */ +class ReplacedEndpointListingTest { + + private val app = "com.example.app" + private val servers = mutableListOf() + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + // The Keystore is not there on the JVM; nothing here reads a hand-added server's secrets. + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } returns KeystoreSecretStore.Stored.Absent + every { McpServerStore.headers(any()) } returns emptyMap() + } + + @After + fun tearDown() { + AutomaticServers.install(null) + McpConnections.closeAll() + McpToolCatalog.clear() + servers.forEach { it.stop() } + plugin.dispose() + unmockkObject(McpServerStore) + } + + private fun fake(token: String, toolName: String) = + FakeMcpServer(token, listOf(tool(toolName, true))).also { servers += it } + + /** + * The old endpoint's listing passes its endpoint check and is held there, by the change + * listener its own record calls, until the new endpoint has listed and recorded. + */ + @Test + fun `a replaced endpoint's listing that finishes last leaves the new endpoint's tools`() { + val first = fake("t1", "old_tool") + val second = fake("t2", "new_tool") + val stored = AtomicReference(listOf(AutomaticEndpoint(app, first.port, "t1"))) + AutomaticServers.install { stored.get() } + val id = AutomaticServers.idFor(app) + val oldEntry = AutomaticServers.servers().single() + + val olderThread = AtomicReference() + val olderRecorded = CountDownLatch(1) + val releaseOlder = CountDownLatch(1) + val holdOlder: () -> Unit = { + if (Thread.currentThread() === olderThread.get() && olderRecorded.count > 0) { + olderRecorded.countDown() + releaseOlder.await(10, TimeUnit.SECONDS) + } + } + AutomaticServers.addChangeListener(holdOlder) + try { + val older = thread(start = false) { McpToolCatalog.connect(oldEntry) } + olderThread.set(older) + older.start() + assertTrue("the old endpoint's listing never recorded", olderRecorded.await(10, TimeUnit.SECONDS)) + + stored.set(listOf(AutomaticEndpoint(app, second.port, "t2"))) + assertTrue(AutomaticServers.refresh()) + McpToolCatalog.connect(AutomaticServers.servers().single()) + + releaseOlder.countDown() + older.join(10_000) + assertFalse("the old endpoint's listing never finished", older.isAlive) + + assertEquals( + "the replaced endpoint's listing overwrote the new endpoint's tools", + listOf("new_tool"), + McpToolCatalog.tools(id).map { it.name }, + ) + assertEquals(listOf("new_tool"), AutomaticServers.servers().single().knownTools) + } finally { + releaseOlder.countDown() + AutomaticServers.removeChangeListener(holdOlder) + } + } +} From 5e877ba3ac320954d7afd8569369715cb8f768b6 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Fri, 20 Nov 2026 08:03:32 -0800 Subject: [PATCH 39/90] ADFA-7139 AI-Agent-MCP: a SQLite debugger entry that went away is cleaned up in the step that removes it AutomaticServers.refresh removed an entry under its lock, then called McpToolCatalog.forget(id) and McpConnections.invalidate(id) after the lock was released. Both work by ID. A newer read could restore the app at a new endpoint in between, and the relisting connect to it; the older read then forgot the new entry's health and closed its session. The health and the session of an entry that went away are now taken out under the lock, in the same step that removes the entry, by McpConnections.detach and McpServerHealth.detach. A read that restores the app has to store after that step, so what it creates cannot be taken. Only the detached sessions are closed, after the lock is released, since closing sends a DELETE; the health listeners are told then too. The tools already go with the entry's State (previous commit). The ticket that decides which read may store is the one generation check; nothing new is added beside it. McpConnections takes its own lock inside AutomaticServers', and never calls into AutomaticServers under it, so the order cannot deadlock. RemovedEntryCleanupTest removes two apps in one read, holds that read in the health listener its first forgotten entry tells, restores the second app at a new endpoint and connects it, then releases the read. Without the fix: "the removal forgot the new endpoint's health expected: but was:". Reported by CodeRabbit in review 5984152741 (AutomaticServers.kt:225-226). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- plugins/AI-Agent-MCP/README.md | 5 +- .../aiagentmcp/client/McpConnections.kt | 15 +- .../aiagentmcp/debugger/AutomaticServers.kt | 39 ++++-- .../aiagentmcp/tools/McpServerHealth.kt | 14 +- .../aiagentmcp/tools/McpToolCatalog.kt | 6 +- .../debugger/RemovedEntryCleanupTest.kt | 132 ++++++++++++++++++ 6 files changed, 194 insertions(+), 17 deletions(-) create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/RemovedEntryCleanupTest.kt diff --git a/plugins/AI-Agent-MCP/README.md b/plugins/AI-Agent-MCP/README.md index 9bc630297..0a5ed0d58 100644 --- a/plugins/AI-Agent-MCP/README.md +++ b/plugins/AI-Agent-MCP/README.md @@ -58,7 +58,10 @@ debug app reports; the plugin reads them through the `DebuggerEndpointService` (permission `debugger.endpoints`, so it needs Code on the Go 26.48 or later) and points the entry at `http://127.0.0.1:/mcp`. A relaunched app gets a new port and token, and the plugin reads them again after a refused connection. An -app that has not reported yet has no entry, and no error is shown. +app that has not reported yet has no entry, and no error is shown. An app that +stops reporting loses its entry, and the entry's tools, health and session go +with it in the same step; if the app comes back before that step has finished +its cleanup, the new entry keeps its own. When the entry cannot reach its app, the reason the Agent tab shows says what to do, told apart by exception type (`SocketTimeoutException` or `ConnectException`, diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt index e1289e8ce..76c7c4044 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt @@ -73,9 +73,22 @@ object McpConnections { /** Drops the session for [serverId], ending it server-side when it had one. */ fun invalidate(serverId: String) { - sessions.remove(serverId)?.second?.let { runCatchingRecoverable { it.close() } } + detach(serverId)?.let { runCatchingRecoverable { it.close() } } } + /** + * Takes the session for [serverId] out without ending it, for a caller that must take it out + * under a lock of its own and end it once that lock is let go, since `close()` sends a DELETE. + * `AutomaticServers` does, for an entry that went away, in the same step that removes it. + * + * Taken under this object's lock, as [session] replaces a session under it. Safe to call under + * another lock: nothing here calls out while holding this one, [session] reading the + * credentials before it takes it. + * + * @return the session taken out, or null when [serverId] had none. + */ + fun detach(serverId: String): McpSession? = synchronized(this) { sessions.remove(serverId)?.second } + /** Ends every session, for the plugin shutting down. */ fun closeAll() { sessions.values.forEach { (_, session) -> runCatchingRecoverable { session.close() } } diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt index 0a4ca85e2..162b4df29 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt @@ -2,13 +2,13 @@ package com.itsaky.androidide.plugins.aiagentmcp.debugger import android.util.Log import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.client.McpSession import com.itsaky.androidide.plugins.aiagentmcp.client.McpTool import com.itsaky.androidide.plugins.aiagentmcp.errors.runCatchingRecoverable import com.itsaky.androidide.plugins.aiagentmcp.logging.LOG_PREFIX import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServer import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore import com.itsaky.androidide.plugins.aiagentmcp.tools.McpServerHealth -import com.itsaky.androidide.plugins.aiagentmcp.tools.McpToolCatalog import com.itsaky.androidide.plugins.services.DebuggerEndpoint import java.util.concurrent.CopyOnWriteArrayList import kotlin.coroutines.cancellation.CancellationException @@ -161,14 +161,22 @@ object AutomaticServers { * overlap, and the read that started first may finish last with the endpoint the other has * already replaced. * + * An entry that went away loses its tools with its entry, and its health and session are taken + * out in the same step, under this object's lock: by ID they would also be the resources of an + * entry a later read restores, so cleaning up after the lock was let go could take the health + * and session of the app's new endpoint. Only the session taken out is closed, after the lock + * is let go, since closing it sends a DELETE; the health listeners are told then too. + * * A read that fails with an Exception or a LinkageError leaves the entries as they were; any * other Error, an OutOfMemoryError above all, propagates to the caller. So does one from a - * change or endpoint listener, or from closing the session of an entry that went away. Such an - * Error comes after the new entries are stored, so it skips what was still to run for this - * read: the remaining endpoint listeners, the reset of a refused credential for the remaining - * moved entries, and the change listeners. No later read repeats them, since it finds those - * entries unchanged. That is accepted rather than guarded against: the Error is the process - * failing, and the IDE's uncaught-exception handler, which it is on its way to, ends it. + * change, health or endpoint listener, or from closing the session of an entry that went away. + * Such an Error comes after the new entries are stored, and the resources of the entries that + * went away are taken out with them, so it skips only what was still to run for this read: + * closing the remaining sessions taken out, telling the health listeners, the remaining + * endpoint listeners, the reset of a refused credential for the remaining moved entries, and + * the change listeners. No later read repeats them, since it finds those entries unchanged. + * That is accepted rather than guarded against: the Error is the process failing, and the + * IDE's uncaught-exception handler, which it is on its way to, ends it. * * @param keepGoing checked after the read, before anything is stored. * @return true when the set of entries, a port or a token changed. @@ -206,7 +214,8 @@ object AutomaticServers { return false } val moved = mutableListOf() - val removed: List + val detached = mutableListOf() + var healthForgotten = false val changed = synchronized(this) { if (source !== read || !keepGoing() || ticket < storedRead) return false storedRead = ticket @@ -223,13 +232,17 @@ object AutomaticServers { } } states = next - removed = (old.keys - next.keys).toList() + // Here, not after the lock: a read that restores the app has to come after this one, + // so the health and session taken out are this entry's, never its successor's. + // McpConnections takes its own lock inside this one and never calls in here under it. + for (id in old.keys - next.keys) { + McpConnections.detach(id)?.let { detached += it } + if (McpServerHealth.detach(id)) healthForgotten = true + } old.mapValues { it.value.endpoint } != next.mapValues { it.value.endpoint } } - for (id in removed) { - McpToolCatalog.forget(id) - McpConnections.invalidate(id) - } + for (session in detached) runCatchingRecoverable { session.close() } + if (healthForgotten) McpServerHealth.notifyChanged() for (id in moved) { // A refused credential is not final for this entry: the new one has not been tried. McpServerHealth.credentialChanged(id) diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpServerHealth.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpServerHealth.kt index bf487a067..c6538239d 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpServerHealth.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpServerHealth.kt @@ -69,9 +69,21 @@ object McpServerHealth { /** Forgets a server that was removed. */ fun forget(serverId: String) { - if (byServer.remove(serverId) != null) fireChanged() + if (detach(serverId)) fireChanged() } + /** + * As [forget], without telling the listeners: for a caller that forgets a server under a lock + * of its own, which a listener calling the host must not run under. That caller calls + * [notifyChanged] once it has let go, when this returned true. + * + * @return whether anything was known of [serverId]. + */ + internal fun detach(serverId: String): Boolean = byServer.remove(serverId) != null + + /** Tells the listeners of a change [detach] made. */ + internal fun notifyChanged() = fireChanged() + /** Forgets everything, for the plugin shutting down. */ fun clear() { if (byServer.isEmpty()) return diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt index 8603dbf55..d370ab6f6 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt @@ -187,7 +187,11 @@ object McpToolCatalog { return refreshed } - /** Forgets a server's tools and health, for one that was removed. */ + /** + * Forgets a server's tools and health, for one of the user's own that was removed. A SQLite + * debugger entry that went away is cleaned up by `AutomaticServers.refresh` itself, under its + * lock, so the entry that replaces it under the same ID keeps its own. + */ fun forget(serverId: String) { toolsByServer.remove(serverId) McpServerHealth.forget(serverId) diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/RemovedEntryCleanupTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/RemovedEntryCleanupTest.kt new file mode 100644 index 000000000..a532cda8d --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/RemovedEntryCleanupTest.kt @@ -0,0 +1,132 @@ +package com.itsaky.androidide.plugins.aiagentmcp.debugger + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpServerHealth +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpToolCatalog +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicReference +import kotlin.concurrent.thread +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * A read that finds an app gone forgets that entry's health and ends its session. A later read can + * restore the app, at a new endpoint, before the first read has finished; what the first read + * forgets is the entry it removed, never the one that replaced it under the same id. + */ +class RemovedEntryCleanupTest { + + private val servers = mutableListOf() + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + // The Keystore is not there on the JVM; nothing here reads a hand-added server's secrets. + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } returns KeystoreSecretStore.Stored.Absent + every { McpServerStore.headers(any()) } returns emptyMap() + } + + @After + fun tearDown() { + AutomaticServers.install(null) + McpConnections.closeAll() + McpToolCatalog.clear() + servers.forEach { it.stop() } + plugin.dispose() + unmockkObject(McpServerStore) + } + + private fun fake(token: String, toolName: String) = + FakeMcpServer(token, listOf(tool(toolName, true))).also { servers += it } + + /** + * Two apps go away in one read. That read is held by the health listener its first forgotten + * entry tells, so the second app's cleanup is still to come, while a newer read restores the + * second app at a new endpoint and the relisting connects to it. + */ + @Test + fun `a removal that finishes after the app came back leaves the new endpoint's health and session`() { + val appA = "com.example.a" + val appB = "com.example.b" + val a = fake("ta", "a_tool") + val b1 = fake("tb1", "b_tool") + val b2 = fake("tb2", "b_tool") + val stored = AtomicReference( + listOf(AutomaticEndpoint(appA, a.port, "ta"), AutomaticEndpoint(appB, b1.port, "tb1")) + ) + AutomaticServers.install { stored.get() } + AutomaticServers.servers().forEach { McpToolCatalog.connect(it) } + val idB = AutomaticServers.idFor(appB) + assertEquals(McpServerHealth.State.AVAILABLE, McpServerHealth.of(idB)?.state) + + val removingThread = AtomicReference() + val removalHeld = CountDownLatch(1) + val releaseRemoval = CountDownLatch(1) + val holdRemoval: () -> Unit = { + if (Thread.currentThread() === removingThread.get() && removalHeld.count > 0) { + removalHeld.countDown() + releaseRemoval.await(10, TimeUnit.SECONDS) + } + } + McpServerHealth.addChangeListener(holdRemoval) + try { + stored.set(emptyList()) + val removal = thread(start = false) { AutomaticServers.refresh() } + removingThread.set(removal) + removal.start() + assertTrue("the removal never forgot anything", removalHeld.await(10, TimeUnit.SECONDS)) + assertNull("the removal stored nothing", AutomaticServers.endpoint(idB)) + + stored.set(listOf(AutomaticEndpoint(appB, b2.port, "tb2"))) + assertTrue(AutomaticServers.refresh()) + val restored = AutomaticServers.servers().single() + McpToolCatalog.connect(restored) + val session = McpConnections.session(restored) + + releaseRemoval.countDown() + removal.join(10_000) + assertFalse("the removal never finished", removal.isAlive) + + assertEquals( + "the removal forgot the new endpoint's tools", + listOf("b_tool"), + McpToolCatalog.tools(idB).map { it.name }, + ) + assertEquals( + "the removal forgot the new endpoint's health", + McpServerHealth.State.AVAILABLE, + McpServerHealth.of(idB)?.state, + ) + assertSame( + "the removal ended the new endpoint's session", + session, + McpConnections.session(restored), + ) + } finally { + releaseRemoval.countDown() + McpServerHealth.removeChangeListener(holdRemoval) + } + } +} From 3c308f96a557b6ac11b47ac2f3e7def247b5b8a8 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Fri, 20 Nov 2026 08:08:36 -0800 Subject: [PATCH 40/90] ADFA-7139 AI-Agent-MCP: a 202 body cut inside a credential shows no part of it in the connection log drain keeps the first DRAINED_CHARS_KEPT characters of a 202 body, and McpExchangeTrace.received scrubbed what was kept. McpRedactor.scrub masks whole credentials only, so when the cut fell inside one, its start stayed in the kept text. Every whole copy before it shrank to the 8-character mask, so that start fell under the log's own cap and was shown. McpRedactor.scrubCut, used by received when anything was dropped, masks the end of a cut text from where a credential it may end partway through starts, in any form scrub matches (plain, \uXXXX, backslash or %XX escaped): the first index from which a secret's pattern reads on to the end unfinished (Matcher.hitEnd), moved back over any whole match that runs past it. The text then ends in the mask. Only the last 6 x (longest secret) characters are examined, and nothing is copied but the result, so memory and time stay bounded. McpHttpClientDrainTest posts to a server whose 202 body is the token repeated, the cut falling inside a copy. Without the fix: "the record kept part of the credential: 'tok_9f2c' expected:<[]> but was:<[tok_9f2c]>". McpRedactorTest covers scrubCut: a plain and an escaped credential cut short, one cut short inside a whole copy of another, and a cut that ends in no credential. Reported by CodeRabbit in review 5984152741 (McpHttpClient.kt:81). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- plugins/AI-Agent-MCP/README.md | 5 ++ .../aiagentmcp/transport/McpExchangeTrace.kt | 6 +- .../aiagentmcp/transport/McpHttpClient.kt | 9 ++- .../aiagentmcp/transport/McpRedactor.kt | 58 ++++++++++++++++++- .../transport/McpHttpClientDrainTest.kt | 38 ++++++++++++ .../aiagentmcp/transport/McpRedactorTest.kt | 32 ++++++++++ 6 files changed, 143 insertions(+), 5 deletions(-) diff --git a/plugins/AI-Agent-MCP/README.md b/plugins/AI-Agent-MCP/README.md index 0a5ed0d58..25165f861 100644 --- a/plugins/AI-Agent-MCP/README.md +++ b/plugins/AI-Agent-MCP/README.md @@ -182,3 +182,8 @@ Two dependencies were deliberately not taken: resolves to the same origin, so the bearer token and the user's own headers cannot be replayed to another host in one hop. - Error bodies stay in logcat. The transcript gets one sentence. +- The connection log masks every credential the request carried wherever the + server echoes it, escaped or not (`McpRedactor`). The body of a `202 Accepted` + is kept only in part, cut at a fixed length; when the cut falls inside a + credential, what was kept of it is masked too, so the log never shows the + start of one. diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpExchangeTrace.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpExchangeTrace.kt index 4bde49d47..7c6c46b7f 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpExchangeTrace.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpExchangeTrace.kt @@ -42,9 +42,13 @@ internal class McpExchangeTrace( /** * As [received], for a body kept only in part: [dropped] more characters came after [body] * and were read and thrown away; the record counts them with what its own cap leaves out. + * + * When anything was dropped, [body] was cut at a fixed length and may end partway through a + * credential, which [McpRedactor.scrub] would leave showing; [McpRedactor.scrubCut] masks it. */ fun received(body: String, dropped: Long) { - val kept = McpExchange.Body.capped(redactor.scrub(body)) + val scrubbed = if (dropped > 0) redactor.scrubCut(body) else redactor.scrub(body) + val kept = McpExchange.Body.capped(scrubbed) responseBody = kept.copy(omitted = (kept.omitted + dropped).coerceAtMost(Int.MAX_VALUE.toLong()).toInt()) } diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt index b2bb79cd5..850d1ef67 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt @@ -51,9 +51,11 @@ open class McpHttpClient( /** * Characters of a drained body kept for the connection log: twice what the log shows, so - * a credential the redactor has to find is whole even where the log's own cut falls. + * a credential the redactor has to find is whole even where the log's own cut falls. The + * drain's own cut, at this length, can fall inside one; the trace masks what was kept of + * it with [McpRedactor.scrubCut], so the log never shows the start of a credential. */ - private const val DRAINED_CHARS_KEPT = 2 * McpExchange.Body.MAX_CHARS + internal const val DRAINED_CHARS_KEPT = 2 * McpExchange.Body.MAX_CHARS /** * Characters of a 202 body read and thrown away, past the ones kept, before the drain gives @@ -80,6 +82,9 @@ open class McpHttpClient( * Only a 202 is bounded this way. A JSON reply and an error body are read whole, with * `readText()`: each is the document the caller needs. * + * What is kept is cut at [keep] characters wherever that falls, inside a credential the + * server echoed too; [McpExchangeTrace.received] masks the end of a cut body for that. + * * @param keep how many characters to keep. * @param budget how many characters past [keep] may be read and dropped before the body is * abandoned. diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpRedactor.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpRedactor.kt index 89d9d352a..a280cf6bf 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpRedactor.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpRedactor.kt @@ -38,6 +38,9 @@ class McpRedactor( /** Characters JSON may escape with a backslash alone. */ private const val JSON_BACKSLASHED = "\"\\/" + /** The longest form [encodedForms] matches one character in: `\uXXXX`. */ + private const val LONGEST_CHAR_FORM = 6 + /** * A redactor for one request to [url], which also masks what the URL itself carries. * @param credentials the token, session and the user's header values, as sent. @@ -58,14 +61,19 @@ class McpRedactor( } } - /** Longest first, so no secret is left half-masked by a shorter one inside it. */ - private val secrets: List = credentials + /** The secrets as given, longest first, so none is left half-masked by a shorter one inside it. */ + private val plainSecrets: List = credentials .flatMap { listOfNotNull(it, SCHEMED.matchEntire(it)?.groupValues?.get(2)) } .filter { it.isNotEmpty() } .distinct() .sortedByDescending { it.length } + + private val secrets: List = plainSecrets .map { if (it.length >= MIN_SUBSTRING_LENGTH) Regex(encodedForms(it)) else wholeToken(it) } + /** How many characters one secret can take up in a text at most, in its longest escaped form. */ + private val longestForm: Int = (plainSecrets.firstOrNull()?.length ?: 0) * LONGEST_CHAR_FORM + /** * A header this client sent, its value hidden when it is a credential. * @return the header as it may be shown. @@ -89,6 +97,52 @@ class McpRedactor( */ fun scrub(text: String): String = secrets.fold(text) { acc, secret -> acc.replace(secret, MASK) } + /** + * As [scrub], for a text that is the start of something longer, cut at a fixed length without + * regard to what it cut through. [scrub] masks whole credentials only, so one the cut fell + * inside would show its start. Here the end is masked from where such a credential starts, + * in any form [scrub] matches, escaped or not, so the text ends in [MASK] rather than in part + * of one. That start is the first character from which a credential reads on to the cut + * unfinished, moved back over any whole credential that runs past it, so no part of one is + * left before the mask either. + * + * Only the last characters, as many as a credential can take up, are examined, and nothing is + * copied but the result, so the cost is bounded whatever the length of [text]. + * + * @param text the first characters of a body, the rest of which was not kept. + * @return the text, safe to show. + */ + fun scrubCut(text: String): String { + val start = credentialAtEnd(text) + return if (start == text.length) scrub(text) else scrub(text.substring(0, start)) + MASK + } + + /** + * Where the credential that [text] may end partway through starts; see [scrubCut]. + * @return its index, or the length of [text] when its end is not part of one. + */ + private fun credentialAtEnd(text: String): Int { + // Transparent bounds, so a short secret's "not inside a word" check sees what precedes. + val matchers = secrets.map { it.toPattern().matcher(text).useTransparentBounds(true) } + var start = text.length + while (true) { + val from = (start - longestForm).coerceAtLeast(0) + val earlier = (from until start).firstOrNull { index -> + matchers.any { it.reachesPast(index, start, text.length) } + } ?: return start + start = earlier + } + } + + /** + * Whether a credential read from [index] runs past [mark]: a whole match that ends after it, or + * one the end of the text cut short, which is what `hitEnd` reports when nothing matched. + */ + private fun java.util.regex.Matcher.reachesPast(index: Int, mark: Int, length: Int): Boolean { + region(index, length) + return if (lookingAt()) end() > mark else hitEnd() + } + /** * A URL as it may be shown: its userinfo and every query value masked, then scrubbed. * A secret carried in a path segment cannot be told apart from the path, so it stays. diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClientDrainTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClientDrainTest.kt index 7464c3ae7..d77e3fdd5 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClientDrainTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClientDrainTest.kt @@ -194,4 +194,42 @@ class McpHttpClientDrainTest { server.stop(0) } } + + /** + * The drain keeps the start of a 202 body and the record masks credentials in what was kept, + * so the cut can fall inside one: the redactor masks whole credentials only, and a copy of the + * token cut in two would show its start. A body of nothing but the token, repeated, with the + * cut inside a copy: the record shows masks and nothing else. + */ + @Test + fun `a 202 body cut inside a repeated credential shows no part of it`() { + val token = "tok_9f2c7e1a4b8d3f6e0a5c9b2d7e4f1a3c5b7d" + val kept = McpHttpClient.DRAINED_CHARS_KEPT + assertTrue("the cut must fall inside a copy of the token", kept % token.length != 0) + val bytes = token.repeat(kept / token.length + 10).toByteArray() + val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply { + createContext("/mcp") { exchange -> + exchange.requestBody.use { it.readBytes() } + exchange.sendResponseHeaders(202, bytes.size.toLong()) + exchange.responseBody.use { it.write(bytes) } + } + start() + } + try { + var recorded: McpExchange? = null + McpHttpClient().post( + "http://127.0.0.1:${server.address.port}/mcp", + token, + JSONObject().put("jsonrpc", "2.0").put("method", "notifications/initialized"), + exchangeListener = { exchange, _ -> recorded = exchange }, + ) + + val text = requireNotNull(recorded?.responseBody).text + val unmasked = text.replace(McpRedactor.MASK, "") + assertEquals("the record kept part of the credential: '$unmasked'", "", unmasked) + assertTrue("the record ends unmasked: '${text.takeLast(16)}'", text.endsWith(McpRedactor.MASK)) + } finally { + server.stop(0) + } + } } diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpRedactorTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpRedactorTest.kt index 19ff65a2b..2f0fbae73 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpRedactorTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpRedactorTest.kt @@ -127,4 +127,36 @@ class McpRedactorTest { assertEquals("https://mcp.example.test/mcp?t=${McpRedactor.MASK} redirected off its origin", message) } + + @Test + fun givenATextCutInsideACredential_whenScrubbedAsCut_thenItEndsInAMask() { + val mask = McpRedactor.MASK + + val shown = redactor("secret-token-123456").scrubCut("ok secret-token-123456 then secret-to") + + assertEquals("ok $mask then $mask", shown) + } + + @Test + fun givenATextCutInsideAnEscapedCredential_whenScrubbedAsCut_thenItEndsInAMask() { + // The cut falls inside the `\u006b` that escapes the token's `k`. + val shown = redactor("secret-token").scrubCut("""{"error":"bad secret-to\u006""") + + assertEquals("""{"error":"bad ${McpRedactor.MASK}""", shown) + } + + @Test + fun givenACutInsideACredentialThatStartsInsideAnother_whenScrubbedAsCut_thenNeitherShows() { + // The second credential's start, cut short, begins inside a whole copy of the first. + val shown = redactor("header-value-123456", "123456-token-abcdef").scrubCut("ok header-value-123456-tok") + + assertEquals("ok ${McpRedactor.MASK}", shown) + } + + @Test + fun givenACutThatEndsInNoCredential_whenScrubbedAsCut_thenOnlyWholeOnesAreMasked() { + val shown = redactor("secret-token").scrubCut("secret-token, and the rest") + + assertEquals("${McpRedactor.MASK}, and the rest", shown) + } } From bd34cd9049cdc163ce9305ccf8e92562f6d9ae4e Mon Sep 17 00:00:00 2001 From: David Schachter Date: Fri, 20 Nov 2026 11:57:53 -0800 Subject: [PATCH 41/90] ADFA-7139 AI-Agent-MCP: reading a 202 body has an overall deadline, not only a byte budget A server sending a byte just under every read timeout never tripped the timeout and would have held initialize (synchronized) for years. The drain now checks an injectable clock between reads and fails like the budget does, so the socket is disconnected. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- plugins/AI-Agent-MCP/README.md | 4 + .../aiagentmcp/transport/McpHttpClient.kt | 33 ++++++-- .../transport/McpHttpClientDrainTest.kt | 81 +++++++++++++++++++ 3 files changed, 113 insertions(+), 5 deletions(-) diff --git a/plugins/AI-Agent-MCP/README.md b/plugins/AI-Agent-MCP/README.md index 25165f861..d7ac14cb3 100644 --- a/plugins/AI-Agent-MCP/README.md +++ b/plugins/AI-Agent-MCP/README.md @@ -187,3 +187,7 @@ Two dependencies were deliberately not taken: is kept only in part, cut at a fixed length; when the cut falls inside a credential, what was kept of it is masked too, so the log never shows the start of one. +- A `202 Accepted` body is read and thrown away, for at most 1 MiB of characters + and 10 seconds; one that runs past either is abandoned and its socket + disconnected, not reused. The worst case is the 10 seconds plus one read + timeout, since a read already blocked ends only at its own timeout. diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt index 850d1ef67..e9c77f05f 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt @@ -26,10 +26,12 @@ private const val TAG = "$LOG_PREFIX.McpHttpClient" * * @param connectTimeoutMs how long to wait for the connection itself. * @param readTimeoutMs how long a call may take to answer. + * @param drainDeadlineMs how long reading a 202 body may take in all; see [drain]. */ open class McpHttpClient( private val connectTimeoutMs: Int = CONNECT_TIMEOUT_MS, private val readTimeoutMs: Int = READ_TIMEOUT_MS, + private val drainDeadlineMs: Long = DRAIN_DEADLINE_MS, ) { companion object { @@ -64,6 +66,13 @@ open class McpHttpClient( */ internal const val DRAIN_BUDGET_CHARS = 1L shl 20 + /** + * How long the drain of a 202 body may take in all, whatever the read timeout: far longer + * than a server needs to send a body it should not have sent, short enough that one which + * dribbles it cannot hold `initialize` for long. + */ + internal const val DRAIN_DEADLINE_MS = 10_000L + /** * Reads a body to its end through a fixed buffer, keeping only its first [keep] characters. * @@ -76,8 +85,11 @@ open class McpHttpClient( * The caller survives either by not reusing the socket; any other Error, an OutOfMemoryError * above all, propagates. * - * The budget bounds how much is read, not how long it takes: a server that trickles a body - * slower than the read timeout can still hold the read until it has sent [budget]. + * The budget bounds how much is read; [deadlineMs] bounds how long it takes. The clock is + * checked between reads, so a server that sends a byte just under every read timeout, which + * never trips that timeout, is abandoned at the deadline like one past the budget. The worst + * case is [deadlineMs] plus one read timeout: a read already blocked when the deadline + * passes ends only at its own timeout. * * Only a 202 is bounded this way. A JSON reply and an error body are read whole, with * `readText()`: each is the document the caller needs. @@ -88,16 +100,22 @@ open class McpHttpClient( * @param keep how many characters to keep. * @param budget how many characters past [keep] may be read and dropped before the body is * abandoned. + * @param deadlineMs how long the whole drain may take before the body is abandoned. + * @param nowMs the clock, in milliseconds from any fixed point; injectable so a test needs + * no real waiting. * @param open opens the body; called inside the guard, since opening it can fail too. * @return what was kept and how much was dropped, or the failure: a recoverable read - * failure, or a [DrainBudgetException] for a body that ran past [budget]. + * failure, or a [DrainBudgetException] for a body that ran past [budget] or [deadlineMs]. */ internal fun drain( keep: Int = DRAINED_CHARS_KEPT, budget: Long = DRAIN_BUDGET_CHARS, + deadlineMs: Long = DRAIN_DEADLINE_MS, + nowMs: () -> Long = { System.nanoTime() / 1_000_000 }, open: () -> InputStream, ): Result = runCatchingRecoverable { + val started = nowMs() open().reader(Charsets.UTF_8).use { reader -> val kept = StringBuilder() val buffer = CharArray(8 * 1024) @@ -113,6 +131,11 @@ open class McpHttpClient( "A 202 body ran past ${kept.length + budget} characters; abandoned it" ) } + if (nowMs() - started > deadlineMs) { + throw DrainBudgetException( + "A 202 body took more than $deadlineMs ms to read; abandoned it" + ) + } } Drained(kept.toString(), dropped) } @@ -126,7 +149,7 @@ open class McpHttpClient( */ internal class Drained(val text: String, val dropped: Long) - /** A 202 body that ran past [DRAIN_BUDGET_CHARS]; its socket is disconnected, not reused. */ + /** A 202 body that ran past [DRAIN_BUDGET_CHARS] or [DRAIN_DEADLINE_MS]; its socket is disconnected, not reused. */ internal class DrainBudgetException(message: String) : IOException(message) /** @@ -197,7 +220,7 @@ open class McpHttpClient( // than ignored, since a body left unread keeps the socket out of the pool. if (conn.responseCode == HttpURLConnection.HTTP_ACCEPTED) { // A half-read body is neither pooled nor closed, so only a whole drain counts. - val drained = drain { conn.inputStream } + val drained = drain(deadlineMs = drainDeadlineMs) { conn.inputStream } drained.getOrNull()?.let { trace.received(it.text, it.dropped) } drained.exceptionOrNull()?.let { e -> Log.w(TAG, "Not reusing the connection after its 202 body: ${e.message}") diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClientDrainTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClientDrainTest.kt index d77e3fdd5..f21bb344e 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClientDrainTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClientDrainTest.kt @@ -72,6 +72,32 @@ class McpHttpClientDrainTest { assertTrue("the body was not closed", body.closed) } + @Test + fun `a body that outlasts the deadline is abandoned though it is far inside the budget`() { + var now = 0L + val body = object : InputStream() { + var reads = 0 + var closed = false + override fun read(): Int = 'a'.code.also { now += 4_000; reads++ } + override fun read(b: ByteArray, off: Int, len: Int): Int { + b[off] = read().toByte() + return 1 + } + override fun close() { + closed = true + } + } + + val drained = McpHttpClient.drain(deadlineMs = 10_000, nowMs = { now }) { body } + + assertTrue( + "a trickling body was not abandoned at the deadline: ${drained.exceptionOrNull()}", + drained.exceptionOrNull() is McpHttpClient.DrainBudgetException, + ) + assertEquals("reads before the deadline passed", 3, body.reads) + assertTrue("the body was not closed", body.closed) + } + @Test fun `an OutOfMemoryError while draining reaches the caller`() { val body = object : InputStream() { @@ -137,6 +163,61 @@ class McpHttpClientDrainTest { } } + /** + * A 202 whose body trickles a byte at a time, never tripping a read timeout: the POST returns + * at the drain's deadline and the next request arrives on a new connection. + */ + @Test(timeout = 30_000) + fun `a 202 body that trickles returns at the deadline and its socket is not reused`() { + val ports = java.util.concurrent.CopyOnWriteArrayList() + val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply { + createContext("/mcp") { exchange -> + ports += exchange.remoteAddress.port + val request = JSONObject(exchange.requestBody.use { String(it.readBytes()) }) + if (request.optString("method") == "notifications/initialized") { + exchange.sendResponseHeaders(202, 0) + runCatching { + exchange.responseBody.use { out -> + while (true) { + out.write('a'.code) + out.flush() + Thread.sleep(20) + } + } + } + } else { + val bytes = JSONObject().put("jsonrpc", "2.0").put("id", 1) + .put("result", JSONObject()).toString().toByteArray() + exchange.responseHeaders.add("Content-Type", "application/json") + exchange.sendResponseHeaders(200, bytes.size.toLong()) + exchange.responseBody.use { it.write(bytes) } + } + exchange.close() + } + start() + } + try { + val url = "http://127.0.0.1:${server.address.port}/mcp" + val client = McpHttpClient(drainDeadlineMs = 300) + + val started = System.nanoTime() + val accepted = client.post( + url, + "", + JSONObject().put("jsonrpc", "2.0").put("method", "notifications/initialized"), + ) + val tookMs = (System.nanoTime() - started) / 1_000_000 + client.post(url, "", JSONObject().put("jsonrpc", "2.0").put("id", 1).put("method", "ping")) + + assertNull(accepted.document) + assertTrue("the drain took $tookMs ms against a 300 ms deadline", tookMs < 5_000) + assertEquals("requests seen", 2, ports.size) + assertNotEquals("the abandoned socket was reused", ports[0], ports[1]) + } finally { + server.stop(0) + } + } + /** The control for the test above: a 202 with no body leaves its socket for the next request. */ @Test fun `a 202 with no body leaves its socket for the next request`() { From 08e9e677efacfafea78440bee2b6738b6fbaf730 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Fri, 20 Nov 2026 12:01:55 -0800 Subject: [PATCH 42/90] ADFA-7139 AI-Agent-MCP: three bare runCatching calls no longer swallow an OutOfMemoryError McpRedactor (URL decode), McpLogFormat (JSON indenting) and McpTranscriptDialog (clipboard copy) now use runCatchingRecoverable, keeping their fallbacks; a VirtualMachineError propagates. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../plugins/aiagentmcp/errors/McpLogFormat.kt | 21 ++++++++++++------- .../settings/McpTranscriptDialog.kt | 3 ++- .../aiagentmcp/transport/McpRedactor.kt | 15 ++++++++++--- .../aiagentmcp/errors/McpLogFormatTest.kt | 14 +++++++++++++ .../aiagentmcp/transport/McpRedactorTest.kt | 15 +++++++++++++ 5 files changed, 56 insertions(+), 12 deletions(-) diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormat.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormat.kt index 35404318b..3b9f804ba 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormat.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormat.kt @@ -52,15 +52,20 @@ object McpLogFormat { private fun code(status: String): Int? = STATUS_CODE.find(status)?.groupValues?.get(1)?.toInt() - private fun json(text: String): String? { - val indented = runCatching { - when { - text.startsWith("{") -> JSONObject(text).toString(JSON_INDENT) - text.startsWith("[") -> JSONArray(text).toString(JSON_INDENT) - else -> null - } - }.getOrNull() + /** + * [text] as indented JSON, or null when it is not JSON. An Exception or LinkageError from + * [indent] is a body that is not JSON; any other Error, an OutOfMemoryError above all, propagates. + * @param indent the parsing and indenting; injectable so a test can make it fail. + */ + internal fun json(text: String, indent: (String) -> String? = ::indentJson): String? { + val indented = runCatchingRecoverable { indent(text) }.getOrNull() // org.json escapes every '/', which turns each URL in a reply into noise. return indented?.replace("\\/", "/") } + + private fun indentJson(text: String): String? = when { + text.startsWith("{") -> JSONObject(text).toString(JSON_INDENT) + text.startsWith("[") -> JSONArray(text).toString(JSON_INDENT) + else -> null + } } diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpTranscriptDialog.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpTranscriptDialog.kt index 7382a246a..7f0818c87 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpTranscriptDialog.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpTranscriptDialog.kt @@ -11,6 +11,7 @@ import androidx.core.content.ContextCompat import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.itsaky.androidide.plugins.aiagentmcp.R import com.itsaky.androidide.plugins.aiagentmcp.errors.McpTranscript +import com.itsaky.androidide.plugins.aiagentmcp.errors.runCatchingRecoverable import kotlin.time.Duration.Companion.seconds import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job @@ -67,7 +68,7 @@ object McpTranscriptDialog { val label = pluginContext.getString(R.string.mcp_transcript_title) val clipboard = context.getSystemService(ClipboardManager::class.java) ?: return // On the main thread: a short binder call, and the clipboard service is Looper-bound on old APIs. - if (runCatching { clipboard.setPrimaryClip(ClipData.newPlainText(label, text)) }.isFailure) return + if (runCatchingRecoverable { clipboard.setPrimaryClip(ClipData.newPlainText(label, text)) }.isFailure) return button.isEnabled = false button.text = pluginContext.getString(R.string.mcp_transcript_copied) // Not restored on cancellation: that only comes with the dialog or its view going. diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpRedactor.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpRedactor.kt index a280cf6bf..381776ead 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpRedactor.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpRedactor.kt @@ -1,5 +1,6 @@ package com.itsaky.androidide.plugins.aiagentmcp.transport +import com.itsaky.androidide.plugins.aiagentmcp.errors.runCatchingRecoverable import java.net.URLDecoder /** @@ -49,14 +50,22 @@ class McpRedactor( fun forRequest(url: String, credentials: Collection, userHeaderNames: Collection) = McpRedactor(credentials + urlSecrets(url), userHeaderNames) - /** The userinfo and query values of [url], long enough to be masked wherever echoed. */ - private fun urlSecrets(url: String): List { + /** + * The userinfo and query values of [url], long enough to be masked wherever echoed. + * A value that cannot be decoded is kept as it is; an Error other than a LinkageError, an + * OutOfMemoryError above all, propagates. + * @param decode the URL decoding; injectable so a test can make it fail. + */ + internal fun urlSecrets( + url: String, + decode: (String) -> String = { URLDecoder.decode(it, "UTF-8") }, + ): List { val userInfo = USERINFO.find(url)?.groupValues?.get(2) val values = url.substringAfter('?', "").substringBefore('#') .split('&') .map { it.substringAfter('=', "") } return (listOfNotNull(userInfo, userInfo?.substringAfter(':', "")) + values) - .flatMap { listOf(it, runCatching { URLDecoder.decode(it, "UTF-8") }.getOrDefault(it)) } + .flatMap { listOf(it, runCatchingRecoverable { decode(it) }.getOrDefault(it)) } .filter { it.length >= MIN_SUBSTRING_LENGTH } } } diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormatTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormatTest.kt index 83eae0ba0..bdea3a1ca 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormatTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormatTest.kt @@ -2,6 +2,8 @@ package com.itsaky.androidide.plugins.aiagentmcp.errors import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows import org.junit.Assert.assertTrue import org.junit.Test @@ -58,4 +60,16 @@ class McpLogFormatTest { assertEquals(capped, McpLogFormat.pretty(capped)) } + + @Test + fun givenAnExceptionWhileIndenting_whenFormatted_thenTheBodyIsNotJson() { + assertNull(McpLogFormat.json("{\"a\":1}") { throw IllegalStateException("bad") }) + } + + @Test + fun givenAnOutOfMemoryErrorWhileIndenting_whenFormatted_thenItPropagates() { + assertThrows(OutOfMemoryError::class.java) { + McpLogFormat.json("{\"a\":1}") { throw OutOfMemoryError("indenting") } + } + } } diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpRedactorTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpRedactorTest.kt index 2f0fbae73..c06279e03 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpRedactorTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpRedactorTest.kt @@ -1,6 +1,7 @@ package com.itsaky.androidide.plugins.aiagentmcp.transport import org.junit.Assert.assertEquals +import org.junit.Assert.assertThrows import org.junit.Test /** What an exchange record may show: credentials hidden, echoes of them masked, the rest kept. */ @@ -159,4 +160,18 @@ class McpRedactorTest { assertEquals("${McpRedactor.MASK}, and the rest", shown) } + + @Test + fun `a URL value that cannot be decoded is still masked as it is`() { + val secrets = McpRedactor.urlSecrets("https://h/mcp?key=abcdefgh1234") { throw IllegalArgumentException("bad") } + + assertEquals(listOf("abcdefgh1234", "abcdefgh1234"), secrets) + } + + @Test + fun `an OutOfMemoryError while decoding a URL value propagates`() { + assertThrows(OutOfMemoryError::class.java) { + McpRedactor.urlSecrets("https://h/mcp?key=abcdefgh1234") { throw OutOfMemoryError("decoding") } + } + } } From 00e27ffaba2776a158e74d4a6155fd5baa7985ba Mon Sep 17 00:00:00 2001 From: David Schachter Date: Fri, 20 Nov 2026 16:34:00 -0800 Subject: [PATCH 43/90] ADFA-7139 AI-Agent-MCP: a cancel that lands just after a request attached no longer lets it go out From brief 6 (ADFA-7131 comment 41407), H1 (medium). post() called onConnected (McpCallHandle.attach) on a connection that was opened but not connected, and the first write connected it and sent the request. A cancel landing after attach read the flag found the connection and disconnected it, but a disconnect() before the connection exists does nothing (Android's OkHttp-based HttpURLConnectionImpl returns early with no engine; the JDK's has no HttpClient yet), so the write then connected and sent the tools/call anyway. On the JDK, a disconnect before connect was checked to be a no-op: the request still reached the server. post() now connects explicitly and then runs a second callback, beforeSend, before writing anything. McpSession passes handle.throwIfCancelled(), which reads the flag again and throws InterruptedIOException. A cancel between attach and beforeSend is caught there; one after it disconnects a connection that is up, which on Android fails the write. Each redirect hop opens a new connection and goes through attach, connect and beforeSend again. The platform behaviour (Android's disconnect() before and after connect) was not checked on a device; there was no phone. On the JDK, which only the tests run on, a disconnect after connect does not stop a later write either (the next getOutputStream reconnects), so the JDK keeps a window after beforeSend. Tests: - CancelAfterAttachTest: the cancel lands inside onConnected, after attach read the flag and before the connection is connected; the server counts the request bodies it receives and sees no tools/call, and the call ends with InterruptedIOException. - McpCallHandleTest: a cancel after attach is caught by throwIfCancelled, and a call not cancelled goes ahead. With only McpSession's beforeSend reverted to a no-op: CancelAfterAttachTest fails with "the cancelled call's request reached the server expected:<[initialize, notifications/initialized]> but was:<[initialize, notifications/initialized, tools/call]>". Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../aiagentmcp/client/McpCallHandle.kt | 27 ++++- .../plugins/aiagentmcp/client/McpSession.kt | 4 +- .../aiagentmcp/transport/McpHttpClient.kt | 12 ++- .../client/CancelAfterAttachTest.kt | 101 ++++++++++++++++++ .../aiagentmcp/client/McpCallHandleTest.kt | 21 ++++ .../client/McpSessionLifecycleTest.kt | 1 + .../debugger/ReadOnlyHintParsingTest.kt | 1 + 7 files changed, 161 insertions(+), 6 deletions(-) create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/CancelAfterAttachTest.kt diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpCallHandle.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpCallHandle.kt index dbca4d218..ebcf1407e 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpCallHandle.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpCallHandle.kt @@ -21,9 +21,17 @@ private const val TAG = "$LOG_PREFIX.McpCallHandle" * The handshake, the same one the tool worker uses with its flag: a request publishes its * connection and then reads the flag ([attach]); [cancel] sets the flag and then takes the * connection. Both sides are volatile, so however the two interleave, one sees the other: either - * the request finds the flag before it sends anything, or the cancel finds the connection and - * drops it. A cancel that lands before the request has a connection at all, while it reads its - * credentials from the Keystore for instance, is caught by the first. + * the request finds the flag, or the cancel finds the connection. A cancel that lands before the + * request has a connection at all, while it reads its credentials from the Keystore for instance, + * is caught by the first. + * + * Finding the connection is not enough on its own: [attach] runs before the connection is + * connected, and a `disconnect()` then does nothing (Android's and the JDK's both return early with + * no connection to drop), so the first write would connect and send the request anyway. The + * request reads the flag a second time once its connection is up, before it writes anything + * ([throwIfCancelled]); a cancel between the two reads is caught there. One after the second read + * disconnects a connection that is up: Android then fails the write rather than sending it. (The + * JDK, which only the tests run on, reconnects instead.) */ class McpCallHandle { @@ -51,7 +59,7 @@ class McpCallHandle { /** * Publishes [conn] as the connection this call's current request uses, then reads the flag. * - * Called before anything is written to [conn], so a cancelled call sends nothing. + * Called before [conn] is connected; [throwIfCancelled] reads the flag again once it is. * * @param conn the request's connection, opened but not yet connected. * @throws InterruptedIOException when the call was cancelled, which is how a dropped connection @@ -65,6 +73,17 @@ class McpCallHandle { } } + /** + * Reads the flag again, once the request's connection is connected and before anything is + * written to it: a cancel that landed after [attach] read the flag disconnected a connection + * that was not connected yet, which does nothing. + * + * @throws InterruptedIOException when the call was cancelled. + */ + internal fun throwIfCancelled() { + if (cancelled) throw InterruptedIOException("The tool call was cancelled before its request was sent") + } + /** * Forgets the connection once its request has ended, so a late [cancel] does not disconnect a * connection whose socket may have gone back to the pool. diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSession.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSession.kt index d86ff47d2..8c93d096a 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSession.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSession.kt @@ -311,7 +311,8 @@ class McpSession( * * @param handle the calling tool call's: its connection is published there before anything is * sent, and the request is refused if the call was cancelled meanwhile, while the credentials - * were read for instance. Null for a listing, which no call's cancel reaches. + * were read for instance, or after that, before the connection was connected. Null for a + * listing, which no call's cancel reaches. */ private fun send(envelope: JSONObject, handle: McpCallHandle? = null): McpHttpClient.Response { // Read here rather than held on the session, so the plaintext lives for one request. @@ -327,6 +328,7 @@ class McpSession( protocolVersion = negotiatedVersion, extraHeaders = current.headers, onConnected = { conn -> handle?.attach(conn) }, + beforeSend = { handle?.throwIfCancelled() }, exchangeListener = recorder.get() ?: McpExchangeListener.NONE, ) } finally { diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt index e9c77f05f..28b42def5 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt @@ -168,7 +168,11 @@ open class McpHttpClient( * @param body the JSON-RPC envelope to send. * @param sessionId the session to continue, or null before one exists. * @param protocolVersion the negotiated revision, or null before `initialize` has answered. - * @param onConnected receives the live connection, so a caller can disconnect it to cancel. + * @param onConnected receives each request's connection, redirect hops included, before it is + * connected, so a caller can disconnect it to cancel. + * @param beforeSend runs once that connection is connected and before anything is written to + * it; what it throws ends the request unsent. A `disconnect()` before the connection exists + * does nothing, so a cancel landing just after [onConnected] is caught here or not at all. * @param exchangeListener receives each request made and what came back, redirects included. * An Exception or a LinkageError it throws is dropped; any other Error propagates. * @return the reply document and any session id the server sent. @@ -182,6 +186,7 @@ open class McpHttpClient( protocolVersion: String? = null, extraHeaders: Map = emptyMap(), onConnected: (HttpURLConnection) -> Unit = {}, + beforeSend: () -> Unit = {}, exchangeListener: McpExchangeListener = McpExchangeListener.NONE, ): Response { val payload = body.toString() @@ -208,6 +213,11 @@ open class McpHttpClient( var reusable = false var failure: Throwable? = null val redirect = try { + // Connected here rather than by the first write, so beforeSend runs in between: a + // cancel whose disconnect came before the connection existed dropped nothing, and the + // write would connect and send the request regardless. + conn.connect() + beforeSend() conn.outputStream.use { it.write(bytes) } trace.answered(conn) val next = conn.redirectTargetFrom(target) diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/CancelAfterAttachTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/CancelAfterAttachTest.kt new file mode 100644 index 000000000..9cf4003f1 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/CancelAfterAttachTest.kt @@ -0,0 +1,101 @@ +package com.itsaky.androidide.plugins.aiagentmcp.client + +import com.itsaky.androidide.plugins.aiagentmcp.transport.McpExchangeListener +import com.itsaky.androidide.plugins.aiagentmcp.transport.McpHttpClient +import com.sun.net.httpserver.HttpServer +import java.io.InterruptedIOException +import java.net.HttpURLConnection +import java.net.InetSocketAddress +import java.util.concurrent.CopyOnWriteArrayList +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * A cancel that lands just after a request published its connection, after [McpCallHandle.attach] + * read the flag and before the connection is connected, sends nothing. + * + * Such a cancel finds the connection and disconnects it, but a connection that is not connected + * yet has nothing to drop, on Android and on the JDK alike; the request's first write then + * connected and sent it. The request now reads the flag again once its connection is up. + */ +class CancelAfterAttachTest { + + /** The JSON-RPC method of every request body the server received, in order. */ + private val received = CopyOnWriteArrayList() + + private val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply { + createContext("/mcp") { exchange -> + val request = JSONObject(exchange.requestBody.use { String(it.readBytes()) }) + received += request.optString("method") + if (!request.has("id")) { + exchange.sendResponseHeaders(202, -1) + } else { + val result = when (request.optString("method")) { + "initialize" -> JSONObject().put("protocolVersion", "2025-06-18") + else -> JSONObject().put("content", org.json.JSONArray()) + } + val bytes = JSONObject().put("jsonrpc", "2.0").put("id", request.get("id")) + .put("result", result).toString().toByteArray() + exchange.responseHeaders.add("Content-Type", "application/json") + exchange.sendResponseHeaders(200, bytes.size.toLong()) + exchange.responseBody.use { it.write(bytes) } + } + exchange.close() + } + start() + } + + @After + fun tearDown() { + server.stop(0) + } + + @Test + fun `a cancel that lands just after the request attached sends nothing`() { + val handle = McpCallHandle() + val http = object : McpHttpClient() { + override fun post( + url: String, + token: String, + body: JSONObject, + sessionId: String?, + protocolVersion: String?, + extraHeaders: Map, + onConnected: (HttpURLConnection) -> Unit, + beforeSend: () -> Unit, + exchangeListener: McpExchangeListener, + ): Response = super.post( + url, + token, + body, + sessionId, + protocolVersion, + extraHeaders, + onConnected = { conn -> + onConnected(conn) + // Here: attach has read the flag, and the connection is not connected yet. + if (body.optString("method") == "tools/call") handle.cancel() + }, + beforeSend = beforeSend, + exchangeListener = exchangeListener, + ) + } + val session = McpSession( + "http://127.0.0.1:${server.address.port}/mcp", + { McpCredentials("", emptyMap()) }, + http, + ) + + val failure = runCatching { session.callTool("echo", emptyMap(), handle) }.exceptionOrNull() + + assertEquals( + "the cancelled call's request reached the server", + listOf("initialize", "notifications/initialized"), + received.toList(), + ) + assertTrue("the call did not end cancelled: $failure", failure is InterruptedIOException) + } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpCallHandleTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpCallHandleTest.kt index 68d236368..e89990609 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpCallHandleTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpCallHandleTest.kt @@ -4,6 +4,7 @@ import java.io.InterruptedIOException import java.net.HttpURLConnection import java.net.URL import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse import org.junit.Assert.assertThrows import org.junit.Assert.assertTrue import org.junit.Test @@ -50,6 +51,26 @@ class McpCallHandleTest { assertTrue(handle.isCancelled) } + @Test + fun `a cancel after the request attached is caught before it sends anything`() { + val handle = McpCallHandle() + handle.attach(FakeConnection()) + + handle.cancel() + + assertThrows(InterruptedIOException::class.java) { handle.throwIfCancelled() } + } + + @Test + fun `a request not cancelled goes ahead`() { + val handle = McpCallHandle() + handle.attach(FakeConnection()) + + handle.throwIfCancelled() + + assertFalse(handle.isCancelled) + } + @Test fun `a cancel after the request ended drops nothing`() { val handle = McpCallHandle() diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSessionLifecycleTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSessionLifecycleTest.kt index 085a6f274..ef0bf7df5 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSessionLifecycleTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSessionLifecycleTest.kt @@ -79,6 +79,7 @@ class McpSessionLifecycleTest { protocolVersion: String?, extraHeaders: Map, onConnected: (HttpURLConnection) -> Unit, + beforeSend: () -> Unit, exchangeListener: McpExchangeListener, ): Response { val method = body.optString("method") diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReadOnlyHintParsingTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReadOnlyHintParsingTest.kt index 74c724506..6301ddfc4 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReadOnlyHintParsingTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReadOnlyHintParsingTest.kt @@ -27,6 +27,7 @@ class ReadOnlyHintParsingTest { protocolVersion: String?, extraHeaders: Map, onConnected: (HttpURLConnection) -> Unit, + beforeSend: () -> Unit, exchangeListener: McpExchangeListener, ): Response { val result = when (body.optString("method")) { From 37faab4b7916210e69c5c0e36d56e3d8dda809c4 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Fri, 20 Nov 2026 16:47:29 -0800 Subject: [PATCH 44/90] ADFA-7139 AI-Agent-MCP: a deeply nested body no longer overflows the stack in the connection log From brief 6 (ADFA-7131 comment 41407), H2 (low-medium), a consequence of 08e9e677. McpLogFormat.json handed a server's body, up to 16 Ki characters, to JSONObject(text) / JSONArray(text). Android's org.json tokener recurses once per nesting level with no limit, so a body such as [[[[... thousands deep can throw StackOverflowError, which since 08e9e677 propagates (the catch takes only Exception and LinkageError). json() now scans the text once, with no recursion, before any parser sees it, and returns null (the body is shown as it came) when arrays and objects nest deeper than MAX_JSON_DEPTH (100). Brackets inside strings do not count. A string is taken to start only where a parser starts a value or a key: a double or single quote (org.json reads both) at the start or after [ { , or :, past whitespace; a backslash escapes the next character. A quote anywhere else starts nothing, so the brackets after it count: counting too many only leaves a body unindented, while counting too few would let a hostile body slip past (['"',[[[[... for instance, or a quote inside a comment, which Android's org.json skips). The narrowed catch is unchanged. The README's security notes say so. The org.json these tests run on (20240303) catches an overflow while parsing and throws JSONException("JSON Array or Object depth too large to process") instead, checked by hand, so the real parser cannot show the overflow here. The failing test therefore uses a parser that recurses once per level as Android's does, on a thread with a 128 KiB stack. Tests (McpLogFormatTest): - 10,000 nested [ is not JSON and nothing throws (real parser). - 10,000 nested [ with a recursive parser on a small stack: nothing throws. - nesting at the limit is indented; one level past it is shown as it came. - brackets inside strings, after an escaped quote and in a single-quoted string, do not count. - the brackets after a " inside a single-quoted string, and after a " in a comment, count. With only the guard call in json() removed: the recursive-parser test fails with "formatting the body threw java.lang.StackOverflowError", and the one-past-the-limit test with "expected null". The real-parser 10,000 test passes either way on this JVM, for the reason above. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- plugins/AI-Agent-MCP/README.md | 4 + .../plugins/aiagentmcp/errors/McpLogFormat.kt | 49 +++++++++++ .../aiagentmcp/errors/McpLogFormatTest.kt | 81 +++++++++++++++++++ 3 files changed, 134 insertions(+) diff --git a/plugins/AI-Agent-MCP/README.md b/plugins/AI-Agent-MCP/README.md index d7ac14cb3..5fb789ed3 100644 --- a/plugins/AI-Agent-MCP/README.md +++ b/plugins/AI-Agent-MCP/README.md @@ -187,6 +187,10 @@ Two dependencies were deliberately not taken: is kept only in part, cut at a fixed length; when the cut falls inside a credential, what was kept of it is masked too, so the log never shows the start of one. +- The connection log indents a JSON body only when it nests arrays and objects + at most 100 levels deep, brackets inside strings not counted. A deeper one is + shown as it came: parsing recurses once per level, and a server's body of + nothing but `[` would run Code on the Go out of stack. - A `202 Accepted` body is read and thrown away, for at most 1 MiB of characters and 10 seconds; one that runs past either is abandoned and its socket disconnected, not reused. The worst case is the 10 seconds plus one read diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormat.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormat.kt index 3b9f804ba..74d240296 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormat.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormat.kt @@ -16,6 +16,13 @@ object McpLogFormat { private const val JSON_INDENT = 2 + /** + * How deeply a body may nest arrays and objects and still be indented. Parsing recurses once + * per level, on Android with no limit of its own, so a server's body of nothing but `[` would + * run the thread out of stack; no MCP reply comes near this. + */ + internal const val MAX_JSON_DEPTH = 100 + private val STATUS_CODE = Regex("""\b([1-5]\d\d)\b""") /** @@ -55,14 +62,56 @@ object McpLogFormat { /** * [text] as indented JSON, or null when it is not JSON. An Exception or LinkageError from * [indent] is a body that is not JSON; any other Error, an OutOfMemoryError above all, propagates. + * So would a StackOverflowError, which is why [text] never reaches [indent] when it nests + * deeper than [MAX_JSON_DEPTH]: it is shown as it came. * @param indent the parsing and indenting; injectable so a test can make it fail. */ internal fun json(text: String, indent: (String) -> String? = ::indentJson): String? { + if (nestsDeeperThan(text, MAX_JSON_DEPTH)) return null val indented = runCatchingRecoverable { indent(text) }.getOrNull() // org.json escapes every '/', which turns each URL in a reply into noise. return indented?.replace("\\/", "/") } + /** + * Whether [text] opens more than [limit] arrays or objects one inside another; one pass, no + * recursion. A bracket inside a string does not count. + * + * A string starts only where a parser starts a value or a key: at a double or single quote + * (org.json reads both) that opens the text or follows `[`, `{`, `,` or `:`, past whitespace. + * A quote anywhere else, after a comment for instance, starts nothing here, so the brackets + * after it count. Erring that way only leaves a body unindented; erring the other way would + * let a parser recurse through brackets this scan took for text. + */ + internal fun nestsDeeperThan(text: String, limit: Int): Boolean { + var depth = 0 + var quote: Char? = null + var escaped = false + var valueStarts = true + for (c in text) { + if (quote != null) { + when { + escaped -> escaped = false + c == '\\' -> escaped = true + c == quote -> quote = null + } + continue + } + if (c == ' ' || c == '\t' || c == '\n' || c == '\r') continue + if ((c == '"' || c == '\'') && valueStarts) { + quote = c + valueStarts = false + continue + } + when (c) { + '[', '{' -> if (++depth > limit) return true + ']', '}' -> if (depth > 0) depth-- + } + valueStarts = c == '[' || c == '{' || c == ',' || c == ':' + } + return false + } + private fun indentJson(text: String): String? = when { text.startsWith("{") -> JSONObject(text).toString(JSON_INDENT) text.startsWith("[") -> JSONArray(text).toString(JSON_INDENT) diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormatTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormatTest.kt index bdea3a1ca..2dcd457c7 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormatTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormatTest.kt @@ -2,6 +2,7 @@ package com.itsaky.androidide.plugins.aiagentmcp.errors import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull import org.junit.Assert.assertNull import org.junit.Assert.assertThrows import org.junit.Assert.assertTrue @@ -72,4 +73,84 @@ class McpLogFormatTest { McpLogFormat.json("{\"a\":1}") { throw OutOfMemoryError("indenting") } } } + + @Test + fun givenTenThousandNestedBrackets_whenFormatted_thenItIsNotJsonAndNothingThrows() { + assertNull(McpLogFormat.json("[".repeat(10_000))) + } + + /** + * Android's org.json recurses once per level with no limit of its own and catches nothing, so + * such a body overflows the stack there, and the StackOverflowError propagates. The org.json + * these tests run on turns an overflow while parsing into a JSONException, so the real parser + * cannot show it here; a parser that recurses the same way, on a thread with a small stack, + * stands in for Android's. + */ + @Test + fun givenTenThousandNestedBrackets_whenFormatted_thenNoParserRecursesThroughThem() { + val deep = "[".repeat(10_000) + var result: String? = "never ran" + var thrown: Throwable? = null + val parsing = Thread(null, { + try { + result = McpLogFormat.json(deep, ::recursiveIndent) + } catch (t: Throwable) { + thrown = t + } + }, "small-stack", SMALL_STACK_BYTES) + parsing.start() + parsing.join(10_000) + + assertNull("formatting the body threw $thrown", thrown) + assertNull(result) + } + + @Test + fun givenNestingAtTheLimit_whenFormatted_thenItIsIndented() { + val depth = McpLogFormat.MAX_JSON_DEPTH + assertNotNull(McpLogFormat.json("[".repeat(depth) + "]".repeat(depth))) + } + + @Test + fun givenNestingOneLevelPastTheLimit_whenFormatted_thenItIsShownAsItCame() { + val depth = McpLogFormat.MAX_JSON_DEPTH + 1 + val body = "{\"a\":" + "[".repeat(depth - 1) + "]".repeat(depth - 1) + "}" + + assertNull(McpLogFormat.json(body)) + assertEquals(body, McpLogFormat.pretty(body)) + } + + @Test + fun givenBracketsInsideStrings_whenFormatted_thenTheyDoNotCount() { + val brackets = "[".repeat(500) + // An escaped quote at the start of "b" and an escaped backslash at its end: neither ends it. + val body = """{"a":"$brackets","b":"\"$brackets\\","c":['$brackets']}""" + + assertNotNull("brackets inside strings were counted", McpLogFormat.json(body)) + } + + @Test + fun givenADoubleQuoteInsideASingleQuotedString_whenScanned_thenTheBracketsAfterItCount() { + // org.json reads '"' as a one-character string, then recurses into the brackets after it. + assertTrue(McpLogFormat.nestsDeeperThan("['\"',${"[".repeat(200)}", 100)) + } + + @Test + fun givenAQuoteWhereNoValueStarts_whenScanned_thenTheBracketsAfterItCount() { + // Android's org.json skips the comment, so no string starts at its quote. + assertTrue(McpLogFormat.nestsDeeperThan("[/*\"*/${"[".repeat(200)}", 100)) + } + + /** Descends once per opening bracket at the start of [text], as a recursive-descent parser does. */ + private fun recursiveIndent(text: String): String? { + fun descend(index: Int): Int = + if (index < text.length && (text[index] == '[' || text[index] == '{')) descend(index + 1) + 1 else 0 + descend(0) + return text + } + + private companion object { + /** Far less than 10,000 frames need, whatever the JIT makes of them. */ + const val SMALL_STACK_BYTES = 128L * 1024 + } } From 2d28abab82a6c598187e347c6118c96cfbc7282e Mon Sep 17 00:00:00 2001 From: David Schachter Date: Fri, 20 Nov 2026 16:51:59 -0800 Subject: [PATCH 45/90] ADFA-7139 AI-Agent-MCP: a deactivation during an activation no longer leaves a closed tool source registered From brief 6 (ADFA-7131 comment 41407), L1 (low). activate() set `toolSource = toolSource ?: McpToolSource()`, a read and a write on a plain field, and teardown() closed the source and then cleared it, with nothing between the two. A teardown falling between activate's read and write put back a closed source; one falling after the registration started and before `registered` was set unregistered nothing and closed the source AI Core was being handed. Either way AI Core held a closed source, and every invoke failed with RejectedExecutionException from its shut-down executor. The listener's registerToolSource, run when AI Core activates, raced teardown the same way. The lifecycle transitions now share lifecycleLock, the lock that already serialised the scope swaps: activate, deactivate, dispose and teardown run whole, one at a time, and so does the registration in the listener's onPluginActivated. toolSource is read and written only under it. The host calls activate and dispatches lifecycle events holding no lock of its own (PluginManager.activateLoadedPlugin, PluginLifecycleDispatcher), and its listener and service registries do not call back, so nothing taken under the lock waits for this plugin. A teardown still ends every session with a DELETE under it, so a lifecycle call or AI Core's registration arriving meanwhile waits for that too. Tests (ConcurrentLifecycleTest): the registry holds the registration on a latch, a deactivate starts on another thread, and the test waits until that thread has finished or is blocked on a monitor the registering thread holds (ThreadMXBean lockOwnerId), then releases the registration. - a deactivate arriving while activate registers the tool source leaves none registered; - the same while AI Core's activation (the lifecycle listener) registers. With only the lock in activate, deactivate, dispose and teardown removed: both tests fail with "a tool source is still registered after the deactivate expected:<0> but was:<1>". With only the listener's lock removed: the listener test fails the same way, and the activate test passes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../plugins/aiagentmcp/plugin/McpPlugin.kt | 55 ++++--- .../plugin/ConcurrentLifecycleTest.kt | 144 ++++++++++++++++++ 2 files changed, 181 insertions(+), 18 deletions(-) create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/ConcurrentLifecycleTest.kt diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt index b641ba774..0eb3c17ea 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt @@ -52,7 +52,7 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { /** * The tool source registered with AI Core: built by the first [activate], kept by a second, and - * closed and cleared by [teardown]. + * closed and cleared by [teardown]. Read and written only under [lifecycleLock]. */ private var toolSource: McpToolSource? = null @@ -60,12 +60,21 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { @Volatile private var registered = false /** - * Serialises every swap of [scope]. + * Serialises the lifecycle transitions: [activate], [deactivate] and [dispose], [teardown] which + * they share, and the registration AI Core's activation triggers. Each runs whole before the next + * starts, since the host may drive one from one thread and the next from another. * - * Cancelling the old scope and installing a new one is one transition, not two: without this, - * two lifecycle calls landing together can each cancel the scope the other has already replaced, - * leaving a live refresh behind after [deactivate] or orphaning an activation's scope uncancelled. - * `@Volatile` alone would publish each write but still let the pair interleave. + * Without it, a teardown could fall inside an activation: between its read of [toolSource] and + * its write, putting back a source the teardown had just closed, or after the registration had + * started and before [registered] was set, so the teardown unregistered nothing and closed the + * source AI Core was being handed. AI Core then held a closed source, whose every call fails + * with a RejectedExecutionException. Every swap of [scope] takes it too: cancelling the old + * scope and installing a new one is one transition, not two. + * + * Nothing taken under it waits for this plugin's own work: the host's listener and service + * registries do not call back, and the coroutines it cancels never take it. A transition can + * still wait for the network, since [teardown] ends every session with a DELETE; a lifecycle + * call arriving meanwhile waits with it. */ private val lifecycleLock = Any() @@ -158,7 +167,9 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { */ private val aiCoreLifecycle = object : PluginLifecycleListener { override fun onPluginActivated(pluginId: String) { - if (pluginId == AI_CORE_PLUGIN_ID) registerToolSource() + // Under the lifecycle lock, so a deactivation arriving meanwhile undoes this + // registration rather than closing the source while AI Core is handed it. + if (pluginId == AI_CORE_PLUGIN_ID) synchronized(lifecycleLock) { registerToolSource() } } override fun onPluginDeactivated(pluginId: String) { @@ -227,7 +238,10 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { return true } - override fun activate(): Boolean = try { + override fun activate(): Boolean = synchronized(lifecycleLock) { activateLocked() } + + /** [activate] itself, under [lifecycleLock]. */ + private fun activateLocked(): Boolean = try { // Cancelled and replaced as one step: a host that activates twice would otherwise orphan // the running scope, and the launch below has to use this activation's scope, not whatever // a concurrent lifecycle call has since installed. @@ -289,17 +303,21 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { return false } - override fun deactivate(): Boolean = try { - teardown() - true - } catch (e: Exception) { - context.logger.error("McpPlugin: deactivation failed", e) - false + override fun deactivate(): Boolean = synchronized(lifecycleLock) { + try { + teardown() + true + } catch (e: Exception) { + context.logger.error("McpPlugin: deactivation failed", e) + false + } } override fun dispose() { - teardown() - pluginContext = null + synchronized(lifecycleLock) { + teardown() + pluginContext = null + } context.logger.info("McpPlugin: disposed") } @@ -307,9 +325,10 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { * Stops what [activate] started: the lifecycle and change listeners, the tool source's * registration, the scope with its work, and the connections. The one teardown path, shared by * [deactivate], [dispose] and a failed [activate], so the three cannot drift apart. Safe to run - * on an activation that got only part of the way, and on none at all. + * on an activation that got only part of the way, and on none at all. Each caller holds + * [lifecycleLock]; taken here too, so a new caller cannot forget it. */ - private fun teardown() { + private fun teardown() = synchronized(lifecycleLock) { // Guarded: a host whose plugin-api differs answers with a LinkageError, and one escaping // here would skip every step below, leaving the scope and its probe running. runCatchingRecoverable { context.removePluginLifecycleListener(aiCoreLifecycle) } diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/ConcurrentLifecycleTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/ConcurrentLifecycleTest.kt new file mode 100644 index 000000000..de8748656 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/ConcurrentLifecycleTest.kt @@ -0,0 +1,144 @@ +package com.itsaky.androidide.plugins.aiagentmcp.plugin + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.PluginLifecycleListener +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.services.SharedServices +import com.itsaky.androidide.plugins.services.ToolSourceRegistry +import io.mockk.every +import io.mockk.mockk +import io.mockk.slot +import java.lang.management.ManagementFactory +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import kotlin.concurrent.thread +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * A deactivation that arrives while the tool source is being registered waits for the registration + * and then undoes it, rather than running alongside it. + * + * The registration used to run unguarded against [McpPlugin.deactivate]: the deactivation found + * nothing registered yet, closed the tool source and cleared it, and the registration then + * finished. AI Core was left holding a closed source, whose every call fails with a + * RejectedExecutionException. The same held for `toolSource = toolSource ?: McpToolSource()`, + * a read and a write a teardown could fall between. The lifecycle calls, and the registration AI + * Core's activation triggers, now share one lock. + * + * The registry holds each registration on a latch. The deactivation runs on another thread, and the + * test waits until it has either finished or is blocked on a lock the registering thread holds: + * no sleeps, and no outcome that depends on timing. + */ +class ConcurrentLifecycleTest { + + /** What the registry holds now. */ + private val registered = CopyOnWriteArrayList() + + private val registering = CountDownLatch(1) + private val releaseRegistration = CountDownLatch(1) + + /** Matches by identity, as AI Core's does; a registration waits on [releaseRegistration]. */ + private val registry = object : ToolSourceRegistry { + override fun getToolSources(): List = registered.toList() + + override fun notifyToolsChanged(providerId: String) = Unit + + override fun registerToolSource(source: ToolSourceRegistry.ToolSource) { + registering.countDown() + assertTrue("the test never released the registration", releaseRegistration.await(10, TimeUnit.SECONDS)) + registered += source + } + + override fun unregisterToolSource(source: ToolSourceRegistry.ToolSource) { + registered.removeAll { it === source } + } + } + + private val lifecycleListener = slot() + private lateinit var context: PluginContext + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + every { context.addPluginLifecycleListener(capture(lifecycleListener)) } returns Unit + every { context.getPluginService(any(), ToolSourceRegistry::class.java) } returns null + plugin = McpPlugin().also { it.initialize(context) } + } + + @After + fun tearDown() { + releaseRegistration.countDown() + plugin.dispose() + SharedServices.unregister(ToolSourceRegistry::class.java) + } + + @Test + fun `a deactivate that arrives while activate registers the tool source leaves none registered`() { + SharedServices.register(ToolSourceRegistry::class.java, registry) + + val activating = thread(name = "activating") { plugin.activate() } + assertTrue("activate never registered the tool source", registering.await(10, TimeUnit.SECONDS)) + val deactivating = thread(name = "deactivating") { plugin.deactivate() } + awaitFinishedOrBlockedBy(deactivating, activating) + releaseRegistration.countDown() + activating.join(10_000) + deactivating.join(10_000) + + assertFalse("activate never finished", activating.isAlive) + assertFalse("deactivate never finished", deactivating.isAlive) + assertEquals("a tool source is still registered after the deactivate", 0, registered.size) + } + + @Test + fun `a deactivate that arrives while AI Core's activation registers the tool source leaves none registered`() { + // AI Core is not active yet: activate registers nothing and leaves it to the listener. + plugin.activate() + assertEquals(0, registered.size) + SharedServices.register(ToolSourceRegistry::class.java, registry) + + val registeringThread = thread(name = "ai-core-activated") { + lifecycleListener.captured.onPluginActivated(AI_CORE_PLUGIN_ID) + } + assertTrue("the listener never registered the tool source", registering.await(10, TimeUnit.SECONDS)) + val deactivating = thread(name = "deactivating") { plugin.deactivate() } + awaitFinishedOrBlockedBy(deactivating, registeringThread) + releaseRegistration.countDown() + registeringThread.join(10_000) + deactivating.join(10_000) + + assertFalse("the registration never finished", registeringThread.isAlive) + assertFalse("deactivate never finished", deactivating.isAlive) + assertEquals("a tool source is still registered after the deactivate", 0, registered.size) + } + + /** + * Waits until [waiter] has finished, or is blocked entering a monitor that [holder] holds. + * Without the lock the deactivation runs straight to its end; with it, it blocks on the lock + * the registering thread holds. Either way the wait ends without depending on how long anything + * takes. + */ + private fun awaitFinishedOrBlockedBy(waiter: Thread, holder: Thread) { + val threads = ManagementFactory.getThreadMXBean() + val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10) + while (System.nanoTime() < deadline) { + if (waiter.state == Thread.State.TERMINATED) return + if (waiter.state == Thread.State.BLOCKED && threads.getThreadInfo(waiter.id)?.lockOwnerId == holder.id) { + return + } + Thread.yield() + } + throw AssertionError("${waiter.name} neither finished nor waited for ${holder.name}: ${waiter.state}") + } + + private companion object { + const val AI_CORE_PLUGIN_ID = "com.itsaky.androidide.plugins.aicore" + } +} From ff9a79a8673cb83036649c50c8f319d9f246ae20 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Fri, 20 Nov 2026 17:08:06 -0800 Subject: [PATCH 46/90] ADFA-7139 AI-Agent-MCP: a session id the server assigns is masked where its reply echoes it From brief 6 (ADFA-7131 comment 41407), L5 (low). post() builds the connection log's redactor from what the request carries: the token, the user's header values and the request's session id. The request for `initialize` carries no session id; the server assigns one in its answer. The Mcp-Session-Id header itself was hidden by name, but a body that repeated the id showed it in the log. McpExchangeTrace.answered now extends its redactor with the session id the answer assigns (McpRedactor.with), before it keeps anything of the answer, so the answer's other headers and its body are scrubbed of it too. post() hands the exchange listener the trace's redactor, so McpExchangeLog.redact masks it in an error raised after that exchange as well. A session id the request already carried changes nothing. The README's security notes say so. The other redactor gaps (case-folded non-hex tokens, HTML entities, '+' for a space, %XX of non-ASCII, base64) are accepted and unchanged. Test (AssignedSessionRedactionTest): an initialize reply whose Mcp-Session-Id header assigns an id and whose body says "Your session is ." shows the body with the id masked in the connection log (McpSession.recording into an McpExchangeLog). With only the extension in answered removed: it fails with "the connection log shows the assigned session id: {"result":{"instructions":"Your session is sess-7d41c9e2a8b3f650.", ...". Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- plugins/AI-Agent-MCP/README.md | 3 +- .../aiagentmcp/transport/McpExchangeTrace.kt | 14 +++- .../aiagentmcp/transport/McpHttpClient.kt | 3 +- .../aiagentmcp/transport/McpRedactor.kt | 11 ++- .../client/AssignedSessionRedactionTest.kt | 68 +++++++++++++++++++ 5 files changed, 95 insertions(+), 4 deletions(-) create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/AssignedSessionRedactionTest.kt diff --git a/plugins/AI-Agent-MCP/README.md b/plugins/AI-Agent-MCP/README.md index 5fb789ed3..6401f2cee 100644 --- a/plugins/AI-Agent-MCP/README.md +++ b/plugins/AI-Agent-MCP/README.md @@ -183,7 +183,8 @@ Two dependencies were deliberately not taken: cannot be replayed to another host in one hop. - Error bodies stay in logcat. The transcript gets one sentence. - The connection log masks every credential the request carried wherever the - server echoes it, escaped or not (`McpRedactor`). The body of a `202 Accepted` + server echoes it, escaped or not (`McpRedactor`), and the session id a reply + assigns wherever that reply echoes it. The body of a `202 Accepted` is kept only in part, cut at a fixed length; when the cut falls inside a credential, what was kept of it is masked too, so the log never shows the start of one. diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpExchangeTrace.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpExchangeTrace.kt index 7c6c46b7f..29338c4fa 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpExchangeTrace.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpExchangeTrace.kt @@ -8,6 +8,7 @@ import java.net.HttpURLConnection * * @param headers the headers as set on the connection, credentials included. * @param contentLength the body's size in bytes, as the stack sends it. + * @param redactor the request's own, built from the credentials it carries. */ internal class McpExchangeTrace( private val method: String, @@ -15,9 +16,17 @@ internal class McpExchangeTrace( private val headers: List>, private val payload: String, private val contentLength: Int, - private val redactor: McpRedactor, + redactor: McpRedactor, ) { + /** + * What everything passes through: the request's redactor until [answered], and from there one + * that also masks the session id the answer assigned. A reply to `initialize` assigns one the + * request could not carry, and its body may repeat it. + */ + var redactor: McpRedactor = redactor + private set + private var status: String? = null private var responseHeaders: List = emptyList() private var responseBody: McpExchange.Body? = null @@ -25,6 +34,9 @@ internal class McpExchangeTrace( /** Records the status line and headers, which is where the server is first heard from. */ fun answered(conn: HttpURLConnection) { val code = conn.responseCode + // Before anything of the answer is kept: its other headers and its body may echo the id. + conn.getHeaderField(McpHttpClient.HEADER_SESSION_ID)?.takeIf { it.isNotBlank() } + ?.let { redactor = redactor.with(it) } val fields = conn.headerFields.orEmpty().entries status = fields.firstOrNull { it.key == null }?.value?.firstOrNull() ?: "HTTP $code ${conn.responseMessage.orEmpty()}".trim() diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt index 28b42def5..17ec2bae9 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt @@ -262,7 +262,8 @@ open class McpHttpClient( // The connection log is a convenience: a listener failing with an Exception or a // LinkageError costs only its record. Any other Error, an OutOfMemoryError above // all, is the process failing and propagates. - runCatchingRecoverable { exchangeListener.onExchange(trace.toExchange(failure), redactor) } + // The trace's redactor, which masks a session id this answer assigned as well. + runCatchingRecoverable { exchangeListener.onExchange(trace.toExchange(failure), trace.redactor) } } if (++hops > MAX_REDIRECTS) { diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpRedactor.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpRedactor.kt index 381776ead..a3e29358e 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpRedactor.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpRedactor.kt @@ -11,7 +11,7 @@ import java.net.URLDecoder * @param userHeaderNames the headers the user configured; their values are stored encrypted. */ class McpRedactor( - credentials: Collection, + private val credentials: Collection, private val userHeaderNames: Collection, ) { @@ -83,6 +83,15 @@ class McpRedactor( /** How many characters one secret can take up in a text at most, in its longest escaped form. */ private val longestForm: Int = (plainSecrets.firstOrNull()?.length ?: 0) * LONGEST_CHAR_FORM + /** + * This redactor, masking [credential] as well: for a secret the server hands out in its answer, + * which the request this redactor was built for could not carry. + * @param credential the secret, such as the session id a reply to `initialize` assigns. + * @return a redactor masking it and everything this one masks; this one when it already does. + */ + fun with(credential: String): McpRedactor = + if (credential in credentials) this else McpRedactor(credentials + credential, userHeaderNames) + /** * A header this client sent, its value hidden when it is a credential. * @return the header as it may be shown. diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/AssignedSessionRedactionTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/AssignedSessionRedactionTest.kt new file mode 100644 index 000000000..329d6e4bc --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/AssignedSessionRedactionTest.kt @@ -0,0 +1,68 @@ +package com.itsaky.androidide.plugins.aiagentmcp.client + +import com.itsaky.androidide.plugins.aiagentmcp.transport.McpExchangeLog +import com.itsaky.androidide.plugins.aiagentmcp.transport.McpRedactor +import com.sun.net.httpserver.HttpServer +import java.net.InetSocketAddress +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * A session id the server assigns in its reply to `initialize` is masked in the connection log + * wherever that same reply's body echoes it. + * + * The log's redactor is built from what the request carried, and `initialize` carries no session + * id: the server assigns one in its answer. The `Mcp-Session-Id` header itself was hidden by name, + * but a body repeating the id showed it. The redactor for that answer now masks it too. + */ +class AssignedSessionRedactionTest { + + private val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply { + createContext("/mcp") { exchange -> + val request = JSONObject(exchange.requestBody.use { String(it.readBytes()) }) + if (!request.has("id")) { + exchange.sendResponseHeaders(202, -1) + } else { + val result = JSONObject() + .put("protocolVersion", "2025-06-18") + .put("serverInfo", JSONObject().put("name", "echoing")) + .put("instructions", "Your session is $SESSION_ID.") + val bytes = JSONObject().put("jsonrpc", "2.0").put("id", request.get("id")) + .put("result", result).toString().toByteArray() + exchange.responseHeaders.add("Content-Type", "application/json") + exchange.responseHeaders.add("Mcp-Session-Id", SESSION_ID) + exchange.sendResponseHeaders(200, bytes.size.toLong()) + exchange.responseBody.use { it.write(bytes) } + } + exchange.close() + } + start() + } + + @After + fun tearDown() { + server.stop(0) + } + + @Test + fun `a session id the server assigns is masked where the same reply's body echoes it`() { + val session = McpSession( + "http://127.0.0.1:${server.address.port}/mcp", + { McpCredentials("", emptyMap()) }, + ) + val log = McpExchangeLog() + + session.recording(log) { session.initialize() } + + val reply = requireNotNull(log.snapshot().first().responseBody).text + assertFalse("the connection log shows the assigned session id: $reply", reply.contains(SESSION_ID)) + assertTrue("the echo was not masked: $reply", reply.contains("Your session is ${McpRedactor.MASK}.")) + } + + private companion object { + const val SESSION_ID = "sess-7d41c9e2a8b3f650" + } +} From 9ccbd92a54bcb34a3d829123d92a8cf95f275089 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Fri, 20 Nov 2026 17:10:39 -0800 Subject: [PATCH 47/90] ADFA-7139 AI-Agent-MCP: a call that outlives its entry's removal leaves no session or health behind From brief 6 (ADFA-7131 comment 41407), L6 (low). The read that removes a SQLite debugger entry takes out its session (McpConnections.detach) and its health in the same step. A call or a listing still on its way looked its session up afterwards, and McpConnections.session stored a new one for the removed server, which nothing would close. Once answered, McpToolSource.runTool recorded McpServerHealth.available, bringing back a health row for a server that no longer exists. Both are now guarded with the isConfigured check that McpToolCatalog.connect and recordFailure already used, moved to McpServers.isConfigured so the three share it. session() makes the check under its own lock and returns a session it does not keep for a server no longer configured; the call goes on as before. The removal of an entry leaves the list before its detach takes that lock, so either the removal takes the session out or the lookup sees the entry gone. runTool records available only for a server still configured; like connect's, that check narrows the window rather than closing it. The README says a call or a listing still running when an entry goes leaves nothing behind. Not covered: a server of the user's is removed from the store after its session is ended (McpSettingsViewModel.delete calls invalidate first, so the DELETE still has the credentials), so a lookup between the two still stores one. A listing of a removed user server still writes its tool list to McpToolCatalog's cache (as before; outside this item). Test (RemovedDuringCallTest): a tool call to an entry is accepted, its worker is held on a latch before its first line, the entry is removed by a refresh, and the worker is released; the call is answered, and the entry has neither a session nor a health row afterwards. With only the session guard removed: "the call stored a session for the removed entry expected null, but was:<...McpSession@...>". With only the health guard removed: "the call brought back the removed entry's health expected null, but was:". Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- plugins/AI-Agent-MCP/README.md | 3 +- .../aiagentmcp/client/McpConnections.kt | 20 +++- .../aiagentmcp/debugger/AutomaticServers.kt | 6 ++ .../aiagentmcp/tools/McpToolCatalog.kt | 7 +- .../plugins/aiagentmcp/tools/McpToolSource.kt | 5 +- .../aiagentmcp/tools/RemovedDuringCallTest.kt | 102 ++++++++++++++++++ 6 files changed, 130 insertions(+), 13 deletions(-) create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/RemovedDuringCallTest.kt diff --git a/plugins/AI-Agent-MCP/README.md b/plugins/AI-Agent-MCP/README.md index 6401f2cee..7a344f6fe 100644 --- a/plugins/AI-Agent-MCP/README.md +++ b/plugins/AI-Agent-MCP/README.md @@ -61,7 +61,8 @@ port and token, and the plugin reads them again after a refused connection. An app that has not reported yet has no entry, and no error is shown. An app that stops reporting loses its entry, and the entry's tools, health and session go with it in the same step; if the app comes back before that step has finished -its cleanup, the new entry keeps its own. +its cleanup, the new entry keeps its own. A call or a listing still running +when the entry goes leaves no session or health behind for it. When the entry cannot reach its app, the reason the Agent tab shows says what to do, told apart by exception type (`SocketTimeoutException` or `ConnectException`, diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt index 76c7c4044..b2b642aea 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt @@ -2,6 +2,7 @@ package com.itsaky.androidide.plugins.aiagentmcp.client import android.util.Log import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticServers +import com.itsaky.androidide.plugins.aiagentmcp.debugger.McpServers import com.itsaky.androidide.plugins.aiagentmcp.errors.runCatchingRecoverable import com.itsaky.androidide.plugins.aiagentmcp.logging.LOG_PREFIX import com.itsaky.androidide.plugins.aiagentmcp.security.UnavailableSecretException @@ -44,6 +45,14 @@ object McpConnections { * * Reads the token and the headers, so call this off the main thread. * + * A server no longer configured gets a session that is not kept: the caller is a call or a + * listing that outlived the server's removal, and a session stored for it would outlive the + * server with nothing left to close it. The check is made under this object's lock, which the + * removal of a SQLite debugger entry takes, to detach its session, only after the entry has + * left the list; so either that removal takes the session out or this sees the entry gone. A + * server of the user's is removed from the store after its session is ended, so its DELETE + * still has the credentials; a lookup between the two still stores one. + * * @param server the server to connect to. * @return its session, not yet initialized. */ @@ -57,11 +66,12 @@ object McpConnections { val session = synchronized(this) { val current = sessions[server.id] if (current != null && current.first == key) return current.second - stale = current?.second // A supplier, not the values: the session is kept for the life of the process, and a // token in one of its fields would be readable in a heap dump for just as long. - McpSession(server.url, { credentialsFor(server.id, server.url) }) - .also { sessions[server.id] = key to it } + val fresh = McpSession(server.url, { credentialsFor(server.id, server.url) }) + if (!McpServers.isConfigured(server.id)) return fresh + stale = current?.second + fresh.also { sessions[server.id] = key to it } } stale?.let { @@ -82,8 +92,8 @@ object McpConnections { * `AutomaticServers` does, for an entry that went away, in the same step that removes it. * * Taken under this object's lock, as [session] replaces a session under it. Safe to call under - * another lock: nothing here calls out while holding this one, [session] reading the - * credentials before it takes it. + * another lock: under this one, [session] only reads the configured servers, which takes no + * lock (`McpServers.all`), and it reads the credentials before it takes this one. * * @return the session taken out, or null when [serverId] had none. */ diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt index 162b4df29..d52642739 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt @@ -325,4 +325,10 @@ object AutomaticServers { /** Every server the agent may use: the user's own plus the automatic entries. */ object McpServers { fun all(): List = McpServerStore.servers() + AutomaticServers.servers() + + /** + * Whether [serverId] is configured now: the check that keeps a call or a listing which outlived + * a server's removal from bringing back that server's session or health. + */ + fun isConfigured(serverId: String): Boolean = all().any { it.id == serverId } } diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt index d370ab6f6..c9be7c248 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt @@ -85,7 +85,7 @@ object McpToolCatalog { throw e } // Deleted while the handshake was in flight: recording it would resurrect its entry. - if (isConfigured(server.id)) McpServerHealth.available(server.id) + if (McpServers.isConfigured(server.id)) McpServerHealth.available(server.id) return listing } @@ -102,15 +102,12 @@ object McpToolCatalog { McpServerHealth.cancelConnecting(server.id) return } - if (!isConfigured(server.id)) return + if (!McpServers.isConfigured(server.id)) return val context = McpPlugin.getContext()?.androidContext val refused = failure is McpFailure.TokenRefused || failure is McpFailure.Forbidden McpServerHealth.degraded(server.id, McpErrorFormatter.format(context, server, error), refused) } - private fun isConfigured(serverId: String): Boolean = - McpServers.all().any { it.id == serverId } - /** The handshake-and-list itself; see [connect]. */ private fun list(server: McpServer, exchangeListener: McpExchangeListener): Listing { // Taken before the request: if the endpoint is replaced while this list is in flight, the diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt index 7b497a64a..74d483817 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt @@ -214,8 +214,9 @@ class McpToolSource internal constructor( // there and reads the flag again before it sends anything. McpConnections.session(target).callTool(tool.name, arguments, call.handle) } - // A reply of any kind, a tool's own failure included, means the server is answering. - McpServerHealth.available(server.id) + // A reply of any kind, a tool's own failure included, means the server is answering; + // unless it was removed while the call ran, when recording it would bring back its row. + if (McpServers.isConfigured(server.id)) McpServerHealth.available(server.id) Outcome(result.success, result.text, result.errorMessage) } catch (e: Throwable) { // Throwable, unlike the other host-facing catches in this plugin: this runs inside diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/RemovedDuringCallTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/RemovedDuringCallTest.kt new file mode 100644 index 000000000..84e3bd921 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/RemovedDuringCallTest.kt @@ -0,0 +1,102 @@ +package com.itsaky.androidide.plugins.aiagentmcp.tools + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticEndpoint +import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticServers +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import com.itsaky.androidide.plugins.services.ToolSourceRegistry +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import java.util.concurrent.CountDownLatch +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicReference +import org.junit.After +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * A tool call still on its way when its SQLite debugger entry goes away leaves nothing of that + * entry behind. + * + * The read that removes an entry takes out its session and its health. A call accepted before that + * looked its session up afterwards, which stored a new one for an entry that no longer exists, and + * once it was answered it marked the entry available again. Both are now skipped for a server that + * is no longer configured, as a listing already skipped recording its health. + * + * The worker is held on a latch before its first line while the entry is removed; nothing sleeps. + */ +class RemovedDuringCallTest { + + private val delegate = Executors.newSingleThreadExecutor() + private lateinit var server: FakeMcpServer + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + // The Keystore is not there on the JVM; nothing here reads a hand-added server's secrets. + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } returns KeystoreSecretStore.Stored.Absent + every { McpServerStore.headers(any()) } returns emptyMap() + // Answers whatever token it is sent: the removed entry's requests go out with none. + server = FakeMcpServer("", listOf(tool("query", true))) + } + + @After + fun tearDown() { + delegate.shutdownNow() + AutomaticServers.install(null) + McpConnections.closeAll() + McpToolCatalog.clear() + server.stop() + plugin.dispose() + unmockkObject(McpServerStore) + } + + @Test + fun `a call that outlives its entry's removal leaves no session and no health behind`() { + val stored = AtomicReference(listOf(AutomaticEndpoint("com.example.notes", server.port, "t"))) + AutomaticServers.install { stored.get() } + val entry = AutomaticServers.servers().single() + McpToolCatalog.connect(entry) + + val started = CountDownLatch(1) + val proceed = CountDownLatch(1) + val source = McpToolSource(delegate) { + started.countDown() + assertTrue("the test never released the worker", proceed.await(10, TimeUnit.SECONDS)) + } + val name = source.listTools().single().name + val future = source.invoke( + mockk { + every { toolName } returns name + every { arguments } returns emptyMap() + every { callId } returns "call-1" + } + ) + assertTrue("the worker never started", started.await(10, TimeUnit.SECONDS)) + + stored.set(emptyList()) + AutomaticServers.refresh() + assertNull("the removal left the entry's health", McpServerHealth.of(entry.id)) + proceed.countDown() + val outcome = future.get(10, TimeUnit.SECONDS) + + assertTrue("the call was not answered: ${outcome.errorMessage}", outcome.isSuccess) + assertNull("the call stored a session for the removed entry", McpConnections.detach(entry.id)) + assertNull("the call brought back the removed entry's health", McpServerHealth.of(entry.id)) + } +} From 0a61665230be823ddf12c78f8c35d8cbc1299933 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Fri, 20 Nov 2026 17:21:21 -0800 Subject: [PATCH 48/90] ADFA-7139 AI-Agent-MCP: a server's deeply nested reply fails with a reason instead of overflowing the stack From the brief 6 follow-ups, N1: the sibling of H2 (37faab4b). JsonRpc.parseReply handed a server's whole reply, with no size cap, to JSONObject / JSONArray, and McpSession.toMap converted the tool schemas in it recursively. Android's org.json recurses once per nesting level with no limit, so a reply nested thousands deep throws StackOverflowError. Nothing on the way catches one: McpSession.call catches Exception, Connect and McpToolCatalog.refreshAll catch Exception and LinkageError, and the plugin's coroutine backstop rethrows a VirtualMachineError. During Connect, the activation's first listing, the health probe or a relist it would end Code on the Go. On main, Connect (catch Exception) and the activation's refreshAll (catch Exception, in a coroutine with no handler) already let it through; the 20 s probe did not, since its bare runCatching swallowed every Throwable. In #166, 21944cf0 narrowed the probe's and the relist's guards to runCatchingRecoverable and made the backstop rethrow a VirtualMachineError, which extended the crash to them. 769bb4c2 and 08e9e677 did not touch this path (08e9e677 made the log-format case, H2). The depth scan moves from McpLogFormat into one shared helper, transport/JsonDepth (MAX = 100, unchanged rules: brackets inside strings do not count, a string starts only where a parser starts a value). parseReply runs it before any parser and throws JsonRpc.TooDeepException for a deeper document. McpSession.call turns that into an IOException, "The server's reply to '' nests arrays and objects more than 100 levels deep; it was not read.", so the call or listing fails like any other unreadable reply and the entry is marked degraded with that reason. toMap only ever sees a reply within the limit. McpLogFormat.json uses the same helper. The README's security note covers replies as well. Tests: - JsonRpcTest: a reply 10,000 deep is refused with TooDeepException before any parser runs; a well-formed reply nested one level past the limit is refused; one within the limit is read. - DeepReplyTest: a tools/list reply 10,000 deep fails listTools with the guard's message. - JsonDepthTest: the scan's rules, moved from McpLogFormatTest. With only the guard line in parseReply removed: the 10,000-deep JsonRpc test fails with "expected TooDeepException but was: " (the test JVM's org.json turns its own overflow into one), the one-past-the-limit test with "expected TooDeepException to be thrown, but nothing was thrown", and DeepReplyTest with "expected:<... [nests arrays and objects more than 100 levels deep; it was not read]> but was:<...[was not JSON-RPC: JSON Array or Object depth too large to process]>". Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- plugins/AI-Agent-MCP/README.md | 9 +-- .../plugins/aiagentmcp/client/McpSession.kt | 4 ++ .../plugins/aiagentmcp/errors/McpLogFormat.kt | 51 +--------------- .../plugins/aiagentmcp/transport/JsonDepth.kt | 55 +++++++++++++++++ .../plugins/aiagentmcp/transport/JsonRpc.kt | 10 ++++ .../aiagentmcp/client/DeepReplyTest.kt | 60 +++++++++++++++++++ .../aiagentmcp/errors/McpLogFormatTest.kt | 17 +----- .../aiagentmcp/transport/JsonDepthTest.kt | 38 ++++++++++++ .../aiagentmcp/transport/JsonRpcTest.kt | 28 +++++++++ 9 files changed, 206 insertions(+), 66 deletions(-) create mode 100644 plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepth.kt create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/DeepReplyTest.kt create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepthTest.kt diff --git a/plugins/AI-Agent-MCP/README.md b/plugins/AI-Agent-MCP/README.md index 7a344f6fe..2deaa0709 100644 --- a/plugins/AI-Agent-MCP/README.md +++ b/plugins/AI-Agent-MCP/README.md @@ -189,10 +189,11 @@ Two dependencies were deliberately not taken: is kept only in part, cut at a fixed length; when the cut falls inside a credential, what was kept of it is masked too, so the log never shows the start of one. -- The connection log indents a JSON body only when it nests arrays and objects - at most 100 levels deep, brackets inside strings not counted. A deeper one is - shown as it came: parsing recurses once per level, and a server's body of - nothing but `[` would run Code on the Go out of stack. +- A server's JSON is parsed only when it nests arrays and objects at most 100 + levels deep, brackets inside strings not counted (`JsonDepth`): parsing + recurses once per level, and a body of nothing but `[` would run Code on the + Go out of stack. A deeper reply fails its call or listing with that reason; a + deeper body in the connection log is shown as it came. - A `202 Accepted` body is read and thrown away, for at most 1 MiB of characters and 10 seconds; one that runs past either is abandoned and its socket disconnected, not reused. The worst case is the 10 seconds plus one read diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSession.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSession.kt index 8c93d096a..c4f54df32 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSession.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSession.kt @@ -296,6 +296,10 @@ class McpSession( val reply = try { JsonRpc.parseReply(document) + } catch (e: JsonRpc.TooDeepException) { + // Refused rather than parsed, so the call or listing fails with this reason instead of + // a StackOverflowError ending Code on the Go. + throw IOException("The server's reply to '$method' ${e.message}; it was not read.", e) } catch (e: Exception) { throw IOException("The server's reply to '$method' was not JSON-RPC: ${e.message}") } ?: throw IOException("The server's reply to '$method' carried no result.") diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormat.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormat.kt index 74d240296..4795f1cd6 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormat.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormat.kt @@ -1,5 +1,6 @@ package com.itsaky.androidide.plugins.aiagentmcp.errors +import com.itsaky.androidide.plugins.aiagentmcp.transport.JsonDepth import org.json.JSONArray import org.json.JSONObject @@ -16,13 +17,6 @@ object McpLogFormat { private const val JSON_INDENT = 2 - /** - * How deeply a body may nest arrays and objects and still be indented. Parsing recurses once - * per level, on Android with no limit of its own, so a server's body of nothing but `[` would - * run the thread out of stack; no MCP reply comes near this. - */ - internal const val MAX_JSON_DEPTH = 100 - private val STATUS_CODE = Regex("""\b([1-5]\d\d)\b""") /** @@ -63,55 +57,16 @@ object McpLogFormat { * [text] as indented JSON, or null when it is not JSON. An Exception or LinkageError from * [indent] is a body that is not JSON; any other Error, an OutOfMemoryError above all, propagates. * So would a StackOverflowError, which is why [text] never reaches [indent] when it nests - * deeper than [MAX_JSON_DEPTH]: it is shown as it came. + * deeper than [JsonDepth.MAX]: it is shown as it came. * @param indent the parsing and indenting; injectable so a test can make it fail. */ internal fun json(text: String, indent: (String) -> String? = ::indentJson): String? { - if (nestsDeeperThan(text, MAX_JSON_DEPTH)) return null + if (JsonDepth.exceeds(text)) return null val indented = runCatchingRecoverable { indent(text) }.getOrNull() // org.json escapes every '/', which turns each URL in a reply into noise. return indented?.replace("\\/", "/") } - /** - * Whether [text] opens more than [limit] arrays or objects one inside another; one pass, no - * recursion. A bracket inside a string does not count. - * - * A string starts only where a parser starts a value or a key: at a double or single quote - * (org.json reads both) that opens the text or follows `[`, `{`, `,` or `:`, past whitespace. - * A quote anywhere else, after a comment for instance, starts nothing here, so the brackets - * after it count. Erring that way only leaves a body unindented; erring the other way would - * let a parser recurse through brackets this scan took for text. - */ - internal fun nestsDeeperThan(text: String, limit: Int): Boolean { - var depth = 0 - var quote: Char? = null - var escaped = false - var valueStarts = true - for (c in text) { - if (quote != null) { - when { - escaped -> escaped = false - c == '\\' -> escaped = true - c == quote -> quote = null - } - continue - } - if (c == ' ' || c == '\t' || c == '\n' || c == '\r') continue - if ((c == '"' || c == '\'') && valueStarts) { - quote = c - valueStarts = false - continue - } - when (c) { - '[', '{' -> if (++depth > limit) return true - ']', '}' -> if (depth > 0) depth-- - } - valueStarts = c == '[' || c == '{' || c == ',' || c == ':' - } - return false - } - private fun indentJson(text: String): String? = when { text.startsWith("{") -> JSONObject(text).toString(JSON_INDENT) text.startsWith("[") -> JSONArray(text).toString(JSON_INDENT) diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepth.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepth.kt new file mode 100644 index 000000000..fd7818d8b --- /dev/null +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepth.kt @@ -0,0 +1,55 @@ +package com.itsaky.androidide.plugins.aiagentmcp.transport + +/** + * How deeply a server's JSON may nest arrays and objects before anything here parses it. + * + * org.json parses recursively, once per array or object, and Android's has no limit of its own: + * a body of nothing but `[` runs the thread out of stack, and the StackOverflowError ends Code on + * the Go, whose process this plugin runs in. So a server's text is scanned first, in one pass with + * no recursion, and text nested deeper than [MAX] is never handed to a parser: a reply is refused + * ([JsonRpc.parseReply]), and a body in the connection log is shown as it came. + */ +internal object JsonDepth { + + /** The deepest nesting read; no MCP reply comes near it. */ + const val MAX = 100 + + /** + * Whether [text] opens more than [limit] arrays or objects one inside another; one pass, no + * recursion. A bracket inside a string does not count. + * + * A string starts only where a parser starts a value or a key: at a double or single quote + * (org.json reads both) that opens the text or follows `[`, `{`, `,` or `:`, past whitespace. + * A quote anywhere else, after a comment for instance, starts nothing here, so the brackets + * after it count. Erring that way only refuses a body a parser could have read; erring the + * other way would let a parser recurse through brackets this scan took for text. + */ + fun exceeds(text: String, limit: Int = MAX): Boolean { + var depth = 0 + var quote: Char? = null + var escaped = false + var valueStarts = true + for (c in text) { + if (quote != null) { + when { + escaped -> escaped = false + c == '\\' -> escaped = true + c == quote -> quote = null + } + continue + } + if (c == ' ' || c == '\t' || c == '\n' || c == '\r') continue + if ((c == '"' || c == '\'') && valueStarts) { + quote = c + valueStarts = false + continue + } + when (c) { + '[', '{' -> if (++depth > limit) return true + ']', '}' -> if (depth > 0) depth-- + } + valueStarts = c == '[' || c == '{' || c == ',' || c == ':' + } + return false + } +} diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonRpc.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonRpc.kt index 7500c3dbf..5cd5bfeff 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonRpc.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonRpc.kt @@ -65,12 +65,18 @@ object JsonRpc { * A batch — which the spec allows and some servers send even for a single request — is reduced * to its first non-notification member, since this client only ever has one call in flight. * + * A document nested deeper than [JsonDepth.MAX] is refused before any parser sees it: parsing + * recurses once per level, and on Android a server's reply nested thousands deep would end in + * a StackOverflowError that nothing here may catch. + * * @param payload one JSON-RPC document, object or array. * @return the reply, or null when the payload is not a reply at all (a server-initiated * request or notification, which this client does not answer). + * @throws TooDeepException when [payload] nests deeper than [JsonDepth.MAX]. */ fun parseReply(payload: String): Reply? { val trimmed = payload.trim() + if (JsonDepth.exceeds(trimmed)) throw TooDeepException() val json = when { trimmed.startsWith("{") -> JSONObject(trimmed) trimmed.startsWith("[") -> org.json.JSONArray(trimmed).let { array -> @@ -115,4 +121,8 @@ object JsonRpc { return Reply(id = id, result = json.optJSONObject("result") ?: JSONObject()) } + + /** A reply [parseReply] refused unparsed, for nesting deeper than [JsonDepth.MAX]. */ + class TooDeepException : + IllegalArgumentException("nests arrays and objects more than ${JsonDepth.MAX} levels deep") } diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/DeepReplyTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/DeepReplyTest.kt new file mode 100644 index 000000000..e27a42fdb --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/DeepReplyTest.kt @@ -0,0 +1,60 @@ +package com.itsaky.androidide.plugins.aiagentmcp.client + +import com.itsaky.androidide.plugins.aiagentmcp.transport.JsonDepth +import com.itsaky.androidide.plugins.aiagentmcp.transport.McpExchangeListener +import com.itsaky.androidide.plugins.aiagentmcp.transport.McpHttpClient +import java.io.IOException +import java.net.HttpURLConnection +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertThrows +import org.junit.Test + +/** + * A server whose reply nests arrays thousands deep fails the listing with a reason, rather than + * running the thread out of stack. + * + * Android's org.json recurses once per level with no limit, and the StackOverflowError it throws + * is not caught on the way: during Connect, the activation's first listing or the health probe it + * would end Code on the Go. The reply is now refused before it is parsed. The org.json these tests + * run on fails such a parse with a JSONException of its own, so the message is what tells the + * guard's refusal apart. + */ +class DeepReplyTest { + + private fun session(listReply: String) = McpSession( + "http://127.0.0.1:1/mcp", + { McpCredentials("", emptyMap()) }, + object : McpHttpClient() { + override fun post( + url: String, + token: String, + body: JSONObject, + sessionId: String?, + protocolVersion: String?, + extraHeaders: Map, + onConnected: (HttpURLConnection) -> Unit, + beforeSend: () -> Unit, + exchangeListener: McpExchangeListener, + ): Response = when (body.optString("method")) { + "initialize" -> Response( + """{"jsonrpc":"2.0","id":${body.get("id")},"result":{"protocolVersion":"2026-07-28"}}""", + null, + ) + "tools/list" -> Response(listReply, null) + else -> Response(null, null) + } + }, + ) + + @Test + fun `a reply nested ten thousand deep fails the listing with the depth as its reason`() { + val failure = assertThrows(IOException::class.java) { session("[".repeat(10_000)).listTools() } + + assertEquals( + "The server's reply to 'tools/list' nests arrays and objects more than ${JsonDepth.MAX} " + + "levels deep; it was not read.", + failure.message, + ) + } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormatTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormatTest.kt index 2dcd457c7..7c7b982b1 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormatTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormatTest.kt @@ -1,5 +1,6 @@ package com.itsaky.androidide.plugins.aiagentmcp.errors +import com.itsaky.androidide.plugins.aiagentmcp.transport.JsonDepth import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNotNull @@ -107,13 +108,13 @@ class McpLogFormatTest { @Test fun givenNestingAtTheLimit_whenFormatted_thenItIsIndented() { - val depth = McpLogFormat.MAX_JSON_DEPTH + val depth = JsonDepth.MAX assertNotNull(McpLogFormat.json("[".repeat(depth) + "]".repeat(depth))) } @Test fun givenNestingOneLevelPastTheLimit_whenFormatted_thenItIsShownAsItCame() { - val depth = McpLogFormat.MAX_JSON_DEPTH + 1 + val depth = JsonDepth.MAX + 1 val body = "{\"a\":" + "[".repeat(depth - 1) + "]".repeat(depth - 1) + "}" assertNull(McpLogFormat.json(body)) @@ -129,18 +130,6 @@ class McpLogFormatTest { assertNotNull("brackets inside strings were counted", McpLogFormat.json(body)) } - @Test - fun givenADoubleQuoteInsideASingleQuotedString_whenScanned_thenTheBracketsAfterItCount() { - // org.json reads '"' as a one-character string, then recurses into the brackets after it. - assertTrue(McpLogFormat.nestsDeeperThan("['\"',${"[".repeat(200)}", 100)) - } - - @Test - fun givenAQuoteWhereNoValueStarts_whenScanned_thenTheBracketsAfterItCount() { - // Android's org.json skips the comment, so no string starts at its quote. - assertTrue(McpLogFormat.nestsDeeperThan("[/*\"*/${"[".repeat(200)}", 100)) - } - /** Descends once per opening bracket at the start of [text], as a recursive-descent parser does. */ private fun recursiveIndent(text: String): String? { fun descend(index: Int): Int = diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepthTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepthTest.kt new file mode 100644 index 000000000..6847a2b54 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepthTest.kt @@ -0,0 +1,38 @@ +package com.itsaky.androidide.plugins.aiagentmcp.transport + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The scan that keeps a server's deeply nested JSON from any parser. It may count too many + * brackets, which only refuses a body a parser could have read, never too few. + */ +class JsonDepthTest { + + @Test + fun `nesting at the limit passes and one level more does not`() { + val depth = JsonDepth.MAX + assertFalse(JsonDepth.exceeds("[".repeat(depth) + "]".repeat(depth))) + assertTrue(JsonDepth.exceeds("[".repeat(depth + 1) + "]".repeat(depth + 1))) + } + + @Test + fun `brackets inside strings do not count`() { + val brackets = "[".repeat(500) + // An escaped quote at the start of "b" and an escaped backslash at its end: neither ends it. + assertFalse(JsonDepth.exceeds("""{"a":"$brackets","b":"\"$brackets\\","c":['$brackets']}""")) + } + + @Test + fun `the brackets after a double quote inside a single-quoted string count`() { + // org.json reads '"' as a one-character string, then recurses into the brackets after it. + assertTrue(JsonDepth.exceeds("['\"',${"[".repeat(200)}", 100)) + } + + @Test + fun `the brackets after a quote where no value starts count`() { + // Android's org.json skips the comment, so no string starts at its quote. + assertTrue(JsonDepth.exceeds("[/*\"*/${"[".repeat(200)}", 100)) + } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonRpcTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonRpcTest.kt index 6082465d6..81f540244 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonRpcTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonRpcTest.kt @@ -3,6 +3,7 @@ package com.itsaky.androidide.plugins.aiagentmcp.transport import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows import org.junit.Assert.assertTrue import org.junit.Test @@ -102,4 +103,31 @@ class JsonRpcTest { assertNull(reply) } + + /** + * The org.json these tests run on turns a parse that runs out of stack into a JSONException; + * Android's lets the StackOverflowError through. The refusal must come from the guard, before + * either parser runs, so the type is what this asserts. + */ + @Test + fun givenAReplyNestedTenThousandDeep_whenParsed_thenItIsRefusedBeforeAnyParserRuns() { + assertThrows(JsonRpc.TooDeepException::class.java) { JsonRpc.parseReply("[".repeat(10_000)) } + } + + @Test + fun givenAWellFormedReplyNestedPastTheLimit_whenParsed_thenItIsRefused() { + val nested = "[".repeat(JsonDepth.MAX) + "]".repeat(JsonDepth.MAX) + val payload = """{"jsonrpc":"2.0","id":"7","result":{"tools":[],"extra":$nested}}""" + + assertThrows(JsonRpc.TooDeepException::class.java) { JsonRpc.parseReply(payload) } + } + + @Test + fun givenAReplyNestedWithinTheLimit_whenParsed_thenItIsRead() { + val depth = JsonDepth.MAX - 3 + val nested = "[".repeat(depth) + "]".repeat(depth) + val payload = """{"jsonrpc":"2.0","id":"7","result":{"extra":$nested}}""" + + assertEquals("7", JsonRpc.parseReply(payload)?.id) + } } From f1bf652e031779e0651f9a9462f619b8452a4441 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Fri, 20 Nov 2026 17:23:45 -0800 Subject: [PATCH 49/90] ADFA-7139 AI-Agent-MCP: a lifecycle call no longer waits behind a deactivation's session DELETEs From the brief 6 follow-ups: the L1 follow-up (2d28abab). Since L1, teardown() ran under lifecycleLock, and its releaseConnections() called McpConnections.closeAll() there. Each session's close sends a DELETE, and close() is synchronized with initialize(), whose notifications/initialized drain can hold the session for about 70 s (L2b). An activate(), or AI Core's registration of the tool source in the lifecycle listener, arriving meanwhile waited behind every DELETE. Before L1 they did not. Under the lock, teardown now only takes the sessions out (McpConnections.detachAll, new: empties the map under its own lock and returns what it held) into releasedSessions, beside closing and clearing the tool source, unregistering it and clearing the catalogue as before. activate, deactivate and dispose each end the sessions they released once they have let go of the lock (closeReleasedSessions, best effort per session as closeAll was). dispose ends them before it clears the plugin context, which the DELETE reads the credentials through. The L1 guarantee is unchanged: the tool source is still closed, cleared and unregistered under the lock, so a closed source is never registered. Tests: - LifecycleSessionCloseTest: a configured server assigns a session id and holds its DELETE on a latch; while deactivate() waits on that DELETE, activate() on another thread runs to its end rather than blocking on a lock the deactivating thread holds. - ConcurrentLifecycleTest's two tests still pass; their thread-state wait moves to testing/ThreadStates.kt so both tests share it. With only the session close moved back under the lock (releaseConnections calling McpConnections.closeAll() again): LifecycleSessionCloseTest fails with "activate waited for the deactivation's DELETE expected: but was:". Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../aiagentmcp/client/McpConnections.kt | 14 +- .../plugins/aiagentmcp/plugin/McpPlugin.kt | 69 +++++++--- .../plugin/ConcurrentLifecycleTest.kt | 21 +-- .../plugin/LifecycleSessionCloseTest.kt | 123 ++++++++++++++++++ .../aiagentmcp/testing/ThreadStates.kt | 26 ++++ 5 files changed, 212 insertions(+), 41 deletions(-) create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/LifecycleSessionCloseTest.kt create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/testing/ThreadStates.kt diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt index b2b642aea..9e91cbd75 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt @@ -101,8 +101,18 @@ object McpConnections { /** Ends every session, for the plugin shutting down. */ fun closeAll() { - sessions.values.forEach { (_, session) -> runCatchingRecoverable { session.close() } } - sessions.clear() + detachAll().forEach { session -> runCatchingRecoverable { session.close() } } + } + + /** + * Takes every session out without ending it, as [detach] does one: for a caller that empties + * the map under a lock of its own and ends the sessions once that lock is let go, since each + * `close()` sends a DELETE and can wait for a handshake in flight. + * + * @return the sessions taken out. + */ + fun detachAll(): List = synchronized(this) { + sessions.values.map { it.second }.also { sessions.clear() } } /** diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt index 0eb3c17ea..ea73162e5 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt @@ -6,6 +6,7 @@ import com.itsaky.androidide.plugins.PluginContext import com.itsaky.androidide.plugins.PluginLifecycleListener import com.itsaky.androidide.plugins.aiagentmcp.R import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.client.McpSession import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticServers import com.itsaky.androidide.plugins.aiagentmcp.debugger.McpServers import com.itsaky.androidide.plugins.aiagentmcp.errors.runCatchingRecoverable @@ -71,13 +72,21 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { * with a RejectedExecutionException. Every swap of [scope] takes it too: cancelling the old * scope and installing a new one is one transition, not two. * - * Nothing taken under it waits for this plugin's own work: the host's listener and service - * registries do not call back, and the coroutines it cancels never take it. A transition can - * still wait for the network, since [teardown] ends every session with a DELETE; a lifecycle - * call arriving meanwhile waits with it. + * Nothing taken under it waits for this plugin's own work or for the network: the host's + * listener and service registries do not call back, the coroutines it cancels never take it, + * and [teardown] only takes the sessions out ([releasedSessions]). Each lifecycle call ends + * them once it has let go: a session's `close()` sends a DELETE and can first wait, up to about + * 70 s, for a handshake in flight to let go of the session, and a lifecycle call or AI Core's + * registration arriving meanwhile must not wait behind it. */ private val lifecycleLock = Any() + /** + * Sessions [teardown] took out under [lifecycleLock], for the lifecycle call that ran it to end + * once it has let go ([closeReleasedSessions]). Guarded by [lifecycleLock]. + */ + private val releasedSessions = mutableListOf() + /** * Background work: listing tools is network work and never belongs on the main thread. * @@ -238,7 +247,12 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { return true } - override fun activate(): Boolean = synchronized(lifecycleLock) { activateLocked() } + override fun activate(): Boolean { + val activated = synchronized(lifecycleLock) { activateLocked() } + // A failed activation tears down what it started, sessions included. + closeReleasedSessions() + return activated + } /** [activate] itself, under [lifecycleLock]. */ private fun activateLocked(): Boolean = try { @@ -303,30 +317,44 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { return false } - override fun deactivate(): Boolean = synchronized(lifecycleLock) { - try { - teardown() - true - } catch (e: Exception) { - context.logger.error("McpPlugin: deactivation failed", e) - false + override fun deactivate(): Boolean { + val deactivated = synchronized(lifecycleLock) { + try { + teardown() + true + } catch (e: Exception) { + context.logger.error("McpPlugin: deactivation failed", e) + false + } } + closeReleasedSessions() + return deactivated } override fun dispose() { - synchronized(lifecycleLock) { - teardown() - pluginContext = null - } + synchronized(lifecycleLock) { teardown() } + // Before the context goes: a session's DELETE reads its credentials through it. + closeReleasedSessions() + pluginContext = null context.logger.info("McpPlugin: disposed") } + /** + * Ends the sessions [teardown] took out, each with a DELETE, best effort. Called by each + * lifecycle call once it has let go of [lifecycleLock], never under it; see there. + */ + private fun closeReleasedSessions() { + val closing = synchronized(lifecycleLock) { releasedSessions.toList().also { releasedSessions.clear() } } + for (session in closing) runCatchingRecoverable { session.close() } + } + /** * Stops what [activate] started: the lifecycle and change listeners, the tool source's * registration, the scope with its work, and the connections. The one teardown path, shared by * [deactivate], [dispose] and a failed [activate], so the three cannot drift apart. Safe to run * on an activation that got only part of the way, and on none at all. Each caller holds - * [lifecycleLock]; taken here too, so a new caller cannot forget it. + * [lifecycleLock]; taken here too, so a new caller cannot forget it. The sessions are only taken + * out here; the lifecycle call ends them after it has let go ([closeReleasedSessions]). */ private fun teardown() = synchronized(lifecycleLock) { // Guarded: a host whose plugin-api differs answers with a LinkageError, and one escaping @@ -527,11 +555,14 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { registered = false } - /** Closes every session and forgets the cached tool lists. */ + /** + * Closes the tool source, takes every session out for [closeReleasedSessions], and forgets the + * cached tool lists. Under [lifecycleLock], with [teardown]. + */ private fun releaseConnections() { toolSource?.close() toolSource = null - McpConnections.closeAll() + releasedSessions += McpConnections.detachAll() McpToolCatalog.clear() AutomaticServers.install(null) } diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/ConcurrentLifecycleTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/ConcurrentLifecycleTest.kt index de8748656..c3b0c8bca 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/ConcurrentLifecycleTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/ConcurrentLifecycleTest.kt @@ -3,12 +3,12 @@ package com.itsaky.androidide.plugins.aiagentmcp.plugin import com.itsaky.androidide.plugins.PluginContext import com.itsaky.androidide.plugins.PluginLifecycleListener import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.aiagentmcp.testing.awaitFinishedOrBlockedBy import com.itsaky.androidide.plugins.services.SharedServices import com.itsaky.androidide.plugins.services.ToolSourceRegistry import io.mockk.every import io.mockk.mockk import io.mockk.slot -import java.lang.management.ManagementFactory import java.util.concurrent.CopyOnWriteArrayList import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit @@ -119,25 +119,6 @@ class ConcurrentLifecycleTest { assertEquals("a tool source is still registered after the deactivate", 0, registered.size) } - /** - * Waits until [waiter] has finished, or is blocked entering a monitor that [holder] holds. - * Without the lock the deactivation runs straight to its end; with it, it blocks on the lock - * the registering thread holds. Either way the wait ends without depending on how long anything - * takes. - */ - private fun awaitFinishedOrBlockedBy(waiter: Thread, holder: Thread) { - val threads = ManagementFactory.getThreadMXBean() - val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10) - while (System.nanoTime() < deadline) { - if (waiter.state == Thread.State.TERMINATED) return - if (waiter.state == Thread.State.BLOCKED && threads.getThreadInfo(waiter.id)?.lockOwnerId == holder.id) { - return - } - Thread.yield() - } - throw AssertionError("${waiter.name} neither finished nor waited for ${holder.name}: ${waiter.state}") - } - private companion object { const val AI_CORE_PLUGIN_ID = "com.itsaky.androidide.plugins.aicore" } diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/LifecycleSessionCloseTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/LifecycleSessionCloseTest.kt new file mode 100644 index 000000000..06f4ee1ca --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/LifecycleSessionCloseTest.kt @@ -0,0 +1,123 @@ +package com.itsaky.androidide.plugins.aiagentmcp.plugin + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.aiagentmcp.testing.awaitFinishedOrBlockedBy +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpToolCatalog +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import com.itsaky.androidide.plugins.services.ToolSourceRegistry +import com.sun.net.httpserver.HttpServer +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import java.net.InetSocketAddress +import java.util.concurrent.CountDownLatch +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import kotlin.concurrent.thread +import org.json.JSONArray +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * A deactivation ends its sessions after it has let go of the lifecycle lock, so an activation + * arriving meanwhile does not wait for them. + * + * Each session's close sends a DELETE, and can first wait, up to about 70 s, for a handshake in + * flight to let go of the session. The teardown used to close the sessions under the lock that + * serialises the lifecycle calls, so an activate, or AI Core's registration of the tool source, + * waited behind every DELETE. The teardown now only takes the sessions out under it. + * + * The server holds the DELETE on a latch; the activation runs on another thread, and the test + * waits until it has finished or is blocked on a lock the deactivating thread holds. Nothing + * sleeps. + */ +class LifecycleSessionCloseTest { + + private val deleteArrived = CountDownLatch(1) + private val releaseDelete = CountDownLatch(1) + + private val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply { + // Its own threads, so the held DELETE does not hold the next activation's listing. + executor = Executors.newCachedThreadPool() + createContext("/mcp") { exchange -> + if (exchange.requestMethod == "DELETE") { + deleteArrived.countDown() + releaseDelete.await(10, TimeUnit.SECONDS) + exchange.sendResponseHeaders(200, -1) + exchange.close() + return@createContext + } + val request = JSONObject(exchange.requestBody.use { String(it.readBytes()) }) + if (!request.has("id")) { + exchange.sendResponseHeaders(202, -1) + } else { + val result = when (request.optString("method")) { + "initialize" -> JSONObject().put("protocolVersion", "2025-06-18") + else -> JSONObject().put("tools", JSONArray()) + } + val bytes = JSONObject().put("jsonrpc", "2.0").put("id", request.get("id")) + .put("result", result).toString().toByteArray() + exchange.responseHeaders.add("Content-Type", "application/json") + exchange.responseHeaders.add("Mcp-Session-Id", "session-1") + exchange.sendResponseHeaders(200, bytes.size.toLong()) + exchange.responseBody.use { it.write(bytes) } + } + exchange.close() + } + start() + } + + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + every { context.getPluginService(any(), ToolSourceRegistry::class.java) } returns null + plugin = McpPlugin().also { it.initialize(context) } + // The Keystore is not there on the JVM. + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } returns KeystoreSecretStore.Stored.Absent + every { McpServerStore.headers(any()) } returns emptyMap() + } + + @After + fun tearDown() { + releaseDelete.countDown() + plugin.dispose() + McpConnections.closeAll() + McpToolCatalog.clear() + server.stop(0) + unmockkObject(McpServerStore) + } + + @Test + fun `an activate arriving while a deactivation ends its sessions does not wait for them`() { + val saved = McpServerStore.saveDetails( + McpServerStore.newServer("Docs", "http://127.0.0.1:${server.address.port}/mcp") + ) + plugin.activate() + // A session with a server-side id, so ending it sends the DELETE the server holds. + McpConnections.session(saved).initialize() + + val deactivating = thread(name = "deactivating") { plugin.deactivate() } + assertTrue("the deactivation never sent its DELETE", deleteArrived.await(10, TimeUnit.SECONDS)) + val activating = thread(name = "activating") { plugin.activate() } + val state = awaitFinishedOrBlockedBy(activating, deactivating) + releaseDelete.countDown() + activating.join(10_000) + deactivating.join(10_000) + + assertEquals("activate waited for the deactivation's DELETE", Thread.State.TERMINATED, state) + assertFalse("deactivate never finished", deactivating.isAlive) + } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/testing/ThreadStates.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/testing/ThreadStates.kt new file mode 100644 index 000000000..6ded4486a --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/testing/ThreadStates.kt @@ -0,0 +1,26 @@ +package com.itsaky.androidide.plugins.aiagentmcp.testing + +import java.lang.management.ManagementFactory +import java.util.concurrent.TimeUnit + +/** + * Waits until [waiter] has finished, or is blocked entering a monitor that [holder] holds. A test + * that lets one thread run into another's lock uses this to tell the two outcomes apart without + * depending on how long anything takes. + * + * @return the state [waiter] was found in: TERMINATED or BLOCKED. + * @throws AssertionError when neither happens within ten seconds. + */ +fun awaitFinishedOrBlockedBy(waiter: Thread, holder: Thread): Thread.State { + val threads = ManagementFactory.getThreadMXBean() + val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10) + while (System.nanoTime() < deadline) { + val state = waiter.state + if (state == Thread.State.TERMINATED) return state + if (state == Thread.State.BLOCKED && threads.getThreadInfo(waiter.id)?.lockOwnerId == holder.id) { + return state + } + Thread.yield() + } + throw AssertionError("${waiter.name} neither finished nor waited for ${holder.name}: ${waiter.state}") +} From 9a82af5c7ee8e3064773a229812f66652d0f12d2 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Fri, 20 Nov 2026 17:26:10 -0800 Subject: [PATCH 50/90] ADFA-7139 AI-Agent-MCP: deleting a server leaves no session that a call stored meanwhile From the brief 6 follow-ups: the L6 sibling for the user's own servers (9ccbd92a). McpSettingsViewModel.delete ended the server's session, then removed the server from the store, then forgot its tools. The session is ended first on purpose: removing the server deletes its token and headers, and the DELETE reads them. A call or a listing that looked the session up between the two steps stored a new one, since the server was still configured, and once the server was gone nothing would end it. The deletion now ends the session a second time once the server is gone. L6's guard in McpConnections.session keeps no session for a server no longer configured, so no lookup after the removal stores one, and the second invalidate catches the one a lookup stored in between. Its DELETE goes without credentials (they were deleted with the server), best effort. Removing from the store first was not taken: the first DELETE would then lose its credentials too. The steps move into deleteNow, the blocking part delete() runs on Dispatchers.IO, so a test can drive them. The listing that writes a removed server's tools to the cache is outside brief 6 and unchanged. Test (DeleteServerSessionTest): a lookup of the server's session is made from inside the store's removal, just before it runs, which stores a new session; after deleteNow the server has no session. With only the second invalidate removed: "a session stored during the deletion outlived the server expected null, but was:<...McpSession@...>". Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../aiagentmcp/client/McpConnections.kt | 3 +- .../settings/McpSettingsViewModel.kt | 25 ++++-- .../settings/DeleteServerSessionTest.kt | 78 +++++++++++++++++++ 3 files changed, 99 insertions(+), 7 deletions(-) create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/DeleteServerSessionTest.kt diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt index 9e91cbd75..35d1a767f 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt @@ -51,7 +51,8 @@ object McpConnections { * removal of a SQLite debugger entry takes, to detach its session, only after the entry has * left the list; so either that removal takes the session out or this sees the entry gone. A * server of the user's is removed from the store after its session is ended, so its DELETE - * still has the credentials; a lookup between the two still stores one. + * still has the credentials; the settings pane ends whatever a lookup stored between the two + * once the server is gone. * * @param server the server to connect to. * @return its session, not yet initialized. diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt index eaf2e2051..4b6d60031 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt @@ -217,16 +217,29 @@ class McpSettingsViewModel( */ fun delete(id: String) { viewModelScope.launch { - withContext(Dispatchers.IO) { - McpConnections.invalidate(id) - // Removed first, so a probe finishing in between sees it gone and records nothing. - McpServerStore.remove(id) - McpToolCatalog.forget(id) - } + withContext(Dispatchers.IO) { deleteNow(id) } reload() } } + /** + * [delete]'s blocking part, off the main thread. + * + * The session is ended before the server is removed, so its DELETE still has the credentials + * the removal deletes. A call or a listing that looked the session up between the two stored + * a new one, which would outlive the server; it is ended again once the server is gone, when + * no lookup stores one any more (McpConnections.session keeps none for a server no longer + * configured). That second DELETE goes without credentials, best effort. + */ + internal fun deleteNow(id: String) { + McpConnections.invalidate(id) + // Removed before the tools are forgotten, so a probe finishing in between sees it gone and + // records nothing. + McpServerStore.remove(id) + McpConnections.invalidate(id) + McpToolCatalog.forget(id) + } + /** * Switches a whole server on or off. * @param id the server. diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/DeleteServerSessionTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/DeleteServerSessionTest.kt new file mode 100644 index 000000000..f7d680b9f --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/DeleteServerSessionTest.kt @@ -0,0 +1,78 @@ +package com.itsaky.androidide.plugins.aiagentmcp.settings + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpToolCatalog +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import org.junit.After +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * Deleting one of the user's servers leaves no session behind, even one a call stored while the + * deletion ran. + * + * The deletion ends the server's session first, so the DELETE still has the credentials that + * removing the server deletes. A call or a listing that looked the session up between the two + * stored a new one, for a server that was then gone, and nothing would ever end it. The session + * is now ended again once the server is gone. + * + * The lookup is made from inside the store's removal, just before it runs: the one point between + * the two steps. Nothing sleeps. + */ +class DeleteServerSessionTest { + + private lateinit var server: FakeMcpServer + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + // The Keystore is not there on the JVM. + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } returns KeystoreSecretStore.Stored.Absent + every { McpServerStore.headers(any()) } returns emptyMap() + server = FakeMcpServer("", listOf(tool("search", true)), sessionId = "session-1") + } + + @After + fun tearDown() { + McpConnections.closeAll() + McpToolCatalog.clear() + server.stop() + plugin.dispose() + unmockkObject(McpServerStore) + } + + @Test + fun `a session stored while the server was being deleted is ended with it`() { + val saved = McpServerStore.saveDetails( + McpServerStore.newServer("Docs", "http://127.0.0.1:${server.port}/mcp") + ) + McpConnections.session(saved).initialize() + var lookedUp = false + every { McpServerStore.remove(saved.id) } answers { + // A call landing between the two steps: its lookup stores a session for the server. + McpConnections.session(saved) + lookedUp = true + callOriginal() + } + + McpSettingsViewModel { null }.deleteNow(saved.id) + + assertTrue("the removal never ran", lookedUp) + assertNull("a session stored during the deletion outlived the server", McpConnections.detach(saved.id)) + } +} From 9d271cc0e95aac3ab5b69eafe6e17f6fbfa9748b Mon Sep 17 00:00:00 2001 From: David Schachter Date: Fri, 20 Nov 2026 18:59:03 -0800 Subject: [PATCH 51/90] ADFA-7139 AI-Agent-MCP: the DELETE ending a SQLite debugger entry's session carries its token again Found on the device (Note 20, integration build C-d-1121-0125, AI-Agent-MCP 9a82af5c): every session close logged "Closing session, server answered 401", on plugin disable and on closing the project. Earlier runs logged 204 for disable and uninstall (11-19 at f95d21e6, 11-20 at 3c308f96). The DELETE went out without the entry's bearer token, the app's MCP server refused it, and the server-side session stayed open. McpSession.close() read the credentials when it sent the DELETE, and on both paths the token was gone by then: - Deactivation (disable, uninstall): f1bf652e moved the session close out of the lifecycle lock. releaseConnections() then took the sessions out, cleared the entries (AutomaticServers.install(null)), and the closes ran afterwards. Before it (3c308f96 through 2d28abab), closeAll() ran before the entries were cleared. - An entry removed (the project closed, the app gone): never carried the token. Since the entry was added (6f2fde44) the removed entry's session is closed after `states = next`, when no token can be read for it; 185d360c kept that (no endpoint, no token) and 5e877ba3 moved the detach under the lock, still after `states = next`. 9ccbd92a (L6's isConfigured guard) only guards a lookup storing a session and does not touch the close. Run against 3c308f96, the new test passes for the deactivation and fails for the removal. The credentials are now read as each session is taken out, while they can still be read, and the DELETE later carries them: - McpSession.close(saved) closes with given credentials; close() still reads them itself. - McpConnections.detach and detachAll return Released: the session with its credentials, read once the session is out of the map, under the caller's lock (no network: an automatic entry's token is in memory, a user server's is a Keystore read). Released.close() ends it with them, best effort; credentials that could not be read are read again then. - McpConnections.detachRemoved, for an entry that has already left the list: AutomaticServers.readEndpoints passes the endpoint the entry had, and the token goes only to that endpoint's URL, the same rule as for a request. The detach stays after `states = next`, which L6's guarantee needs. - McpPlugin's releaseConnections takes the sessions out before it clears the entries, as it did; the closes still run after the lifecycle lock is let go, so f1bf652e's guarantee (no network under that lock) holds. - McpSettingsViewModel.deleteNow's second, best-effort DELETE (9a82af5c) carries the credentials read for the first one, not the empty ones left after the server is removed. Tests: - AutomaticSessionCloseTest (a FakeMcpServer that records each DELETE's Authorization): a deactivation's DELETE for an entry carries the entry's token; the DELETE when the entry's app goes away carries it too. - DeleteServerSessionTest: both DELETEs of a deleted server, including the one for the session a call stored meanwhile, carry its token. - LifecycleSessionCloseTest and ConcurrentLifecycleTest still pass. With main at 9a82af5c (every main file of this fix reverted): the two AutomaticSessionCloseTest tests fail with "the DELETE ending the entry's session expected:<[Bearer t1]> but was:<[null]>", and the new DeleteServerSessionTest test with "expected:<[Bearer ut, Bearer ut]> but was:<[Bearer ut, null]>". Not checked on a device. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- plugins/AI-Agent-MCP/README.md | 3 +- .../aiagentmcp/client/McpConnections.kt | 103 +++++++++++++++--- .../plugins/aiagentmcp/client/McpSession.kt | 16 ++- .../aiagentmcp/debugger/AutomaticServers.kt | 11 +- .../plugins/aiagentmcp/plugin/McpPlugin.kt | 11 +- .../settings/McpSettingsViewModel.kt | 7 +- .../plugin/AutomaticSessionCloseTest.kt | 101 +++++++++++++++++ .../settings/DeleteServerSessionTest.kt | 35 ++++++ 8 files changed, 256 insertions(+), 31 deletions(-) create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/AutomaticSessionCloseTest.kt diff --git a/plugins/AI-Agent-MCP/README.md b/plugins/AI-Agent-MCP/README.md index 2deaa0709..febd8695f 100644 --- a/plugins/AI-Agent-MCP/README.md +++ b/plugins/AI-Agent-MCP/README.md @@ -60,7 +60,8 @@ points the entry at `http://127.0.0.1:/mcp`. A relaunched app gets a new port and token, and the plugin reads them again after a refused connection. An app that has not reported yet has no entry, and no error is shown. An app that stops reporting loses its entry, and the entry's tools, health and session go -with it in the same step; if the app comes back before that step has finished +with it in the same step (the session ended with the entry's token, which the +app's server requires); if the app comes back before that step has finished its cleanup, the new entry keeps its own. A call or a listing still running when the entry goes leaves no session or health behind for it. diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt index 35d1a767f..0d54192fa 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt @@ -1,6 +1,7 @@ package com.itsaky.androidide.plugins.aiagentmcp.client import android.util.Log +import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticEndpoint import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticServers import com.itsaky.androidide.plugins.aiagentmcp.debugger.McpServers import com.itsaky.androidide.plugins.aiagentmcp.errors.runCatchingRecoverable @@ -82,38 +83,98 @@ object McpConnections { return session } + /** + * A session taken out of use, with the credentials its DELETE is to carry, read as it was taken + * out. It is ended later, outside the caller's lock, and by then the credentials may have gone + * with the server: a SQLite debugger entry's token leaves with its entry, a deleted server's + * with the server. Read at the DELETE they would be empty, and the server would refuse it and + * keep its session open. + * + * @property credentials what the DELETE carries; null when they could not be read, when + * [close] reads them again. + */ + class Released internal constructor( + private val session: McpSession, + internal val credentials: McpCredentials?, + ) { + /** + * Ends the session, best effort: sends a DELETE when it has a server-side id, so never under + * a lock. An Exception or a LinkageError is survived; any other Error propagates. + * + * @param credentials what the DELETE carries: the ones saved here, unless the caller holds + * better ones. + */ + fun close(credentials: McpCredentials? = this.credentials) { + runCatchingRecoverable { if (credentials != null) session.close(credentials) else session.close() } + } + } + /** Drops the session for [serverId], ending it server-side when it had one. */ fun invalidate(serverId: String) { - detach(serverId)?.let { runCatchingRecoverable { it.close() } } + detach(serverId)?.close() } /** - * Takes the session for [serverId] out without ending it, for a caller that must take it out - * under a lock of its own and end it once that lock is let go, since `close()` sends a DELETE. - * `AutomaticServers` does, for an entry that went away, in the same step that removes it. + * Takes the session for [serverId] out without ending it, with its credentials read now, for a + * caller that must take it out under a lock of its own and end it once that lock is let go, + * since ending it sends a DELETE. * - * Taken under this object's lock, as [session] replaces a session under it. Safe to call under - * another lock: under this one, [session] only reads the configured servers, which takes no - * lock (`McpServers.all`), and it reads the credentials before it takes this one. + * Taken under this object's lock, as [session] replaces a session under it. The credentials are + * read once that is let go, still under the caller's lock: for a server of the user's that is a + * Keystore read, never network. Safe to call under another lock: under this one, [session] only + * reads the configured servers, which takes no lock (`McpServers.all`), and it reads the + * credentials before it takes this one. * * @return the session taken out, or null when [serverId] had none. */ - fun detach(serverId: String): McpSession? = synchronized(this) { sessions.remove(serverId)?.second } + fun detach(serverId: String): Released? = release(serverId) { url -> credentialsFor(serverId, url) } + + /** + * As [detach], for a SQLite debugger entry that has already left the list, its app gone: its + * token can no longer be read, so it is taken from [endpoint], the one the entry had. As for a + * request, it goes only to the URL it belongs to. `AutomaticServers` does this, in the same step + * that removes the entry. + * + * @param endpoint the endpoint the entry had when it was removed. + */ + fun detachRemoved(serverId: String, endpoint: AutomaticEndpoint): Released? = + release(serverId) { url -> automaticCredentials(endpoint, url) } /** Ends every session, for the plugin shutting down. */ fun closeAll() { - detachAll().forEach { session -> runCatchingRecoverable { session.close() } } + detachAll().forEach { it.close() } } /** * Takes every session out without ending it, as [detach] does one: for a caller that empties * the map under a lock of its own and ends the sessions once that lock is let go, since each - * `close()` sends a DELETE and can wait for a handshake in flight. + * close sends a DELETE and can wait for a handshake in flight. * - * @return the sessions taken out. + * @return the sessions taken out, each with its credentials. */ - fun detachAll(): List = synchronized(this) { - sessions.values.map { it.second }.also { sessions.clear() } + fun detachAll(): List { + val taken = synchronized(this) { sessions.toMap().also { sessions.clear() } } + return taken.map { (id, entry) -> released(entry, id) { url -> credentialsFor(id, url) } } + } + + /** Takes [serverId]'s session out; see [detach]. */ + private fun release(serverId: String, credentials: (url: String) -> McpCredentials): Released? { + val entry = synchronized(this) { sessions.remove(serverId) } ?: return null + return released(entry, serverId, credentials) + } + + /** + * [entry]'s session with its credentials, read for the URL it was built for. A failed read + * leaves them unread: the close tries again, which beats not ending the session. + */ + private fun released( + entry: Pair, + serverId: String, + credentials: (url: String) -> McpCredentials, + ): Released { + val read = runCatchingRecoverable { credentials(entry.first.url) } + .onFailure { e -> Log.d(TAG, "Could not read the credentials to end '$serverId' with: $e") } + return Released(entry.second, read.getOrNull()) } /** @@ -135,9 +196,7 @@ object McpConnections { private fun credentialsFor(serverId: String, url: String): McpCredentials { if (AutomaticServers.isAutomatic(serverId)) { // Read per request, so a token refreshed on the same port is used without a new session. - val endpoint = AutomaticServers.endpoint(serverId) - val token = if (endpoint != null && AutomaticServers.urlFor(endpoint) == url) endpoint.token else "" - return McpCredentials(token, emptyMap()) + return automaticCredentials(AutomaticServers.endpoint(serverId), url) } val token = when (val stored = McpServerStore.token(serverId)) { // Trimmed here, not by the store: the host's readAndMigrate migrates verbatim, and a @@ -156,6 +215,18 @@ object McpConnections { return McpCredentials(token, McpServerStore.headers(serverId)) } + /** + * A SQLite debugger entry's credentials from [endpoint]: its token, but only while [url] is + * that endpoint's own, so a session for a replaced endpoint cannot hand the new process's token + * to the old port. + * @param endpoint the entry's endpoint, or null when it has none. + * @param url the URL the session was built for. + */ + private fun automaticCredentials(endpoint: AutomaticEndpoint?, url: String): McpCredentials { + val token = if (endpoint != null && AutomaticServers.urlFor(endpoint) == url) endpoint.token else "" + return McpCredentials(token, emptyMap()) + } + /** * What [server]'s session was built from, credentials included as digests. * diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSession.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSession.kt index c4f54df32..a02fa9767 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSession.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSession.kt @@ -218,11 +218,23 @@ class McpSession( * The DELETE is best effort; its credentials come from the host's Keystore, so a LinkageError * is survived as well as an Exception, and any other Error propagates. */ + fun close() = close(credentials) + + /** + * As [close], with credentials read earlier: for a session taken out of use while they could + * still be read, and ended once they may have gone with the server, as when a SQLite debugger + * entry is removed or the plugin deactivates. Read at the DELETE, they would be empty, and the + * server would refuse it and keep the session open. + * + * @param saved what the DELETE carries. + */ + fun close(saved: McpCredentials) = close { saved } + @Synchronized - fun close() { + private fun close(read: () -> McpCredentials) { sessionId?.let { id -> runCatchingRecoverable { - val current = credentials() + val current = read() http.deleteSession(endpoint, current.token, id, current.headers) } } diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt index d52642739..e6b04b98f 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt @@ -2,7 +2,6 @@ package com.itsaky.androidide.plugins.aiagentmcp.debugger import android.util.Log import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections -import com.itsaky.androidide.plugins.aiagentmcp.client.McpSession import com.itsaky.androidide.plugins.aiagentmcp.client.McpTool import com.itsaky.androidide.plugins.aiagentmcp.errors.runCatchingRecoverable import com.itsaky.androidide.plugins.aiagentmcp.logging.LOG_PREFIX @@ -165,7 +164,9 @@ object AutomaticServers { * out in the same step, under this object's lock: by ID they would also be the resources of an * entry a later read restores, so cleaning up after the lock was let go could take the health * and session of the app's new endpoint. Only the session taken out is closed, after the lock - * is let go, since closing it sends a DELETE; the health listeners are told then too. + * is let go, since closing it sends a DELETE; the health listeners are told then too. The DELETE + * carries the token the entry had, taken from the entry as it is removed: once it has left the + * list no token can be read for it, and the app's server refuses a DELETE without one. * * A read that fails with an Exception or a LinkageError leaves the entries as they were; any * other Error, an OutOfMemoryError above all, propagates to the caller. So does one from a @@ -214,7 +215,7 @@ object AutomaticServers { return false } val moved = mutableListOf() - val detached = mutableListOf() + val detached = mutableListOf() var healthForgotten = false val changed = synchronized(this) { if (source !== read || !keepGoing() || ticket < storedRead) return false @@ -236,12 +237,12 @@ object AutomaticServers { // so the health and session taken out are this entry's, never its successor's. // McpConnections takes its own lock inside this one and never calls in here under it. for (id in old.keys - next.keys) { - McpConnections.detach(id)?.let { detached += it } + McpConnections.detachRemoved(id, old.getValue(id).endpoint)?.let { detached += it } if (McpServerHealth.detach(id)) healthForgotten = true } old.mapValues { it.value.endpoint } != next.mapValues { it.value.endpoint } } - for (session in detached) runCatchingRecoverable { session.close() } + for (session in detached) session.close() if (healthForgotten) McpServerHealth.notifyChanged() for (id in moved) { // A refused credential is not final for this entry: the new one has not been tried. diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt index ea73162e5..0954cf339 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt @@ -6,7 +6,6 @@ import com.itsaky.androidide.plugins.PluginContext import com.itsaky.androidide.plugins.PluginLifecycleListener import com.itsaky.androidide.plugins.aiagentmcp.R import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections -import com.itsaky.androidide.plugins.aiagentmcp.client.McpSession import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticServers import com.itsaky.androidide.plugins.aiagentmcp.debugger.McpServers import com.itsaky.androidide.plugins.aiagentmcp.errors.runCatchingRecoverable @@ -83,9 +82,11 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { /** * Sessions [teardown] took out under [lifecycleLock], for the lifecycle call that ran it to end - * once it has let go ([closeReleasedSessions]). Guarded by [lifecycleLock]. + * once it has let go ([closeReleasedSessions]), each with the credentials read as it was taken + * out: [teardown] clears the SQLite debugger entries after, and an entry's token goes with it. + * Guarded by [lifecycleLock]. */ - private val releasedSessions = mutableListOf() + private val releasedSessions = mutableListOf() /** * Background work: listing tools is network work and never belongs on the main thread. @@ -345,7 +346,7 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { */ private fun closeReleasedSessions() { val closing = synchronized(lifecycleLock) { releasedSessions.toList().also { releasedSessions.clear() } } - for (session in closing) runCatchingRecoverable { session.close() } + for (session in closing) session.close() } /** @@ -562,6 +563,8 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { private fun releaseConnections() { toolSource?.close() toolSource = null + // Before the entries are cleared below: each session's credentials are read as it is taken + // out, and a SQLite debugger entry's token leaves with its entry. releasedSessions += McpConnections.detachAll() McpToolCatalog.clear() AutomaticServers.install(null) diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt index 4b6d60031..7d953e1b5 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt @@ -229,14 +229,15 @@ class McpSettingsViewModel( * the removal deletes. A call or a listing that looked the session up between the two stored * a new one, which would outlive the server; it is ended again once the server is gone, when * no lookup stores one any more (McpConnections.session keeps none for a server no longer - * configured). That second DELETE goes without credentials, best effort. + * configured). That second DELETE carries the credentials read for the first, best effort; + * none when there was no first session to read them for. */ internal fun deleteNow(id: String) { - McpConnections.invalidate(id) + val ended = McpConnections.detach(id)?.also { it.close() } // Removed before the tools are forgotten, so a probe finishing in between sees it gone and // records nothing. McpServerStore.remove(id) - McpConnections.invalidate(id) + McpConnections.detach(id)?.close(ended?.credentials) McpToolCatalog.forget(id) } diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/AutomaticSessionCloseTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/AutomaticSessionCloseTest.kt new file mode 100644 index 000000000..83b3e0a49 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/AutomaticSessionCloseTest.kt @@ -0,0 +1,101 @@ +package com.itsaky.androidide.plugins.aiagentmcp.plugin + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticEndpoint +import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticServers +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpToolCatalog +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import com.itsaky.androidide.plugins.services.DebuggerEndpointService +import com.itsaky.androidide.plugins.services.ToolSourceRegistry +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import java.util.concurrent.atomic.AtomicReference +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Before +import org.junit.Test + +/** + * The DELETE that ends a SQLite debugger entry's session carries the entry's token, whether the + * plugin is deactivated or the entry's app goes away, as when its project is closed. + * + * The app's MCP server refuses a DELETE without the token, and the session stays open. Both + * DELETEs read the token when they were sent, and by then it had gone: a deactivation clears the + * entries before it ends the sessions, outside its lock, and a removed entry has left the list + * before its session is ended. The token is now read as each session is taken out, from the entry + * as it is removed. + */ +class AutomaticSessionCloseTest { + + /** Asks for the token on every request but a DELETE, and records each with its Authorization. */ + private val server = FakeMcpServer(TOKEN, listOf(tool("query", true)), sessionId = "session-1") + + private val stored = AtomicReference(listOf(AutomaticEndpoint(APP, server.port, TOKEN))) + + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + // The entry is installed by the test, not read from the host. + every { context.services.get(DebuggerEndpointService::class.java) } returns null + every { context.getPluginService(any(), ToolSourceRegistry::class.java) } returns null + plugin = McpPlugin().also { it.initialize(context) } + // The Keystore is not there on the JVM; nothing here reads a hand-added server's secrets. + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } returns KeystoreSecretStore.Stored.Absent + every { McpServerStore.headers(any()) } returns emptyMap() + } + + @After + fun tearDown() { + AutomaticServers.install(null) + McpConnections.closeAll() + McpToolCatalog.clear() + plugin.dispose() + server.stop() + unmockkObject(McpServerStore) + } + + /** Installs the entry and lists it, which leaves it a session with a server-side id. */ + private fun connectEntry() { + AutomaticServers.install { stored.get() } + McpToolCatalog.connect(AutomaticServers.servers().single()) + } + + private fun deleteAuthorizations() = + server.requests.filter { it.httpMethod == "DELETE" }.map { it.authorization } + + @Test + fun `a deactivation's DELETE for a SQLite debugger entry carries the entry's token`() { + plugin.activate() + connectEntry() + + plugin.deactivate() + + assertEquals("the DELETE ending the entry's session", listOf("Bearer $TOKEN"), deleteAuthorizations()) + } + + @Test + fun `the DELETE when an entry's app goes away carries the entry's token`() { + connectEntry() + + stored.set(emptyList()) + AutomaticServers.refresh() + + assertEquals("the DELETE ending the entry's session", listOf("Bearer $TOKEN"), deleteAuthorizations()) + } + + private companion object { + const val APP = "com.example.notes" + const val TOKEN = "t1" + } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/DeleteServerSessionTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/DeleteServerSessionTest.kt index f7d680b9f..467fa9527 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/DeleteServerSessionTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/DeleteServerSessionTest.kt @@ -13,6 +13,7 @@ import io.mockk.mockk import io.mockk.mockkObject import io.mockk.unmockkObject import org.junit.After +import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Before @@ -75,4 +76,38 @@ class DeleteServerSessionTest { assertTrue("the removal never ran", lookedUp) assertNull("a session stored during the deletion outlived the server", McpConnections.detach(saved.id)) } + + /** + * The second DELETE, for the session a call stored meanwhile, goes out after the server's token + * was deleted with it; it carries the token read for the first one instead. + */ + @Test + fun `the second DELETE of a deleted server carries the credentials read for the first`() { + val guarded = FakeMcpServer("ut", listOf(tool("search", true)), sessionId = "session-2") + try { + var removed = false + every { McpServerStore.token(any()) } answers { + if (removed) KeystoreSecretStore.Stored.Absent else KeystoreSecretStore.Stored.Value("ut") + } + val saved = McpServerStore.saveDetails( + McpServerStore.newServer("Guarded", "http://127.0.0.1:${guarded.port}/mcp") + ) + McpConnections.session(saved).initialize() + every { McpServerStore.remove(saved.id) } answers { + // A call landing between the two steps: its session has a server-side id too. + McpConnections.session(saved).initialize() + callOriginal().also { removed = true } + } + + McpSettingsViewModel { null }.deleteNow(saved.id) + + assertEquals( + "the DELETEs ending the deleted server's two sessions", + listOf("Bearer ut", "Bearer ut"), + guarded.requests.filter { it.httpMethod == "DELETE" }.map { it.authorization }, + ) + } finally { + guarded.stop() + } + } } From 0f1ae4db90e9353e3fbb611eb4e5fbb53d896560 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Fri, 20 Nov 2026 20:58:52 -0800 Subject: [PATCH 52/90] ADFA-7139 AI-Agent-MCP: the depth guard reads strict JSON, so lenient syntax cannot hide brackets from it JsonDepth.exceeds took a quote for the start of a string only where a value starts, and counted every bracket after any other quote. A closing bracket it did not take for text still closed a level, so `[;"]";` repeated and `[//]` plus a newline repeated each net to depth 0 per unit, and the scan passed them at any length. The scan now reads strict JSON. Outside a string, `'`, `;`, `=`, `/` and `#` refuse the text, and a `"` opens a string where a value or a name starts and refuses the text anywhere else. That last rule goes beyond the brief: with every `"` opening a string, `[a",` followed by thousands of `[` would pass, since Android's parser reads `a"` as one unquoted string and the brackets after the comma as nested arrays. The scan at 9d271cc0 refused that payload; the new test keeps it refused. Valid JSON has none of these outside a string, so no MCP reply is refused. The two tests that used a single-quoted string as their example of brackets inside a string now use a double-quoted one; a single-quoted string has its own test, refused. Android's lenient parse of these payloads is inferred from libcore's JSONTokener source (`;` and `=` separators, comments, unquoted text that runs to the next delimiter, a quote included). It was not run on a device; the org.json these tests use rejects all of them, so only the scan's answer is tested. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- plugins/AI-Agent-MCP/README.md | 5 ++- .../plugins/aiagentmcp/transport/JsonDepth.kt | 45 +++++++++++-------- .../aiagentmcp/errors/McpLogFormatTest.kt | 2 +- .../aiagentmcp/transport/JsonDepthTest.kt | 36 ++++++++++++++- 4 files changed, 67 insertions(+), 21 deletions(-) diff --git a/plugins/AI-Agent-MCP/README.md b/plugins/AI-Agent-MCP/README.md index febd8695f..ef78cb891 100644 --- a/plugins/AI-Agent-MCP/README.md +++ b/plugins/AI-Agent-MCP/README.md @@ -194,7 +194,10 @@ Two dependencies were deliberately not taken: levels deep, brackets inside strings not counted (`JsonDepth`): parsing recurses once per level, and a body of nothing but `[` would run Code on the Go out of stack. A deeper reply fails its call or listing with that reason; a - deeper body in the connection log is shown as it came. + deeper body in the connection log is shown as it came. The scan reads strict + JSON and refuses the same way any text that is not: Android's org.json also + reads `;` and `=` separators, comments, single-quoted strings and unquoted + text, each a way to make it nest through brackets a strict scan took as text. - A `202 Accepted` body is read and thrown away, for at most 1 MiB of characters and 10 seconds; one that runs past either is abandoned and its socket disconnected, not reused. The worst case is the 10 seconds plus one read diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepth.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepth.kt index fd7818d8b..5b695c60f 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepth.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepth.kt @@ -15,40 +15,49 @@ internal object JsonDepth { const val MAX = 100 /** - * Whether [text] opens more than [limit] arrays or objects one inside another; one pass, no - * recursion. A bracket inside a string does not count. + * Whether [text] opens more than [limit] arrays or objects one inside another, or is not strict + * JSON where that could hide brackets; one pass, no recursion. A bracket inside a string does + * not count. * - * A string starts only where a parser starts a value or a key: at a double or single quote - * (org.json reads both) that opens the text or follows `[`, `{`, `,` or `:`, past whitespace. - * A quote anywhere else, after a comment for instance, starts nothing here, so the brackets - * after it count. Erring that way only refuses a body a parser could have read; erring the - * other way would let a parser recurse through brackets this scan took for text. + * The scan reads strict JSON, because Android's org.json is lenient: it also reads `;` as a + * separator, `=` and `=>` between a name and its value, `//`, `/* */` and `#` comments, single + * quoted strings, and unquoted text that runs up to the next delimiter, a `"` included. Each is + * a way for a parser to take a bracket as structure where a scan of strict JSON takes it as + * text, and so to recurse past [limit] through text this scan passed. So, outside a string: + * - `'`, `;`, `=`, `/` and `#` refuse the text: valid JSON has none of them there; + * - a `"` opens a string where a value or a name starts, at the start or after `[`, `{`, `,` or + * `:`, whitespace aside, and refuses the text anywhere else, where Android's parser reads it + * as part of unquoted text: `[a",[[[` is one array nested in another for it, however many + * brackets follow the quote. + * + * Valid JSON is never refused for these rules, so no MCP reply is. */ fun exceeds(text: String, limit: Int = MAX): Boolean { var depth = 0 - var quote: Char? = null + var inString = false var escaped = false - var valueStarts = true + // The last character outside a string and whitespace, or null at the start of the text. + var last: Char? = null for (c in text) { - if (quote != null) { + if (inString) { when { escaped -> escaped = false c == '\\' -> escaped = true - c == quote -> quote = null + c == '"' -> inString = false } continue } - if (c == ' ' || c == '\t' || c == '\n' || c == '\r') continue - if ((c == '"' || c == '\'') && valueStarts) { - quote = c - valueStarts = false - continue - } when (c) { + ' ', '\t', '\n', '\r' -> continue + '\'', ';', '=', '/', '#' -> return true + '"' -> { + if (last != null && last != '[' && last != '{' && last != ',' && last != ':') return true + inString = true + } '[', '{' -> if (++depth > limit) return true ']', '}' -> if (depth > 0) depth-- } - valueStarts = c == '[' || c == '{' || c == ',' || c == ':' + last = c } return false } diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormatTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormatTest.kt index 7c7b982b1..395965872 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormatTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormatTest.kt @@ -125,7 +125,7 @@ class McpLogFormatTest { fun givenBracketsInsideStrings_whenFormatted_thenTheyDoNotCount() { val brackets = "[".repeat(500) // An escaped quote at the start of "b" and an escaped backslash at its end: neither ends it. - val body = """{"a":"$brackets","b":"\"$brackets\\","c":['$brackets']}""" + val body = """{"a":"$brackets","b":"\"$brackets\\","c":["$brackets"]}""" assertNotNull("brackets inside strings were counted", McpLogFormat.json(body)) } diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepthTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepthTest.kt index 6847a2b54..93722f380 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepthTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepthTest.kt @@ -21,7 +21,41 @@ class JsonDepthTest { fun `brackets inside strings do not count`() { val brackets = "[".repeat(500) // An escaped quote at the start of "b" and an escaped backslash at its end: neither ends it. - assertFalse(JsonDepth.exceeds("""{"a":"$brackets","b":"\"$brackets\\","c":['$brackets']}""")) + assertFalse(JsonDepth.exceeds("""{"a":"$brackets","b":"\"$brackets\\","c":["$brackets"]}""")) + } + + @Test + fun `the characters refused outside a string are read as text inside one`() { + val brackets = "[".repeat(500) + val text = """{"a":"it's; a=b // c /* d */ # e","b":["'$brackets;=/#"],"c" : [ "x" , "y" ]}""" + assertFalse(JsonDepth.exceeds(text)) + } + + @Test + fun `a single-quoted string is refused`() { + // Not JSON; Android's org.json reads it, and a quote inside it hides nothing from that parser. + assertTrue(JsonDepth.exceeds("['a']")) + } + + @Test + fun `a semicolon separator hiding a closing bracket is refused`() { + // Android's org.json reads ';' as a separator and "]" as a string, so each unit opens one + // more array; a scan that took the quote for text counted each "]" as a close. + assertTrue(JsonDepth.exceeds("[;\"]\";".repeat(5_000))) + } + + @Test + fun `a comment hiding a closing bracket is refused`() { + // Android's org.json skips "//]" to the end of the line, so each unit opens one more array. + assertTrue(JsonDepth.exceeds("[//]\n".repeat(5_000))) + } + + @Test + fun `a quote inside unquoted text is refused`() { + // Android's org.json reads `a"` as one unquoted string, so the brackets after the comma + // are arrays nested in it, not text inside a string the quote opened. + assertTrue(JsonDepth.exceeds("[a\",${"[".repeat(5_000)}")) + assertTrue(JsonDepth.exceeds("""{"x":1",${"[".repeat(5_000)}""")) } @Test From da4209c9d690e405f77adb7a5ec9b5e8716bf885 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Fri, 20 Nov 2026 21:03:40 -0800 Subject: [PATCH 53/90] ADFA-7139 AI-Agent-MCP: a server moved to another URL no longer sends its new token to the old one McpSettingsViewModel.save stores the new URL, token and headers, then calls McpConnections.invalidate. The old session's DELETE read the server's credentials without asking which URL they were for, so it went to the old URL with the token and headers entered for the new one. So did a stale session closed in McpConnections.session and any request of the old session still running. credentialsFor now gives a server of the user's empty credentials unless the store still has it at the URL the session was built for: the rule automaticCredentials already applies to a SQLite debugger entry. The check comes before the Keystore read. Every caller goes through it: the DELETE on invalidate, the stale session's close, a request in flight, and the credentials Released saves as a session is taken out (read for the session's own URL, unchanged for a server that has not moved). The old session's DELETE now goes out with no credentials, and a server that requires them may refuse it and keep that session; that is the trade the rule makes. FakeMcpServer records the names of each request's headers, so the test can see that no user header went out. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- plugins/AI-Agent-MCP/README.md | 3 + .../aiagentmcp/client/McpConnections.kt | 13 ++- .../client/MovedServerCredentialTest.kt | 100 ++++++++++++++++++ .../aiagentmcp/testing/FakeMcpServer.kt | 13 ++- 4 files changed, 123 insertions(+), 6 deletions(-) create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/MovedServerCredentialTest.kt diff --git a/plugins/AI-Agent-MCP/README.md b/plugins/AI-Agent-MCP/README.md index ef78cb891..a664ffcb8 100644 --- a/plugins/AI-Agent-MCP/README.md +++ b/plugins/AI-Agent-MCP/README.md @@ -180,6 +180,9 @@ Two dependencies were deliberately not taken: version needs **26.48 or later**, the first release that ships `DebuggerEndpointService` (`plugin.min_ide_version`); users on 26.47 or older cannot install it. 26.48 assumes the release after 26.47 ships it; recheck it against the real release number before merging. +- A server's token and headers go only to the URL it is saved with. When the URL + is edited, the old session is ended, and any of its requests still running + finish, with neither: the token entered for the new URL never reaches the old. - Redirects are never followed automatically. A 3xx is repeated only when it resolves to the same origin, so the bearer token and the user's own headers cannot be replayed to another host in one hop. diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt index 0d54192fa..ac6404d89 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt @@ -184,9 +184,13 @@ object McpConnections { * does not register, and it is what keeps the plaintext from outliving the request. * * @param serverId the server being called. - * @param url the url the calling session was built for. An automatic entry's token is released - * only while the entry still points there; a session for a replaced endpoint gets none, so - * its `close()` and any call still in flight cannot hand the new process's token to the old port. + * @param url the url the calling session was built for. A server's credentials are released + * only while it still points there; a session for a URL it has left gets none, so its + * `close()` and any call still in flight cannot hand the credentials meant for the new URL + * to the old one. That holds for an automatic entry, whose replaced endpoint would get the + * new process's token, and for a server of the user's, whose old URL would get the token + * and headers the user entered for the new one: the settings pane stores them before it + * ends the old session. * @return its token and headers; either may be empty. * @throws UnreadableSecretException when a stored credential cannot be decrypted here. Sending * the request without it would earn a 401 and tell the user their token was refused. @@ -198,6 +202,9 @@ object McpConnections { // Read per request, so a token refreshed on the same port is used without a new session. return automaticCredentials(AutomaticServers.endpoint(serverId), url) } + // A server removed since, or moved to another URL, gets nothing; checked before the + // Keystore is read, so its secrets are not even decrypted. + if (McpServerStore.server(serverId)?.url != url) return McpCredentials("", emptyMap()) val token = when (val stored = McpServerStore.token(serverId)) { // Trimmed here, not by the store: the host's readAndMigrate migrates verbatim, and a // legacy token saved with a stray newline is one `setRequestProperty` refuses to send. diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/MovedServerCredentialTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/MovedServerCredentialTest.kt new file mode 100644 index 000000000..34eb8e8c3 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/MovedServerCredentialTest.kt @@ -0,0 +1,100 @@ +package com.itsaky.androidide.plugins.aiagentmcp.client + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServer +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpToolCatalog +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Before +import org.junit.Test + +/** + * A server of the user's moved to another URL never hands the credentials entered for the new URL + * to the old one. + * + * The settings pane stores the new URL, token and headers, and only then ends the old session. Its + * DELETE read the server's credentials without asking which URL they were for, so it went to the + * old URL with the new token and headers; so did any request of the old session still running. + * The credentials are now released only to a session built for the URL the server has, the rule a + * SQLite debugger entry already followed. + */ +class MovedServerCredentialTest { + + private val old = FakeMcpServer("", listOf(tool("search", true)), sessionId = "old-session") + private val moved = FakeMcpServer("new-token", listOf(tool("search", true))) + + @Volatile private var token = "old-token" + @Volatile private var headers = mapOf("X-Team" to "old") + + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + // The Keystore is not there on the JVM: the store answers what the user last entered. + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } answers { KeystoreSecretStore.Stored.Value(token) } + every { McpServerStore.headers(any()) } answers { headers } + } + + @After + fun tearDown() { + McpConnections.closeAll() + McpToolCatalog.clear() + old.stop() + moved.stop() + plugin.dispose() + unmockkObject(McpServerStore) + } + + @Test + fun `the old session's DELETE carries none of the credentials entered for the new URL`() { + val saved = McpServerStore.saveDetails(McpServerStore.newServer("Docs", url(old))) + McpConnections.session(saved).initialize() + assertEquals("the old session did not carry the old token", "Bearer old-token", old.requests.first().authorization) + + moveToTheNewUrl(saved) + McpConnections.invalidate(saved.id) + + val delete = old.requests.single { it.httpMethod == "DELETE" } + assertNull("the old URL was sent a token", delete.authorization) + assertFalse("the old URL was sent the user's headers", "x-team" in delete.headerNames) + } + + @Test + fun `a request of the old session after the move carries none of the new credentials`() { + val saved = McpServerStore.saveDetails(McpServerStore.newServer("Docs", url(old))) + val session = McpConnections.session(saved).also { it.initialize() } + + moveToTheNewUrl(saved) + session.listTools() + + val listing = old.requests.last() + assertEquals("POST", listing.httpMethod) + assertNull("the old URL was sent a token", listing.authorization) + assertFalse("the old URL was sent the user's headers", "x-team" in listing.headerNames) + } + + /** What the settings pane's save stores, before it ends the old session. */ + private fun moveToTheNewUrl(saved: McpServer) { + McpServerStore.saveDetails(saved.copy(url = url(moved))) + token = "new-token" + headers = mapOf("X-Team" to "new") + } + + private fun url(server: FakeMcpServer) = "http://127.0.0.1:${server.port}/mcp" +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/testing/FakeMcpServer.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/testing/FakeMcpServer.kt index c2c6383da..44092d8bd 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/testing/FakeMcpServer.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/testing/FakeMcpServer.kt @@ -22,14 +22,21 @@ class FakeMcpServer( private val sessionId: String? = null, ) { - /** One request as the server saw it. */ - data class Seen(val httpMethod: String, val authorization: String?) + /** + * One request as the server saw it. + * @property headerNames the names of every header it carried, in lower case. + */ + data class Seen(val httpMethod: String, val authorization: String?, val headerNames: Set = emptySet()) val requests = java.util.concurrent.CopyOnWriteArrayList() private val server: HttpServer = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply { createContext("/mcp") { exchange -> - requests += Seen(exchange.requestMethod, exchange.requestHeaders.getFirst("Authorization")) + requests += Seen( + exchange.requestMethod, + exchange.requestHeaders.getFirst("Authorization"), + exchange.requestHeaders.keys.mapTo(mutableSetOf()) { it.lowercase() }, + ) if (exchange.requestMethod == "DELETE") { exchange.sendResponseHeaders(200, -1) exchange.close() From 3ba9579cc258a0363bdfcd7304894e9586b89566 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Fri, 20 Nov 2026 21:04:08 -0800 Subject: [PATCH 54/90] ADFA-7139 AI-Agent-MCP: a cancel that lands while a request is written no longer lets it go out 00e27ffa made the request read its call's cancel flag once its connection was up, before the write. But without a streaming mode the write only fills a buffer: the request goes out when the answer is first read (trace.answered asks for responseCode). A cancel landing between that check and the read disconnected the connection, and the JDK connected again at the read and sent the request anyway. McpHttpClient.post now runs beforeSend again between the write and the read. A cancel after that last check still disconnects a connection that is up; the JDK reconnects then, and Android's OkHttp-based connection is expected to fail the read instead, which is inferred and was not run. The test cancels from inside the first check, once it has passed: the write and the read both come after the cancel. A real server records every request body it gets. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../aiagentmcp/client/McpCallHandle.kt | 13 ++- .../plugins/aiagentmcp/client/McpSession.kt | 4 +- .../aiagentmcp/transport/McpHttpClient.kt | 13 ++- .../aiagentmcp/client/CancelAfterCheckTest.kt | 108 ++++++++++++++++++ 4 files changed, 128 insertions(+), 10 deletions(-) create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/CancelAfterCheckTest.kt diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpCallHandle.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpCallHandle.kt index ebcf1407e..799c3c0d6 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpCallHandle.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpCallHandle.kt @@ -28,10 +28,12 @@ private const val TAG = "$LOG_PREFIX.McpCallHandle" * Finding the connection is not enough on its own: [attach] runs before the connection is * connected, and a `disconnect()` then does nothing (Android's and the JDK's both return early with * no connection to drop), so the first write would connect and send the request anyway. The - * request reads the flag a second time once its connection is up, before it writes anything - * ([throwIfCancelled]); a cancel between the two reads is caught there. One after the second read - * disconnects a connection that is up: Android then fails the write rather than sending it. (The - * JDK, which only the tests run on, reconnects instead.) + * request reads the flag a second time once its connection is up, before it writes anything, and a + * third time after the write, before it asks for the answer ([throwIfCancelled]): without a + * streaming mode the write only fills a buffer, and the request goes out with that first read of + * the answer. A cancel before the last read is caught there. One after it disconnects a connection + * that is up: Android's should then fail the request rather than send it, which is inferred, not + * run. (The JDK, which only the tests run on, reconnects instead.) */ class McpCallHandle { @@ -76,7 +78,8 @@ class McpCallHandle { /** * Reads the flag again, once the request's connection is connected and before anything is * written to it: a cancel that landed after [attach] read the flag disconnected a connection - * that was not connected yet, which does nothing. + * that was not connected yet, which does nothing. Read once more after the write, before the + * request goes out: the write only filled a buffer. * * @throws InterruptedIOException when the call was cancelled. */ diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSession.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSession.kt index a02fa9767..4ccbf476b 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSession.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSession.kt @@ -327,8 +327,8 @@ class McpSession( * * @param handle the calling tool call's: its connection is published there before anything is * sent, and the request is refused if the call was cancelled meanwhile, while the credentials - * were read for instance, or after that, before the connection was connected. Null for a - * listing, which no call's cancel reaches. + * were read for instance, or after that, before the connection was connected or while the + * body was written. Null for a listing, which no call's cancel reaches. */ private fun send(envelope: JSONObject, handle: McpCallHandle? = null): McpHttpClient.Response { // Read here rather than held on the session, so the plaintext lives for one request. diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt index 17ec2bae9..1dab432e3 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt @@ -170,9 +170,12 @@ open class McpHttpClient( * @param protocolVersion the negotiated revision, or null before `initialize` has answered. * @param onConnected receives each request's connection, redirect hops included, before it is * connected, so a caller can disconnect it to cancel. - * @param beforeSend runs once that connection is connected and before anything is written to - * it; what it throws ends the request unsent. A `disconnect()` before the connection exists - * does nothing, so a cancel landing just after [onConnected] is caught here or not at all. + * @param beforeSend runs once that connection is connected, before anything is written to it, + * and again once the body is written, before the answer is asked for; what it throws ends + * the request unsent. A `disconnect()` before the connection exists does nothing, so a cancel + * landing just after [onConnected] is caught here or not at all. Without a streaming mode the + * write only fills a buffer and the request goes out when the answer is first read, so the + * second run catches a cancel that landed during the write. * @param exchangeListener receives each request made and what came back, redirects included. * An Exception or a LinkageError it throws is dropped; any other Error propagates. * @return the reply document and any session id the server sent. @@ -219,6 +222,10 @@ open class McpHttpClient( conn.connect() beforeSend() conn.outputStream.use { it.write(bytes) } + // Again: the write only filled a buffer, and the request goes out at the first read + // of the answer, just below. A cancel that landed meanwhile disconnected a connection + // the JDK connects again at that read, sending the request after all. + beforeSend() trace.answered(conn) val next = conn.redirectTargetFrom(target) if (next == null) { diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/CancelAfterCheckTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/CancelAfterCheckTest.kt new file mode 100644 index 000000000..c20ecc266 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/CancelAfterCheckTest.kt @@ -0,0 +1,108 @@ +package com.itsaky.androidide.plugins.aiagentmcp.client + +import com.itsaky.androidide.plugins.aiagentmcp.transport.McpExchangeListener +import com.itsaky.androidide.plugins.aiagentmcp.transport.McpHttpClient +import com.sun.net.httpserver.HttpServer +import java.io.InterruptedIOException +import java.net.HttpURLConnection +import java.net.InetSocketAddress +import java.util.concurrent.CopyOnWriteArrayList +import org.json.JSONArray +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * A cancel that lands once the request has read its flag before the write sends nothing. + * + * Without a streaming mode the write only fills a buffer: the request goes out when the answer is + * first asked for. A cancel landing between the flag's read and that point disconnected the + * connection, and the JDK connected again at the write and sent the request when it was answered. + * The request now reads the flag once more after the write, before it asks for the answer. + * + * The cancel is made from inside that first read, just after it passed: the write, and the point + * where the request would go out, both come after it. The server counts the request bodies it gets. + */ +class CancelAfterCheckTest { + + /** The JSON-RPC method of every request body the server received, in order. */ + private val received = CopyOnWriteArrayList() + + private val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply { + createContext("/mcp") { exchange -> + val request = JSONObject(exchange.requestBody.use { String(it.readBytes()) }) + received += request.optString("method") + if (!request.has("id")) { + exchange.sendResponseHeaders(202, -1) + } else { + val result = when (request.optString("method")) { + "initialize" -> JSONObject().put("protocolVersion", "2025-06-18") + else -> JSONObject().put("content", JSONArray()) + } + val bytes = JSONObject().put("jsonrpc", "2.0").put("id", request.get("id")) + .put("result", result).toString().toByteArray() + exchange.responseHeaders.add("Content-Type", "application/json") + exchange.sendResponseHeaders(200, bytes.size.toLong()) + exchange.responseBody.use { it.write(bytes) } + } + exchange.close() + } + start() + } + + @After + fun tearDown() { + server.stop(0) + } + + @Test + fun `a cancel that lands after the check before the write sends nothing`() { + val handle = McpCallHandle() + val http = object : McpHttpClient() { + override fun post( + url: String, + token: String, + body: JSONObject, + sessionId: String?, + protocolVersion: String?, + extraHeaders: Map, + onConnected: (HttpURLConnection) -> Unit, + beforeSend: () -> Unit, + exchangeListener: McpExchangeListener, + ): Response { + var checks = 0 + return super.post( + url, + token, + body, + sessionId, + protocolVersion, + extraHeaders, + onConnected, + beforeSend = { + beforeSend() + // Here: the connection is up and the flag was read; the write comes next. + if (body.optString("method") == "tools/call" && checks++ == 0) handle.cancel() + }, + exchangeListener = exchangeListener, + ) + } + } + val session = McpSession( + "http://127.0.0.1:${server.address.port}/mcp", + { McpCredentials("", emptyMap()) }, + http, + ) + + val failure = runCatching { session.callTool("echo", emptyMap(), handle) }.exceptionOrNull() + + assertEquals( + "the cancelled call's request reached the server", + listOf("initialize", "notifications/initialized"), + received.toList(), + ) + assertTrue("the call did not end cancelled: $failure", failure is InterruptedIOException) + } +} From 6a9d0511dff13e36c88fe3df42702dc00e47ffe7 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Fri, 20 Nov 2026 21:05:16 -0800 Subject: [PATCH 55/90] ADFA-7139 AI-Agent-MCP: a request cancelled before it was sent is logged as cancelled, not as sent McpHttpClient built a request's record the same way whether it had gone out or not. A request that beforeSend ended was logged with its headers and body marked as sent ("> ..." in the copied transcript, a Request section in the log view), then "No response". McpExchange now carries `cancelled`, set when beforeSend ends the request. The transcript shows such a request as two "*" lines, its method and URL and "Cancelled before it was sent: nothing of it reached the server.", with no ">" line; the log view shows a "Cancelled" badge and that note in place of the request. Two new strings, in English only, as the plugin has no translations. Today only a tool call's requests can be cancelled, and only a listing's requests are recorded, so no log reaches this yet: it holds for the first caller that records a cancellable request. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../aiagentmcp/errors/McpTranscript.kt | 23 ++++-- .../settings/McpConnectionLogView.kt | 35 ++++++--- .../settings/McpTranscriptStrings.kt | 2 + .../aiagentmcp/transport/McpExchange.kt | 4 + .../aiagentmcp/transport/McpExchangeTrace.kt | 4 +- .../aiagentmcp/transport/McpHttpClient.kt | 19 ++++- .../src/main/res/values/strings.xml | 2 + .../aiagentmcp/errors/McpTranscriptTest.kt | 1 + .../transport/CancelledExchangeLogTest.kt | 75 +++++++++++++++++++ 9 files changed, 142 insertions(+), 23 deletions(-) create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/CancelledExchangeLogTest.kt diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpTranscript.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpTranscript.kt index a65fb649e..fdd852435 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpTranscript.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpTranscript.kt @@ -21,6 +21,9 @@ object McpTranscript { /** The transcript of a failure that never reached the network. */ val nothingSent: String + + /** The note on a request given up before it was sent; see [McpExchange.cancelled]. */ + val cancelled: String } /** @@ -77,13 +80,19 @@ object McpTranscript { exchanges.lastOrNull()?.failure == null && error !is McpHttpException private fun render(exchange: McpExchange, labels: Labels): String = buildList { - add("> ${exchange.method} ${exchange.url}") - addAll(headers(">", exchange.requestHeaders, labels)) - addAll(body(">", exchange.requestBody, labels)) - exchange.status?.let { status -> - add("< $status") - addAll(headers("<", exchange.responseHeaders, labels)) - exchange.responseBody?.let { addAll(body("<", it, labels)) } + if (exchange.cancelled) { + // Nothing of it went over the wire, so no line of it is marked as sent. + add("* ${exchange.method} ${exchange.url}") + add("* ${labels.cancelled}") + } else { + add("> ${exchange.method} ${exchange.url}") + addAll(headers(">", exchange.requestHeaders, labels)) + addAll(body(">", exchange.requestBody, labels)) + exchange.status?.let { status -> + add("< $status") + addAll(headers("<", exchange.responseHeaders, labels)) + exchange.responseBody?.let { addAll(body("<", it, labels)) } + } } exchange.failure?.let { add("* $it") } }.joinToString("\n") diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpConnectionLogView.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpConnectionLogView.kt index 6a2461e65..35cf5a1e8 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpConnectionLogView.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpConnectionLogView.kt @@ -59,12 +59,17 @@ class McpConnectionLogView( val context = card.context card.findViewById(R.id.mcpLogMethod).text = exchange.method card.findViewById(R.id.mcpLogUrl).text = exchange.url - status(card.findViewById(R.id.mcpLogStatus), exchange.status) + status(card.findViewById(R.id.mcpLogStatus), exchange) val sections = card.findViewById(R.id.mcpLogSections) - sections.addView(text(context, context.getString(R.string.mcp_log_request), Role.SECTION)) - addHeaders(sections, exchange.requestHeaders) - addBody(sections, exchange.requestBody) + if (exchange.cancelled) { + // Never sent, so no request is shown as if it had been. + sections.addView(text(context, labels.cancelled, Role.NOTE)) + } else { + sections.addView(text(context, context.getString(R.string.mcp_log_request), Role.SECTION)) + addHeaders(sections, exchange.requestHeaders) + addBody(sections, exchange.requestBody) + } if (exchange.status != null) { sections.addView(text(context, context.getString(R.string.mcp_log_response), Role.SECTION)) addHeaders(sections, exchange.responseHeaders) @@ -74,15 +79,23 @@ class McpConnectionLogView( return card } - private fun status(badge: TextView, status: String?) { + private fun status(badge: TextView, exchange: McpExchange) { val context = badge.context - val (container, content) = when (McpLogFormat.tone(status)) { - McpLogFormat.Tone.SUCCESS -> R.color.plugin_success_container to R.color.plugin_success - McpLogFormat.Tone.REDIRECT -> - R.color.plugin_secondary_container to R.color.plugin_on_secondary_container - McpLogFormat.Tone.ERROR -> R.color.plugin_error_container to R.color.plugin_on_error_container + val status = exchange.status + val (container, content) = when { + // A cancel is the caller's doing, not the server failing. + exchange.cancelled -> R.color.plugin_secondary_container to R.color.plugin_on_secondary_container + else -> when (McpLogFormat.tone(status)) { + McpLogFormat.Tone.SUCCESS -> R.color.plugin_success_container to R.color.plugin_success + McpLogFormat.Tone.REDIRECT -> + R.color.plugin_secondary_container to R.color.plugin_on_secondary_container + McpLogFormat.Tone.ERROR -> R.color.plugin_error_container to R.color.plugin_on_error_container + } + } + badge.text = when { + exchange.cancelled -> context.getString(R.string.mcp_log_cancelled) + else -> status?.let(McpLogFormat::badge) ?: context.getString(R.string.mcp_log_no_response) } - badge.text = status?.let(McpLogFormat::badge) ?: context.getString(R.string.mcp_log_no_response) badge.backgroundTintList = ColorStateList.valueOf(color(context, container)) badge.setTextColor(color(context, content)) } diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpTranscriptStrings.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpTranscriptStrings.kt index c8bb96cd9..eabbe63bc 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpTranscriptStrings.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpTranscriptStrings.kt @@ -16,6 +16,8 @@ class McpTranscriptStrings(private val context: Context?) : McpTranscript.Labels override val nothingSent: String get() = string(R.string.mcp_transcript_nothing_sent) + override val cancelled: String get() = string(R.string.mcp_transcript_cancelled) + private fun string(resId: Int, vararg args: Any): String = context?.getString(resId, *args).orEmpty() } diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpExchange.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpExchange.kt index e9afd518e..e70ea0a27 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpExchange.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpExchange.kt @@ -12,6 +12,9 @@ package com.itsaky.androidide.plugins.aiagentmcp.transport * @property responseHeaders the server's headers, in the order it sent them. * @property responseBody what the server sent back, or null when none was read. * @property failure what interrupted the exchange, or null when it ran to the end. + * @property cancelled the request was given up before it went out, as a cancelled tool call's is: + * nothing of it reached the server, and [requestHeaders] and [requestBody] are only what it + * would have carried. */ data class McpExchange( val method: String, @@ -22,6 +25,7 @@ data class McpExchange( val responseHeaders: List
, val responseBody: Body?, val failure: String?, + val cancelled: Boolean = false, ) { /** One header line. */ diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpExchangeTrace.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpExchangeTrace.kt index 29338c4fa..352ece7fa 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpExchangeTrace.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpExchangeTrace.kt @@ -67,8 +67,9 @@ internal class McpExchangeTrace( /** * The finished record. * @param failure what ended the request early, or null when it ran to the end. + * @param cancelled whether the request was given up before it went out; see [McpExchange.cancelled]. */ - fun toExchange(failure: Throwable?): McpExchange = McpExchange( + fun toExchange(failure: Throwable?, cancelled: Boolean = false): McpExchange = McpExchange( method = method, url = redactor.url(url), requestHeaders = headers.map { (name, value) -> redactor.requestHeader(name, value) } + @@ -79,5 +80,6 @@ internal class McpExchangeTrace( responseBody = responseBody, // The status line and body already say what an HTTP error was. failure = failure?.takeUnless { it is McpHttpException }?.let { redactor.message(it.describe()) }, + cancelled = cancelled, ) } diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt index 1dab432e3..0d99e804b 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt @@ -175,7 +175,8 @@ open class McpHttpClient( * the request unsent. A `disconnect()` before the connection exists does nothing, so a cancel * landing just after [onConnected] is caught here or not at all. Without a streaming mode the * write only fills a buffer and the request goes out when the answer is first read, so the - * second run catches a cancel that landed during the write. + * second run catches a cancel that landed during the write. A request it ends is recorded + * as cancelled, never as sent ([McpExchange.cancelled]). * @param exchangeListener receives each request made and what came back, redirects included. * An Exception or a LinkageError it throws is dropped; any other Error propagates. * @return the reply document and any session id the server sent. @@ -215,17 +216,25 @@ open class McpHttpClient( // tools/list page, each tools/call — pay a fresh TCP and TLS handshake. var reusable = false var failure: Throwable? = null + // Set when beforeSend ends the request: nothing went out, and its record must not say so. + var cancelled = false + fun checkBeforeSend() = try { + beforeSend() + } catch (e: Throwable) { + cancelled = true + throw e + } val redirect = try { // Connected here rather than by the first write, so beforeSend runs in between: a // cancel whose disconnect came before the connection existed dropped nothing, and the // write would connect and send the request regardless. conn.connect() - beforeSend() + checkBeforeSend() conn.outputStream.use { it.write(bytes) } // Again: the write only filled a buffer, and the request goes out at the first read // of the answer, just below. A cancel that landed meanwhile disconnected a connection // the JDK connects again at that read, sending the request after all. - beforeSend() + checkBeforeSend() trace.answered(conn) val next = conn.redirectTargetFrom(target) if (next == null) { @@ -270,7 +279,9 @@ open class McpHttpClient( // LinkageError costs only its record. Any other Error, an OutOfMemoryError above // all, is the process failing and propagates. // The trace's redactor, which masks a session id this answer assigned as well. - runCatchingRecoverable { exchangeListener.onExchange(trace.toExchange(failure), trace.redactor) } + runCatchingRecoverable { + exchangeListener.onExchange(trace.toExchange(failure, cancelled), trace.redactor) + } } if (++hops > MAX_REDIRECTS) { diff --git a/plugins/AI-Agent-MCP/src/main/res/values/strings.xml b/plugins/AI-Agent-MCP/src/main/res/values/strings.xml index 78cc70520..4f40b1b19 100644 --- a/plugins/AI-Agent-MCP/src/main/res/values/strings.xml +++ b/plugins/AI-Agent-MCP/src/main/res/values/strings.xml @@ -103,7 +103,9 @@ Headers Body No response + Cancelled Nothing was sent: the request failed before it reached the server. + Cancelled before it was sent: nothing of it reached the server. Extra headers diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpTranscriptTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpTranscriptTest.kt index 08de3e998..837f3fb79 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpTranscriptTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpTranscriptTest.kt @@ -16,6 +16,7 @@ class McpTranscriptTest { override fun hidden(length: Int) = "<$length hidden>" override fun omitted(count: Int) = "<$count more>" override val nothingSent = "" + override val cancelled = "" } private fun exchange( diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/CancelledExchangeLogTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/CancelledExchangeLogTest.kt new file mode 100644 index 000000000..faa4e70e5 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/CancelledExchangeLogTest.kt @@ -0,0 +1,75 @@ +package com.itsaky.androidide.plugins.aiagentmcp.transport + +import com.itsaky.androidide.plugins.aiagentmcp.errors.McpTranscript +import com.sun.net.httpserver.HttpServer +import java.io.InterruptedIOException +import java.net.InetSocketAddress +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.atomic.AtomicInteger +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * A request its caller cancels before it is sent is recorded in the connection log as cancelled, + * not as a request that went out. + * + * The record was built the same way whether the request had gone out or not, so the log showed + * the request's headers and body marked as sent, then "no response". It now says the request was + * cancelled before it was sent, and shows none of it as sent. + */ +class CancelledExchangeLogTest { + + private val bodies = AtomicInteger(0) + + private val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply { + createContext("/mcp") { exchange -> + exchange.requestBody.use { it.readBytes() } + bodies.incrementAndGet() + exchange.sendResponseHeaders(202, -1) + exchange.close() + } + start() + } + + private val labels = object : McpTranscript.Labels { + override fun hidden(length: Int) = "<$length hidden>" + override fun omitted(count: Int) = "<$count more>" + override val nothingSent = "" + override val cancelled = "" + } + + @After + fun tearDown() { + server.stop(0) + } + + @Test + fun `a request cancelled before it is sent is logged as cancelled, not as sent`() { + val exchanges = CopyOnWriteArrayList() + val cancel = InterruptedIOException("The tool call was cancelled before its request was sent") + + assertThrows(InterruptedIOException::class.java) { + McpHttpClient().post( + url = "http://127.0.0.1:${server.address.port}/mcp", + token = "", + body = JSONObject().put("jsonrpc", "2.0").put("id", 1).put("method", "tools/call"), + beforeSend = { throw cancel }, + exchangeListener = { exchange, _ -> exchanges += exchange }, + ) + } + val transcript = McpTranscript.render(exchanges.toList(), cancel, labels) { it } + + assertEquals("the cancelled request reached the server", 0, bodies.get()) + assertTrue("the record does not say the request was cancelled", exchanges.single().cancelled) + assertFalse( + "the transcript shows the cancelled request as sent:\n$transcript", + transcript.lines().any { it.startsWith(">") }, + ) + assertTrue("the transcript does not say it was cancelled:\n$transcript", "* " in transcript) + } +} From 42767c9d6c39a191b762dc99c464f45416996422 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Fri, 20 Nov 2026 21:06:04 -0800 Subject: [PATCH 56/90] ADFA-7139 AI-Agent-MCP: a server removed just after the check gets no health or tools back 9ccbd92a guarded the health writes with a check that the server is still configured, but checked and wrote with nothing between them: a removal landing after the check (McpToolCatalog.connect, recordFailure, McpToolSource.runTool) forgot the row, and the write brought it back. The listing's `toolsByServer[server.id] = tools` had no check at all, so a listing that outlived a deletion put the deleted server's tools back. McpServerHealth now takes one lock in every removal (detach, forget, clear) and around a guarded write's check and write; connectingIfUnknown, available and degraded take the check as `configured`, which the catalog and the tool source pass as McpServers::isConfigured. connectingIfUnknown is guarded too: a connect that started after the removal wrote a CONNECTING row nothing would clear. McpToolCatalog stores a listing's tools under a lock of its own that forget and clear take, after the same check. A removal takes the server out of its list before it forgets it, so under either lock the write either comes first and is forgotten, or sees the server gone. Listeners are still told after the lock is let go. Lock order: AutomaticServers' lock is held around McpServerHealth.detach; the check under the health lock reads the lists without a lock. The tests run the deletion from inside the check, once the request before it is over, and wait until it has finished or is blocked on the checking thread's lock; one deletes inline as the listing is answered, before its tools are stored. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../aiagentmcp/tools/McpServerHealth.kt | 60 ++++-- .../aiagentmcp/tools/McpToolCatalog.kt | 37 +++- .../plugins/aiagentmcp/tools/McpToolSource.kt | 3 +- .../tools/RemovalDuringRecordTest.kt | 197 ++++++++++++++++++ 4 files changed, 275 insertions(+), 22 deletions(-) create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/RemovalDuringRecordTest.kt diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpServerHealth.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpServerHealth.kt index c6538239d..0691db9ef 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpServerHealth.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpServerHealth.kt @@ -29,6 +29,19 @@ object McpServerHealth { private val byServer = ConcurrentHashMap() private val listeners = CopyOnWriteArrayList<() -> Unit>() + /** + * Taken by every removal ([detach], [forget], [clear]), and by a write made only while its + * server is configured, around the check and the write together. A removal landing between the + * two would otherwise be undone by the write, bringing back the row of a server that is gone. A + * removal takes its server out of the list first and forgets its row after, so under this lock + * either the write comes first and the removal takes its row, or the check sees the server gone. + * Nothing is called under it but that check, and never a listener. + */ + private val lock = Any() + + /** Writes a row whatever the list holds; the default of every `configured` below. */ + private val always: (String) -> Boolean = { true } + /** * @param serverId the server. * @return what is known of it, or null before it was ever asked. @@ -38,9 +51,15 @@ object McpServerHealth { /** * Records a first attempt under way. Only for a server with no answer yet: a re-probe of a * known server keeps its last answer until the new one lands, so the tag does not flicker. + * + * @param configured whether [serverId] is still configured; checked with the write, under the + * lock a removal takes, and false skips the write. */ - fun connectingIfUnknown(serverId: String) { - if (byServer.putIfAbsent(serverId, Health(State.CONNECTING)) == null) fireChanged() + fun connectingIfUnknown(serverId: String, configured: (String) -> Boolean = always) { + val added = synchronized(lock) { + configured(serverId) && byServer.putIfAbsent(serverId, Health(State.CONNECTING)) == null + } + if (added) fireChanged() } /** @@ -51,16 +70,25 @@ object McpServerHealth { if (byServer.remove(serverId, Health(State.CONNECTING))) fireChanged() } - /** Records that the server answered. */ - fun available(serverId: String) = set(serverId, Health(State.AVAILABLE)) + /** + * Records that the server answered. + * @param configured as for [connectingIfUnknown]. + */ + fun available(serverId: String, configured: (String) -> Boolean = always) = + set(serverId, Health(State.AVAILABLE), configured) /** * Records that the server could not be used. * @param message why, for the user, in the words the settings pane would use. * @param refused whether it refused the credential; see [Health.refused]. + * @param configured as for [connectingIfUnknown]. */ - fun degraded(serverId: String, message: String, refused: Boolean = false) = - set(serverId, Health(State.DEGRADED, message, refused)) + fun degraded( + serverId: String, + message: String, + refused: Boolean = false, + configured: (String) -> Boolean = always, + ) = set(serverId, Health(State.DEGRADED, message, refused), configured) /** Lets the probe ask a server that refused its credential again, once the user changed it. */ fun credentialChanged(serverId: String) { @@ -79,16 +107,15 @@ object McpServerHealth { * * @return whether anything was known of [serverId]. */ - internal fun detach(serverId: String): Boolean = byServer.remove(serverId) != null + internal fun detach(serverId: String): Boolean = synchronized(lock) { byServer.remove(serverId) != null } /** Tells the listeners of a change [detach] made. */ internal fun notifyChanged() = fireChanged() /** Forgets everything, for the plugin shutting down. */ fun clear() { - if (byServer.isEmpty()) return - byServer.clear() - fireChanged() + val had = synchronized(lock) { byServer.isNotEmpty().also { byServer.clear() } } + if (had) fireChanged() } /** @@ -108,9 +135,16 @@ object McpServerHealth { /** How many change listeners are registered; a test seam for a listener registered twice. */ internal val changeListenerCount: Int get() = listeners.size - /** Stores [health], telling the listeners only when it differs from what was there. */ - private fun set(serverId: String, health: Health) { - if (byServer.put(serverId, health) != health) fireChanged() + /** + * Stores [health] while [configured] holds, telling the listeners, after the lock is let go, + * only when it differs from what was there. + */ + private fun set(serverId: String, health: Health, configured: (String) -> Boolean) { + val changed = synchronized(lock) { + if (!configured(serverId)) return + byServer.put(serverId, health) != health + } + if (changed) fireChanged() } /** diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt index c9be7c248..a73686035 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt @@ -36,6 +36,15 @@ object McpToolCatalog { /** The tools of the user's own servers; an automatic entry's are in [AutomaticServers]. */ private val toolsByServer = ConcurrentHashMap>() + /** + * Taken by [forget] and [clear], and around the check and the write that store a listing of one + * of the user's servers. The deletion removes the server from the store before it forgets its + * tools, so under this lock either the listing is stored first and forgotten with the server, or + * the check sees the server gone; written with no check, a listing that outlived the deletion + * brought the tools of a server that no longer exists back. + */ + private val lock = Any() + /** Re-reads an automatic entry's endpoint and tries once more when the stored one is stale. */ val retry = EndpointRetry( refresh = AutomaticServers::refresh, @@ -77,15 +86,16 @@ object McpToolCatalog { server: McpServer, exchangeListener: McpExchangeListener = McpExchangeListener.NONE, ): Listing { - McpServerHealth.connectingIfUnknown(server.id) + // Each checked with its write, under the lock a removal takes: a server deleted while the + // handshake was in flight, even just after a check, gets no row back. + McpServerHealth.connectingIfUnknown(server.id, McpServers::isConfigured) val listing = try { retry.call(server) { list(it, exchangeListener) } } catch (e: Throwable) { recordFailure(server, e) throw e } - // Deleted while the handshake was in flight: recording it would resurrect its entry. - if (McpServers.isConfigured(server.id)) McpServerHealth.available(server.id) + McpServerHealth.available(server.id, McpServers::isConfigured) return listing } @@ -102,10 +112,15 @@ object McpToolCatalog { McpServerHealth.cancelConnecting(server.id) return } - if (!McpServers.isConfigured(server.id)) return val context = McpPlugin.getContext()?.androidContext val refused = failure is McpFailure.TokenRefused || failure is McpFailure.Forbidden - McpServerHealth.degraded(server.id, McpErrorFormatter.format(context, server, error), refused) + // Not for a server removed meanwhile, checked with the write as in connect. + McpServerHealth.degraded( + server.id, + McpErrorFormatter.format(context, server, error), + refused, + McpServers::isConfigured, + ) } /** The handshake-and-list itself; see [connect]. */ @@ -135,7 +150,13 @@ object McpToolCatalog { return Listing(session.serverName, tools) } } else { - toolsByServer[server.id] = tools + val stored = synchronized(lock) { + McpServers.isConfigured(server.id).also { if (it) toolsByServer[server.id] = tools } + } + if (!stored) { + Log.i(TAG, "Dropping a tool list from '${server.name}', removed while it listed") + return Listing(session.serverName, tools) + } McpServerStore.setKnownTools(server.id, tools.map { it.name }) } Log.i(TAG, "Server '${server.name}' listed ${tools.size} tool(s)") @@ -190,13 +211,13 @@ object McpToolCatalog { * lock, so the entry that replaces it under the same ID keeps its own. */ fun forget(serverId: String) { - toolsByServer.remove(serverId) + synchronized(lock) { toolsByServer.remove(serverId) } McpServerHealth.forget(serverId) } /** Forgets everything, for the plugin shutting down. */ fun clear() { - toolsByServer.clear() + synchronized(lock) { toolsByServer.clear() } McpServerHealth.clear() } } diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt index 74d483817..690621c95 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt @@ -216,7 +216,8 @@ class McpToolSource internal constructor( } // A reply of any kind, a tool's own failure included, means the server is answering; // unless it was removed while the call ran, when recording it would bring back its row. - if (McpServers.isConfigured(server.id)) McpServerHealth.available(server.id) + // Checked with the write, under the lock the removal takes, so it cannot land between. + McpServerHealth.available(server.id, McpServers::isConfigured) Outcome(result.success, result.text, result.errorMessage) } catch (e: Throwable) { // Throwable, unlike the other host-facing catches in this plugin: this runs inside diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/RemovalDuringRecordTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/RemovalDuringRecordTest.kt new file mode 100644 index 000000000..eeea73c38 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/RemovalDuringRecordTest.kt @@ -0,0 +1,197 @@ +package com.itsaky.androidide.plugins.aiagentmcp.tools + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.debugger.McpServers +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServer +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpSettingsViewModel +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.aiagentmcp.testing.awaitFinishedOrBlockedBy +import com.itsaky.androidide.plugins.aiagentmcp.transport.McpExchangeListener +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import com.itsaky.androidide.plugins.services.ToolSourceRegistry +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean +import kotlin.concurrent.thread +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * A server of the user's removed between the check that it is still configured and the write of + * its health or its tools leaves neither behind. + * + * A listing and a call checked that their server was configured, then wrote its health, with + * nothing to keep a removal from landing in between: the removal forgot the health, and the write + * brought it back. The listing wrote the server's tools with no check at all, so a removal that + * finished first saw them come back too. Each check and its write now share the lock the + * removal's forget takes. + * + * The deletion runs on its own thread from inside the check, once the request before it is over, + * and the check waits until the deletion has finished or is blocked on a lock the checking thread + * holds. Nothing sleeps. + */ +class RemovalDuringRecordTest { + + private val delegate = Executors.newSingleThreadExecutor() + private val removals = CopyOnWriteArrayList() + + /** Whether the next check should run the deletion; read by every check, on any thread. */ + @Volatile private var trigger: () -> Boolean = { false } + private val fired = AtomicBoolean(false) + + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + // The Keystore is not there on the JVM; these servers have no secrets. + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } returns KeystoreSecretStore.Stored.Absent + every { McpServerStore.headers(any()) } returns emptyMap() + mockkObject(McpServers) + every { McpServers.isConfigured(any()) } answers { + // What the check found, before the deletion it lets in. + val configured = callOriginal() + if (trigger() && fired.compareAndSet(false, true)) { + val checking = Thread.currentThread() + val id = firstArg() + val removal = thread(name = "removing") { McpSettingsViewModel { null }.deleteNow(id) } + removals += removal + awaitFinishedOrBlockedBy(removal, checking) + } + configured + } + } + + @After + fun tearDown() { + removals.forEach { it.join(10_000) } + delegate.shutdownNow() + unmockkObject(McpServers) + McpConnections.closeAll() + McpToolCatalog.clear() + plugin.dispose() + unmockkObject(McpServerStore) + } + + @Test + fun `a listing whose server is removed after the check records neither health nor tools`() { + val server = FakeMcpServer("", listOf(tool("search", true))) + try { + val saved = save(server) + val listed = AtomicBoolean(false) + trigger = { listed.get() } + + McpToolCatalog.connect( + saved, + McpExchangeListener { exchange, _ -> + if (exchange.requestBody.text.contains("\"tools/list\"")) listed.set(true) + }, + ) + removals.forEach { it.join(10_000) } + + assertTrue("no check ran after the listing", fired.get()) + assertNull("the listing brought back the removed server's health", McpServerHealth.of(saved.id)) + assertEquals("the listing brought back the removed server's tools", emptyList(), toolNames(saved)) + } finally { + server.stop() + } + } + + @Test + fun `a listing whose server is removed before its tools are stored leaves no tools`() { + val server = FakeMcpServer("", listOf(tool("search", true))) + try { + val saved = save(server) + + McpToolCatalog.connect( + saved, + McpExchangeListener { exchange, _ -> + // Deleted as the listing is answered, before anything stores its tools. + if (exchange.requestBody.text.contains("\"tools/list\"")) { + McpSettingsViewModel { null }.deleteNow(saved.id) + } + }, + ) + + assertTrue("the server was not deleted", McpServerStore.server(saved.id) == null) + assertEquals("the listing stored the removed server's tools", emptyList(), toolNames(saved)) + assertNull("the listing brought back the removed server's health", McpServerHealth.of(saved.id)) + } finally { + server.stop() + } + } + + @Test + fun `a failed listing whose server is removed after the check records no health`() { + // Refuses the listing: its requests carry no token. + val server = FakeMcpServer("required", listOf(tool("search", true))) + try { + val saved = save(server) + val answered = AtomicBoolean(false) + trigger = { answered.get() } + + val failure = runCatching { + McpToolCatalog.connect(saved, McpExchangeListener { _, _ -> answered.set(true) }) + }.exceptionOrNull() + removals.forEach { it.join(10_000) } + + assertTrue("the listing did not fail: $failure", failure != null) + assertTrue("no check ran after the refusal", fired.get()) + assertNull("the failed listing brought back the removed server's health", McpServerHealth.of(saved.id)) + } finally { + server.stop() + } + } + + @Test + fun `a call whose server is removed after the check records no health`() { + val server = FakeMcpServer("", listOf(tool("search", true))) + try { + val saved = save(server) + McpToolCatalog.connect(saved) + McpServerStore.setToolEnabled(saved.id, "search", true) + val source = McpToolSource(delegate) + val name = source.listTools().single().name + val before = server.requests.size + // Armed by the call's own request: nothing checks the server while that is answered. + trigger = { server.requests.size > before } + + val outcome = source.invoke( + mockk { + every { toolName } returns name + every { arguments } returns emptyMap() + every { callId } returns "call-1" + } + ).get(10, TimeUnit.SECONDS) + removals.forEach { it.join(10_000) } + + assertTrue("the call was not answered: ${outcome.errorMessage}", outcome.isSuccess) + assertTrue("no check ran after the call", fired.get()) + assertNull("the call brought back the removed server's health", McpServerHealth.of(saved.id)) + } finally { + server.stop() + } + } + + private fun save(server: FakeMcpServer): McpServer = + McpServerStore.saveDetails(McpServerStore.newServer("Docs", "http://127.0.0.1:${server.port}/mcp")) + + private fun toolNames(server: McpServer) = McpToolCatalog.tools(server.id).map { it.name } +} From 55e58046e0a232b69025dc45fd82f01a3551ce18 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Fri, 20 Nov 2026 21:06:42 -0800 Subject: [PATCH 57/90] ADFA-7139 AI-Agent-MCP: a call or listing on a removed server ends the session it opened 9ccbd92a made McpConnections.session return an unstored session for a server no longer configured, so it would not outlive the server. But nothing ended that session either: the call or listing initialized it, the server assigned a session id, and nothing ever sent the DELETE. McpConnections.withSession runs the caller's requests on the session and, when it was not kept, ends it after them. McpToolSource.runTool and McpToolCatalog's listing use it. The DELETE reads the credentials through the session's own supplier, so the J2 rule applies to it as to each of its requests: the URL must still be the server's. A server that is gone gets none, as its requests got none; the credentials saved as a session is taken out (9d271cc0) are for sessions that were stored, which this one never was. session() stays, for the tests that look a session up directly. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../aiagentmcp/client/McpConnections.kt | 44 ++++++- .../aiagentmcp/tools/McpToolCatalog.kt | 31 ++--- .../plugins/aiagentmcp/tools/McpToolSource.kt | 4 +- .../tools/RemovedServerSessionTest.kt | 108 ++++++++++++++++++ 4 files changed, 168 insertions(+), 19 deletions(-) create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/RemovedServerSessionTest.kt diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt index ac6404d89..753d367ec 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt @@ -55,10 +55,46 @@ object McpConnections { * still has the credentials; the settings pane ends whatever a lookup stored between the two * once the server is gone. * + * A session that is not kept is the caller's to end; [withSession] does that, and is what a + * request should use. + * * @param server the server to connect to. * @return its session, not yet initialized. */ - fun session(server: McpServer): McpSession { + fun session(server: McpServer): McpSession = lookUp(server).session + + /** + * Runs [block] with [server]'s session, as [session] finds or builds it, and ends the session + * once [block] is done when it was not kept, for a server no longer configured. Nothing else + * would end that one, so the server would keep the session its `initialize` assigned. Its DELETE + * reads the credentials as each of its requests did, under the same rule: only for the URL it + * was built for, while the server still has it, so a server that is gone gets none, as the + * requests did. + * + * Blocking, like [block]: ending the session sends a DELETE. + * + * @param server the server to connect to. + * @param block the calls to make; the session is not yet initialized. + * @return what [block] returned. + */ + fun withSession(server: McpServer, block: (McpSession) -> T): T { + val found = lookUp(server) + try { + return block(found.session) + } finally { + if (!found.kept) found.session.close() + } + } + + /** + * What [lookUp] found. + * @property kept whether [session] is the one stored for its server; false for a server no + * longer configured. + */ + private class Found(val session: McpSession, val kept: Boolean) + + /** [session] itself, telling a session it kept from one it did not. */ + private fun lookUp(server: McpServer): Found { val key = keyFor(server) // Locked, so two tool calls arriving together cannot each build a session and leave one of @@ -67,11 +103,11 @@ object McpConnections { var stale: McpSession? = null val session = synchronized(this) { val current = sessions[server.id] - if (current != null && current.first == key) return current.second + if (current != null && current.first == key) return Found(current.second, kept = true) // A supplier, not the values: the session is kept for the life of the process, and a // token in one of its fields would be readable in a heap dump for just as long. val fresh = McpSession(server.url, { credentialsFor(server.id, server.url) }) - if (!McpServers.isConfigured(server.id)) return fresh + if (!McpServers.isConfigured(server.id)) return Found(fresh, kept = false) stale = current?.second fresh.also { sessions[server.id] = key to it } } @@ -80,7 +116,7 @@ object McpConnections { Log.i(TAG, "Server '${server.name}' changed; dropping its session") runCatchingRecoverable { it.close() } } - return session + return Found(session, kept = true) } /** diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt index a73686035..a76861923 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt @@ -128,18 +128,21 @@ object McpToolCatalog { // Taken before the request: if the endpoint is replaced while this list is in flight, the // list is the old process's and must not be attached to the new one. val origin = if (server.automatic) AutomaticServers.endpoint(server.id) else null - // Kept, not just its tools: the name the handshake returned lands on the session. - val session = McpConnections.session(server) - val tools = session.recording(exchangeListener) { - // Explicit, so a catalogue refused below is told apart from a refused connection. - session.initialize() - try { - session.listTools() - } catch (e: McpProtocolException) { - // No tools capability: some servers expose only prompts or resources, and still work. - if (e.code != JsonRpc.METHOD_NOT_FOUND) throw e - emptyList() + // The name too: the handshake returns it on the session, which is ended here for a server + // removed meanwhile. + val (serverName, tools) = McpConnections.withSession(server) { session -> + val listed = session.recording(exchangeListener) { + // Explicit, so a catalogue refused below is told apart from a refused connection. + session.initialize() + try { + session.listTools() + } catch (e: McpProtocolException) { + // No tools capability: some servers expose only prompts or resources, and still work. + if (e.code != JsonRpc.METHOD_NOT_FOUND) throw e + emptyList() + } } + session.serverName to listed } if (server.automatic) { // Stored by recordTools alone, beside the endpoint it checks, under the same lock. @@ -147,7 +150,7 @@ object McpToolCatalog { AutomaticServers.recordTools(server.id, origin, tools) if (!current) { Log.i(TAG, "Dropping a tool list from an endpoint '${server.name}' has since left") - return Listing(session.serverName, tools) + return Listing(serverName, tools) } } else { val stored = synchronized(lock) { @@ -155,12 +158,12 @@ object McpToolCatalog { } if (!stored) { Log.i(TAG, "Dropping a tool list from '${server.name}', removed while it listed") - return Listing(session.serverName, tools) + return Listing(serverName, tools) } McpServerStore.setKnownTools(server.id, tools.map { it.name }) } Log.i(TAG, "Server '${server.name}' listed ${tools.size} tool(s)") - return Listing(session.serverName, tools) + return Listing(serverName, tools) } /** diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt index 690621c95..5cb513f5c 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt @@ -212,7 +212,9 @@ class McpToolSource internal constructor( // A cancel landing from here on, during the session lookup or while a request reads // its credentials, is caught by the handle: each request publishes its connection // there and reads the flag again before it sends anything. - McpConnections.session(target).callTool(tool.name, arguments, call.handle) + // The session is ended after the call when it was not kept: a server removed + // meanwhile would otherwise keep the session this call's handshake opened. + McpConnections.withSession(target) { it.callTool(tool.name, arguments, call.handle) } } // A reply of any kind, a tool's own failure included, means the server is answering; // unless it was removed while the call ran, when recording it would bring back its row. diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/RemovedServerSessionTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/RemovedServerSessionTest.kt new file mode 100644 index 000000000..aeba07efe --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/RemovedServerSessionTest.kt @@ -0,0 +1,108 @@ +package com.itsaky.androidide.plugins.aiagentmcp.tools + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServer +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpSettingsViewModel +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import com.itsaky.androidide.plugins.services.ToolSourceRegistry +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import java.util.concurrent.CountDownLatch +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * A call or a listing made for a server of the user's that is already gone ends the session it + * used. + * + * Such a lookup gets a session that is not kept, since one stored for a server that is gone would + * outlive it with nothing left to end it. But nothing ended the unkept one either, so the server + * kept the session its `initialize` assigned. It is now ended once the call or the listing is done. + * + * The worker is held on a latch before its first line while the server is deleted; nothing sleeps. + */ +class RemovedServerSessionTest { + + private val delegate = Executors.newSingleThreadExecutor() + private val server = FakeMcpServer("", listOf(tool("search", true)), sessionId = "session-1") + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + // The Keystore is not there on the JVM; this server has no secrets. + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } returns KeystoreSecretStore.Stored.Absent + every { McpServerStore.headers(any()) } returns emptyMap() + } + + @After + fun tearDown() { + delegate.shutdownNow() + McpConnections.closeAll() + McpToolCatalog.clear() + server.stop() + plugin.dispose() + unmockkObject(McpServerStore) + } + + @Test + fun `a call that outlives its server's removal ends the session it used`() { + val saved = save() + McpToolCatalog.connect(saved) + McpServerStore.setToolEnabled(saved.id, "search", true) + val started = CountDownLatch(1) + val proceed = CountDownLatch(1) + val source = McpToolSource(delegate) { + started.countDown() + assertTrue("the test never released the worker", proceed.await(10, TimeUnit.SECONDS)) + } + val name = source.listTools().single().name + val future = source.invoke( + mockk { + every { toolName } returns name + every { arguments } returns emptyMap() + every { callId } returns "call-1" + } + ) + assertTrue("the worker never started", started.await(10, TimeUnit.SECONDS)) + + McpSettingsViewModel { null }.deleteNow(saved.id) + val ended = deletes() + proceed.countDown() + val outcome = future.get(10, TimeUnit.SECONDS) + + assertTrue("the call was not answered: ${outcome.errorMessage}", outcome.isSuccess) + assertEquals("the session the call used for the removed server was never ended", ended + 1, deletes()) + } + + @Test + fun `a listing of a server already removed ends the session it used`() { + val saved = save() + McpSettingsViewModel { null }.deleteNow(saved.id) + + McpToolCatalog.connect(saved) + + assertEquals("the session the listing used for the removed server was never ended", 1, deletes()) + } + + private fun save(): McpServer = + McpServerStore.saveDetails(McpServerStore.newServer("Docs", "http://127.0.0.1:${server.port}/mcp")) + + private fun deletes() = server.requests.count { it.httpMethod == "DELETE" } +} From 6b57e0f9a394bc5f9ebab1bc37600b5719bb1207 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Fri, 20 Nov 2026 21:07:36 -0800 Subject: [PATCH 58/90] ADFA-7139 AI-Agent-MCP: a deleted server's second DELETE carries its token when there was no first session deleteNow ends the server's session, removes the server, and ends again any session a call stored in between. 9a82af5c gave that second DELETE the credentials read for the first, so when the first detach found no session it went out with none, and a server that requires a token refused it with 401 and kept the session. deleteNow now reads the credentials before the removal, for the URL the server has then (McpConnections.saveCredentials), and the second close carries them. Released.close takes them only when they were read for the session's own URL, the J2 rule, and otherwise falls back to what it read as the session was taken out. Released keeps its session's URL for that; the close that took plain credentials had no other caller and is gone. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../aiagentmcp/client/McpConnections.kt | 36 +++++++++++++++---- .../settings/McpSettingsViewModel.kt | 11 +++--- .../settings/DeleteServerSessionTest.kt | 34 ++++++++++++++++++ 3 files changed, 71 insertions(+), 10 deletions(-) diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt index 753d367ec..d77a22ac4 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt @@ -126,25 +126,49 @@ object McpConnections { * with the server. Read at the DELETE they would be empty, and the server would refuse it and * keep its session open. * + * @property url the URL the session was built for. * @property credentials what the DELETE carries; null when they could not be read, when * [close] reads them again. */ class Released internal constructor( private val session: McpSession, - internal val credentials: McpCredentials?, + private val url: String, + private val credentials: McpCredentials?, ) { /** * Ends the session, best effort: sends a DELETE when it has a server-side id, so never under * a lock. An Exception or a LinkageError is survived; any other Error propagates. * - * @param credentials what the DELETE carries: the ones saved here, unless the caller holds - * better ones. + * @param saved credentials the caller read before they could go, carried in place of the + * ones saved here when they were read for this session's URL, and ignored for any other: + * they do not belong there. */ - fun close(credentials: McpCredentials? = this.credentials) { - runCatchingRecoverable { if (credentials != null) session.close(credentials) else session.close() } + fun close(saved: SavedCredentials? = null) { + val carried = saved?.takeIf { it.url == url }?.credentials ?: credentials + runCatchingRecoverable { if (carried != null) session.close(carried) else session.close() } } } + /** + * A server's credentials as read for one URL, for a DELETE sent once they may have gone with + * the server; see [saveCredentials]. + */ + class SavedCredentials internal constructor(internal val url: String, internal val credentials: McpCredentials) + + /** + * [serverId]'s credentials, read now for the URL it has now: for a caller about to delete one of + * the user's servers, which may find a session to end once the deletion has taken them away. + * [Released.close] carries them only to a session built for that URL. + * + * @return them, or null for a server not stored or credentials that could not be read. + */ + fun saveCredentials(serverId: String): SavedCredentials? { + val url = McpServerStore.server(serverId)?.url ?: return null + return runCatchingRecoverable { SavedCredentials(url, credentialsFor(serverId, url)) } + .onFailure { e -> Log.d(TAG, "Could not read the credentials to end '$serverId' with: $e") } + .getOrNull() + } + /** Drops the session for [serverId], ending it server-side when it had one. */ fun invalidate(serverId: String) { detach(serverId)?.close() @@ -210,7 +234,7 @@ object McpConnections { ): Released { val read = runCatchingRecoverable { credentials(entry.first.url) } .onFailure { e -> Log.d(TAG, "Could not read the credentials to end '$serverId' with: $e") } - return Released(entry.second, read.getOrNull()) + return Released(entry.second, entry.first.url, read.getOrNull()) } /** diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt index 7d953e1b5..c7b6cc229 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt @@ -229,15 +229,18 @@ class McpSettingsViewModel( * the removal deletes. A call or a listing that looked the session up between the two stored * a new one, which would outlive the server; it is ended again once the server is gone, when * no lookup stores one any more (McpConnections.session keeps none for a server no longer - * configured). That second DELETE carries the credentials read for the first, best effort; - * none when there was no first session to read them for. + * configured). That second DELETE carries the credentials read before the server was removed, + * whether or not there was a first session, best effort; only to a session built for the URL + * they were read for, so none to a session for a URL the server has left. */ internal fun deleteNow(id: String) { - val ended = McpConnections.detach(id)?.also { it.close() } + // Read while the server is still stored: removing it deletes them. + val saved = McpConnections.saveCredentials(id) + McpConnections.detach(id)?.close() // Removed before the tools are forgotten, so a probe finishing in between sees it gone and // records nothing. McpServerStore.remove(id) - McpConnections.detach(id)?.close(ended?.credentials) + McpConnections.detach(id)?.close(saved) McpToolCatalog.forget(id) } diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/DeleteServerSessionTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/DeleteServerSessionTest.kt index 467fa9527..910bc0477 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/DeleteServerSessionTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/DeleteServerSessionTest.kt @@ -110,4 +110,38 @@ class DeleteServerSessionTest { guarded.stop() } } + + /** + * The same when the deletion found no session to end first, so no credentials were read for + * one: the DELETE for the session a call stored meanwhile carries the token read before the + * server was removed, not none. + */ + @Test + fun `the second DELETE of a deleted server with no first session carries its token`() { + val guarded = FakeMcpServer("ut", listOf(tool("search", true)), sessionId = "session-3") + try { + var removed = false + every { McpServerStore.token(any()) } answers { + if (removed) KeystoreSecretStore.Stored.Absent else KeystoreSecretStore.Stored.Value("ut") + } + val saved = McpServerStore.saveDetails( + McpServerStore.newServer("Guarded", "http://127.0.0.1:${guarded.port}/mcp") + ) + every { McpServerStore.remove(saved.id) } answers { + // A call landing between the two steps, the server's first session. + McpConnections.session(saved).initialize() + callOriginal().also { removed = true } + } + + McpSettingsViewModel { null }.deleteNow(saved.id) + + assertEquals( + "the DELETE ending the session stored during the deletion", + listOf("Bearer ut"), + guarded.requests.filter { it.httpMethod == "DELETE" }.map { it.authorization }, + ) + } finally { + guarded.stop() + } + } } From c37850d2e0756a2b06f86f280cb27a7030399668 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Fri, 20 Nov 2026 21:08:35 -0800 Subject: [PATCH 59/90] ADFA-7139 AI-Agent-MCP: a lifecycle call ends only the sessions its own teardown took out f1bf652e moved the session DELETEs out of the lifecycle lock: teardown put the sessions it took out in one shared list, and each lifecycle call emptied that list once it had let go of the lock. An activate taking the lock after a deactivation's teardown and before its drain emptied the list itself, so it ended the deactivation's sessions and waited for their DELETEs, up to about 70 s each. teardown (and releaseConnections under it) now returns the sessions it took out, and the call that ran it ends those alone (endSessions): deactivate, dispose, and activate for the teardown of a failed activation. The shared releasedSessions field is gone. The test holds the deactivation at its teardown's last steps, after the sessions are taken out, in a wait on the lifecycle lock (reached by reflection, as the lock is private), which lets the lock go; the activate runs in that window. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../plugins/aiagentmcp/plugin/McpPlugin.kt | 80 ++++++++++--------- .../plugin/LifecycleSessionCloseTest.kt | 66 +++++++++++++++ 2 files changed, 108 insertions(+), 38 deletions(-) diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt index 0954cf339..789df403b 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt @@ -73,21 +73,15 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { * * Nothing taken under it waits for this plugin's own work or for the network: the host's * listener and service registries do not call back, the coroutines it cancels never take it, - * and [teardown] only takes the sessions out ([releasedSessions]). Each lifecycle call ends - * them once it has let go: a session's `close()` sends a DELETE and can first wait, up to about - * 70 s, for a handshake in flight to let go of the session, and a lifecycle call or AI Core's - * registration arriving meanwhile must not wait behind it. + * and [teardown] only takes the sessions out, returning them. The lifecycle call that ran it + * ends them once it has let go ([endSessions]): a session's `close()` sends a DELETE and can + * first wait, up to about 70 s, for a handshake in flight to let go of the session, and a + * lifecycle call or AI Core's registration arriving meanwhile must not wait behind it. Each + * call ends only the sessions its own teardown took out, so one arriving meanwhile neither + * ends another's nor waits for them. */ private val lifecycleLock = Any() - /** - * Sessions [teardown] took out under [lifecycleLock], for the lifecycle call that ran it to end - * once it has let go ([closeReleasedSessions]), each with the credentials read as it was taken - * out: [teardown] clears the SQLite debugger entries after, and an entry's token goes with it. - * Guarded by [lifecycleLock]. - */ - private val releasedSessions = mutableListOf() - /** * Background work: listing tools is network work and never belongs on the main thread. * @@ -249,14 +243,17 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { } override fun activate(): Boolean { - val activated = synchronized(lifecycleLock) { activateLocked() } + val (activated, released) = synchronized(lifecycleLock) { activateLocked() } // A failed activation tears down what it started, sessions included. - closeReleasedSessions() + endSessions(released) return activated } - /** [activate] itself, under [lifecycleLock]. */ - private fun activateLocked(): Boolean = try { + /** + * [activate] itself, under [lifecycleLock]. + * @return whether it worked, and the sessions a failed one's teardown took out, to end. + */ + private fun activateLocked(): Pair> = try { // Cancelled and replaced as one step: a host that activates twice would otherwise orphan // the running scope, and the launch below has to use this activation's scope, not whatever // a concurrent lifecycle call has since installed. @@ -295,12 +292,12 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { if (refreshed > 0 && isActive) settingsChanged() probeHealth({ isActive }) } - true + true to emptyList() } catch (e: Exception) { - activationFailed(e) + false to activationFailed(e) } catch (e: LinkageError) { // A host call outside the guards above, from a host whose plugin-api differs. - activationFailed(e) + false to activationFailed(e) } /** @@ -310,43 +307,44 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { * stop the scope it had started or remove the listeners it had registered by then. * * @param e what ended the activation. - * @return false, for [activate] to return. + * @return the sessions the teardown took out, for [activate] to end. */ - private fun activationFailed(e: Throwable): Boolean { - teardown() + private fun activationFailed(e: Throwable): List { + val released = teardown() runCatchingRecoverable { context.logger.error("McpPlugin: activation failed", e) } - return false + return released } override fun deactivate(): Boolean { + var released = emptyList() val deactivated = synchronized(lifecycleLock) { try { - teardown() + released = teardown() true } catch (e: Exception) { context.logger.error("McpPlugin: deactivation failed", e) false } } - closeReleasedSessions() + endSessions(released) return deactivated } override fun dispose() { - synchronized(lifecycleLock) { teardown() } + val released = synchronized(lifecycleLock) { teardown() } // Before the context goes: a session's DELETE reads its credentials through it. - closeReleasedSessions() + endSessions(released) pluginContext = null context.logger.info("McpPlugin: disposed") } /** - * Ends the sessions [teardown] took out, each with a DELETE, best effort. Called by each - * lifecycle call once it has let go of [lifecycleLock], never under it; see there. + * Ends [released], each with a DELETE, best effort: the sessions the calling lifecycle call's + * own [teardown] took out, never another's. Called once that call has let go of + * [lifecycleLock], never under it; see there. */ - private fun closeReleasedSessions() { - val closing = synchronized(lifecycleLock) { releasedSessions.toList().also { releasedSessions.clear() } } - for (session in closing) session.close() + private fun endSessions(released: List) { + for (session in released) session.close() } /** @@ -355,9 +353,12 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { * [deactivate], [dispose] and a failed [activate], so the three cannot drift apart. Safe to run * on an activation that got only part of the way, and on none at all. Each caller holds * [lifecycleLock]; taken here too, so a new caller cannot forget it. The sessions are only taken - * out here; the lifecycle call ends them after it has let go ([closeReleasedSessions]). + * out here; the lifecycle call ends them after it has let go ([endSessions]). + * + * @return the sessions taken out, each with the credentials read as it was taken out, for the + * caller alone to end. */ - private fun teardown() = synchronized(lifecycleLock) { + private fun teardown(): List = synchronized(lifecycleLock) { // Guarded: a host whose plugin-api differs answers with a LinkageError, and one escaping // here would skip every step below, leaving the scope and its probe running. runCatchingRecoverable { context.removePluginLifecycleListener(aiCoreLifecycle) } @@ -557,17 +558,20 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { } /** - * Closes the tool source, takes every session out for [closeReleasedSessions], and forgets the - * cached tool lists. Under [lifecycleLock], with [teardown]. + * Closes the tool source, takes every session out, and forgets the cached tool lists. Under + * [lifecycleLock], with [teardown]. + * + * @return the sessions taken out, for the lifecycle call to end ([endSessions]). */ - private fun releaseConnections() { + private fun releaseConnections(): List { toolSource?.close() toolSource = null // Before the entries are cleared below: each session's credentials are read as it is taken // out, and a SQLite debugger entry's token leaves with its entry. - releasedSessions += McpConnections.detachAll() + val released = McpConnections.detachAll() McpToolCatalog.clear() AutomaticServers.install(null) + return released } /** diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/LifecycleSessionCloseTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/LifecycleSessionCloseTest.kt index 06f4ee1ca..517a9000e 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/LifecycleSessionCloseTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/LifecycleSessionCloseTest.kt @@ -5,6 +5,7 @@ import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences import com.itsaky.androidide.plugins.aiagentmcp.testing.awaitFinishedOrBlockedBy +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpServerHealth import com.itsaky.androidide.plugins.aiagentmcp.tools.McpToolCatalog import com.itsaky.androidide.plugins.security.KeystoreSecretStore import com.itsaky.androidide.plugins.services.ToolSourceRegistry @@ -120,4 +121,69 @@ class LifecycleSessionCloseTest { assertEquals("activate waited for the deactivation's DELETE", Thread.State.TERMINATED, state) assertFalse("deactivate never finished", deactivating.isAlive) } + + /** + * An activate that runs after a deactivation has taken its sessions out, and before that + * deactivation has ended them, leaves them to it: it neither ends them nor waits for them. + * + * The sessions taken out were kept in one list that every lifecycle call emptied once it had + * let go of the lock. An activate taking the lock in that window emptied it, ended the + * deactivation's sessions itself, and waited for their DELETEs, up to about 70 s each. Each + * lifecycle call now ends only the sessions its own teardown took out. + * + * A health listener holds the deactivation at its teardown's last steps, after the sessions are + * taken out, in a wait on the lifecycle lock, which lets that lock go: the window, opened for as + * long as the test needs. The lock is private, so the test reaches it by reflection. Nothing + * sleeps. + */ + @Test + @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") // wait and notifyAll on the lock's own monitor + fun `an activate between a deactivation's teardown and its DELETEs leaves the sessions to it`() { + val saved = McpServerStore.saveDetails( + McpServerStore.newServer("Docs", "http://127.0.0.1:${server.address.port}/mcp") + ) + plugin.activate() + McpConnections.session(saved).initialize() + // A health row, so the teardown's clearing of the cache tells the health listeners. + McpServerHealth.available(saved.id) + val lock = McpPlugin::class.java.getDeclaredField("lifecycleLock") + .apply { isAccessible = true } + .get(plugin) as java.lang.Object + val held = CountDownLatch(1) + var resume = false + val hold = { + if (Thread.currentThread().name == "deactivating" && held.count > 0) { + synchronized(lock) { + held.countDown() + while (!resume) lock.wait() + } + } + } + McpServerHealth.addChangeListener(hold) + try { + val deactivating = thread(name = "deactivating") { plugin.deactivate() } + assertTrue("the deactivation's teardown never took its sessions out", held.await(10, TimeUnit.SECONDS)) + val activating = thread(name = "activating") { plugin.activate() } + // Whichever comes first: the activate ending, or a DELETE sent while the deactivation is held. + val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10) + while (activating.isAlive && deleteArrived.count > 0 && System.nanoTime() < deadline) activating.join(10) + val endedByActivate = deleteArrived.count == 0L + val activateEnded = !activating.isAlive + synchronized(lock) { + resume = true + lock.notifyAll() + } + val endedByDeactivate = deleteArrived.await(10, TimeUnit.SECONDS) + releaseDelete.countDown() + activating.join(10_000) + deactivating.join(10_000) + + assertFalse("activate ended the sessions the deactivation took out", endedByActivate) + assertTrue("activate did not end", activateEnded) + assertTrue("the deactivation never ended its own session", endedByDeactivate) + assertFalse("deactivate never finished", deactivating.isAlive) + } finally { + McpServerHealth.removeChangeListener(hold) + } + } } From fc9d6295764d7cacc0b090e3d4b96a298402a1b2 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 09:12:55 -0800 Subject: [PATCH 60/90] ADFA-7139 AI-Agent-MCP: a refused reply names the rule it broke, too deep or not strict JSON A reply with a comment, a single quote, ';' or '=' outside a string, or a stray '"', is refused before any parser sees it, because Android's lenient org.json could nest through brackets the strict scan took as text. It was refused with JsonRpc.TooDeepException, "nests arrays and objects more than 100 levels deep", so the author of an MCP server would look for nesting that is not there. JsonDepth.refusal now says which rule tripped: TooDeep(limit) or NotStrict(found), each with its reason. parseReply throws UnparsedReplyException with that reason, so the call or listing fails with "The server's reply to 'tools/list' is not strict JSON: a comment, single quote, ';', '=' or stray '"' outside a string (found '/'); it was not read." That sentence is what the connection log's error line and the Agent tab's reason show. McpLogFormat.json still shows a refused body as it came. Tests: DeepReplyTest gets a reply with '//' (strict-JSON reason) and one nested 101 deep (depth reason); JsonRpcTest the same at parseReply; JsonDepthTest now pins which rule each refused case trips; McpLogFormatTest shows a non-strict body as it came. The '//' case fails without the fix, with the depth reason in place of the strict-JSON one. README: the refusal names the rule. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- plugins/AI-Agent-MCP/README.md | 13 ++++-- .../plugins/aiagentmcp/client/McpSession.kt | 6 +-- .../plugins/aiagentmcp/errors/McpLogFormat.kt | 5 +- .../plugins/aiagentmcp/transport/JsonDepth.kt | 46 +++++++++++++++---- .../plugins/aiagentmcp/transport/JsonRpc.kt | 20 ++++---- .../aiagentmcp/client/DeepReplyTest.kt | 32 +++++++++++++ .../aiagentmcp/errors/McpLogFormatTest.kt | 8 ++++ .../aiagentmcp/transport/JsonDepthTest.kt | 30 ++++++------ .../aiagentmcp/transport/JsonRpcTest.kt | 23 +++++++++- 9 files changed, 139 insertions(+), 44 deletions(-) diff --git a/plugins/AI-Agent-MCP/README.md b/plugins/AI-Agent-MCP/README.md index a664ffcb8..9e45d951b 100644 --- a/plugins/AI-Agent-MCP/README.md +++ b/plugins/AI-Agent-MCP/README.md @@ -196,11 +196,14 @@ Two dependencies were deliberately not taken: - A server's JSON is parsed only when it nests arrays and objects at most 100 levels deep, brackets inside strings not counted (`JsonDepth`): parsing recurses once per level, and a body of nothing but `[` would run Code on the - Go out of stack. A deeper reply fails its call or listing with that reason; a - deeper body in the connection log is shown as it came. The scan reads strict - JSON and refuses the same way any text that is not: Android's org.json also - reads `;` and `=` separators, comments, single-quoted strings and unquoted - text, each a way to make it nest through brackets a strict scan took as text. + Go out of stack. The scan reads strict JSON and refuses any text that is not: + Android's org.json also reads `;` and `=` separators, comments, + single-quoted strings and unquoted text, each a way to make it nest through + brackets a strict scan took as text. A refused reply fails its call or + listing with the rule it broke, "nests arrays and objects more than 100 + levels deep" or "is not strict JSON" with the character found, so the + server's author knows which to look for; a refused body in the connection log + is shown as it came. - A `202 Accepted` body is read and thrown away, for at most 1 MiB of characters and 10 seconds; one that runs past either is abandoned and its socket disconnected, not reused. The worst case is the 10 seconds plus one read diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSession.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSession.kt index 4ccbf476b..fb1da8a18 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSession.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSession.kt @@ -308,9 +308,9 @@ class McpSession( val reply = try { JsonRpc.parseReply(document) - } catch (e: JsonRpc.TooDeepException) { - // Refused rather than parsed, so the call or listing fails with this reason instead of - // a StackOverflowError ending Code on the Go. + } catch (e: JsonRpc.UnparsedReplyException) { + // Refused rather than parsed, so the call or listing fails with the rule the reply broke + // instead of a StackOverflowError ending Code on the Go. throw IOException("The server's reply to '$method' ${e.message}; it was not read.", e) } catch (e: Exception) { throw IOException("The server's reply to '$method' was not JSON-RPC: ${e.message}") diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormat.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormat.kt index 4795f1cd6..3076aaa88 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormat.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormat.kt @@ -57,11 +57,12 @@ object McpLogFormat { * [text] as indented JSON, or null when it is not JSON. An Exception or LinkageError from * [indent] is a body that is not JSON; any other Error, an OutOfMemoryError above all, propagates. * So would a StackOverflowError, which is why [text] never reaches [indent] when it nests - * deeper than [JsonDepth.MAX]: it is shown as it came. + * deeper than [JsonDepth.MAX], or is not strict JSON and could hide such nesting: it is shown + * as it came. * @param indent the parsing and indenting; injectable so a test can make it fail. */ internal fun json(text: String, indent: (String) -> String? = ::indentJson): String? { - if (JsonDepth.exceeds(text)) return null + if (JsonDepth.refusal(text) != null) return null val indented = runCatchingRecoverable { indent(text) }.getOrNull() // org.json escapes every '/', which turns each URL in a reply into noise. return indented?.replace("\\/", "/") diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepth.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepth.kt index 5b695c60f..44cce643a 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepth.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepth.kt @@ -6,8 +6,9 @@ package com.itsaky.androidide.plugins.aiagentmcp.transport * org.json parses recursively, once per array or object, and Android's has no limit of its own: * a body of nothing but `[` runs the thread out of stack, and the StackOverflowError ends Code on * the Go, whose process this plugin runs in. So a server's text is scanned first, in one pass with - * no recursion, and text nested deeper than [MAX] is never handed to a parser: a reply is refused - * ([JsonRpc.parseReply]), and a body in the connection log is shown as it came. + * no recursion, and text nested deeper than [MAX], or not strict JSON, is never handed to a parser: + * a reply is refused with the rule it broke ([JsonRpc.parseReply]), and a body in the connection + * log is shown as it came. */ internal object JsonDepth { @@ -15,9 +16,32 @@ internal object JsonDepth { const val MAX = 100 /** - * Whether [text] opens more than [limit] arrays or objects one inside another, or is not strict - * JSON where that could hide brackets; one pass, no recursion. A bracket inside a string does - * not count. + * Why [refusal] refused a text, kept apart so a server's author is told the rule their reply + * broke: a reply refused for a comment but reported as nested too deep sends them looking for + * nesting that is not there. + * @property reason what is wrong with the text, to follow "The server's reply to 'm' ". + */ + sealed interface Refusal { + val reason: String + + /** More than [limit] arrays or objects one inside another. */ + data class TooDeep(val limit: Int) : Refusal { + override val reason: String get() = "nests arrays and objects more than $limit levels deep" + } + + /** [found] outside a string, where strict JSON never has it. */ + data class NotStrict(val found: Char) : Refusal { + override val reason: String + get() = "is not strict JSON: a comment, single quote, ';', '=' or stray '\"' outside " + + "a string (found '$found')" + } + } + + /** + * Why [text] may not be parsed: it opens more than [limit] arrays or objects one inside + * another, or it is not strict JSON where that could hide brackets; null when it may. One + * pass, no recursion; the first rule broken is the one reported. A bracket inside a string + * does not count. * * The scan reads strict JSON, because Android's org.json is lenient: it also reads `;` as a * separator, `=` and `=>` between a name and its value, `//`, `/* */` and `#` comments, single @@ -32,7 +56,7 @@ internal object JsonDepth { * * Valid JSON is never refused for these rules, so no MCP reply is. */ - fun exceeds(text: String, limit: Int = MAX): Boolean { + fun refusal(text: String, limit: Int = MAX): Refusal? { var depth = 0 var inString = false var escaped = false @@ -49,16 +73,18 @@ internal object JsonDepth { } when (c) { ' ', '\t', '\n', '\r' -> continue - '\'', ';', '=', '/', '#' -> return true + '\'', ';', '=', '/', '#' -> return Refusal.NotStrict(c) '"' -> { - if (last != null && last != '[' && last != '{' && last != ',' && last != ':') return true + if (last != null && last != '[' && last != '{' && last != ',' && last != ':') { + return Refusal.NotStrict(c) + } inString = true } - '[', '{' -> if (++depth > limit) return true + '[', '{' -> if (++depth > limit) return Refusal.TooDeep(limit) ']', '}' -> if (depth > 0) depth-- } last = c } - return false + return null } } diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonRpc.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonRpc.kt index 5cd5bfeff..a4175443f 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonRpc.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonRpc.kt @@ -65,18 +65,20 @@ object JsonRpc { * A batch — which the spec allows and some servers send even for a single request — is reduced * to its first non-notification member, since this client only ever has one call in flight. * - * A document nested deeper than [JsonDepth.MAX] is refused before any parser sees it: parsing - * recurses once per level, and on Android a server's reply nested thousands deep would end in - * a StackOverflowError that nothing here may catch. + * A document nested deeper than [JsonDepth.MAX], or not strict JSON, is refused before any + * parser sees it: parsing recurses once per level, and on Android a server's reply nested + * thousands deep would end in a StackOverflowError that nothing here may catch. Text that is + * not strict JSON could hide such nesting from the scan, so it is refused too. * * @param payload one JSON-RPC document, object or array. * @return the reply, or null when the payload is not a reply at all (a server-initiated * request or notification, which this client does not answer). - * @throws TooDeepException when [payload] nests deeper than [JsonDepth.MAX]. + * @throws UnparsedReplyException when [payload] nests deeper than [JsonDepth.MAX] or is not + * strict JSON, its message naming which. */ fun parseReply(payload: String): Reply? { val trimmed = payload.trim() - if (JsonDepth.exceeds(trimmed)) throw TooDeepException() + JsonDepth.refusal(trimmed)?.let { throw UnparsedReplyException(it.reason) } val json = when { trimmed.startsWith("{") -> JSONObject(trimmed) trimmed.startsWith("[") -> org.json.JSONArray(trimmed).let { array -> @@ -122,7 +124,9 @@ object JsonRpc { return Reply(id = id, result = json.optJSONObject("result") ?: JSONObject()) } - /** A reply [parseReply] refused unparsed, for nesting deeper than [JsonDepth.MAX]. */ - class TooDeepException : - IllegalArgumentException("nests arrays and objects more than ${JsonDepth.MAX} levels deep") + /** + * A reply [parseReply] refused unparsed: nested deeper than [JsonDepth.MAX], or not strict JSON. + * @param reason the rule it broke, to follow "The server's reply to 'm' ". + */ + class UnparsedReplyException internal constructor(reason: String) : IllegalArgumentException(reason) } diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/DeepReplyTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/DeepReplyTest.kt index e27a42fdb..ed1f7d940 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/DeepReplyTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/DeepReplyTest.kt @@ -19,6 +19,10 @@ import org.junit.Test * would end Code on the Go. The reply is now refused before it is parsed. The org.json these tests * run on fails such a parse with a JSONException of its own, so the message is what tells the * guard's refusal apart. + * + * The reason is the rule the reply broke. A reply with a comment, refused because it is not strict + * JSON, was reported as nested more than 100 levels deep, and its server's author would look for + * nesting that is not there. */ class DeepReplyTest { @@ -57,4 +61,32 @@ class DeepReplyTest { failure.message, ) } + + @Test + fun `a reply one level past the limit fails the listing with the depth as its reason`() { + val depth = JsonDepth.MAX + 1 + val failure = assertThrows(IOException::class.java) { + session("[".repeat(depth) + "]".repeat(depth)).listTools() + } + + assertEquals( + "The server's reply to 'tools/list' nests arrays and objects more than ${JsonDepth.MAX} " + + "levels deep; it was not read.", + failure.message, + ) + } + + @Test + fun `a reply with a comment fails the listing as not strict JSON, not as nested too deep`() { + val reply = """{"jsonrpc":"2.0","id":2, // the listing + |"result":{"tools":[]}}""".trimMargin() + + val failure = assertThrows(IOException::class.java) { session(reply).listTools() } + + assertEquals( + "The server's reply to 'tools/list' is not strict JSON: a comment, single quote, ';', '=' " + + "or stray '\"' outside a string (found '/'); it was not read.", + failure.message, + ) + } } diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormatTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormatTest.kt index 395965872..b1902b744 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormatTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormatTest.kt @@ -130,6 +130,14 @@ class McpLogFormatTest { assertNotNull("brackets inside strings were counted", McpLogFormat.json(body)) } + @Test + fun givenABodyThatIsNotStrictJson_whenFormatted_thenItIsShownAsItCame() { + val body = """{"jsonrpc":"2.0","id":2,"result":{}} // done""" + + assertNull(McpLogFormat.json(body)) + assertEquals(body, McpLogFormat.pretty(body)) + } + /** Descends once per opening bracket at the start of [text], as a recursive-descent parser does. */ private fun recursiveIndent(text: String): String? { fun descend(index: Int): Int = diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepthTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepthTest.kt index 93722f380..58a8c5938 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepthTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepthTest.kt @@ -1,72 +1,74 @@ package com.itsaky.androidide.plugins.aiagentmcp.transport -import org.junit.Assert.assertFalse -import org.junit.Assert.assertTrue +import com.itsaky.androidide.plugins.aiagentmcp.transport.JsonDepth.Refusal +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull import org.junit.Test /** * The scan that keeps a server's deeply nested JSON from any parser. It may count too many - * brackets, which only refuses a body a parser could have read, never too few. + * brackets, which only refuses a body a parser could have read, never too few. Each refusal names + * the rule that tripped, too deep or not strict JSON, which is what the server's author is told. */ class JsonDepthTest { @Test fun `nesting at the limit passes and one level more does not`() { val depth = JsonDepth.MAX - assertFalse(JsonDepth.exceeds("[".repeat(depth) + "]".repeat(depth))) - assertTrue(JsonDepth.exceeds("[".repeat(depth + 1) + "]".repeat(depth + 1))) + assertNull(JsonDepth.refusal("[".repeat(depth) + "]".repeat(depth))) + assertEquals(Refusal.TooDeep(depth), JsonDepth.refusal("[".repeat(depth + 1) + "]".repeat(depth + 1))) } @Test fun `brackets inside strings do not count`() { val brackets = "[".repeat(500) // An escaped quote at the start of "b" and an escaped backslash at its end: neither ends it. - assertFalse(JsonDepth.exceeds("""{"a":"$brackets","b":"\"$brackets\\","c":["$brackets"]}""")) + assertNull(JsonDepth.refusal("""{"a":"$brackets","b":"\"$brackets\\","c":["$brackets"]}""")) } @Test fun `the characters refused outside a string are read as text inside one`() { val brackets = "[".repeat(500) val text = """{"a":"it's; a=b // c /* d */ # e","b":["'$brackets;=/#"],"c" : [ "x" , "y" ]}""" - assertFalse(JsonDepth.exceeds(text)) + assertNull(JsonDepth.refusal(text)) } @Test fun `a single-quoted string is refused`() { // Not JSON; Android's org.json reads it, and a quote inside it hides nothing from that parser. - assertTrue(JsonDepth.exceeds("['a']")) + assertEquals(Refusal.NotStrict('\''), JsonDepth.refusal("['a']")) } @Test fun `a semicolon separator hiding a closing bracket is refused`() { // Android's org.json reads ';' as a separator and "]" as a string, so each unit opens one // more array; a scan that took the quote for text counted each "]" as a close. - assertTrue(JsonDepth.exceeds("[;\"]\";".repeat(5_000))) + assertEquals(Refusal.NotStrict(';'), JsonDepth.refusal("[;\"]\";".repeat(5_000))) } @Test fun `a comment hiding a closing bracket is refused`() { // Android's org.json skips "//]" to the end of the line, so each unit opens one more array. - assertTrue(JsonDepth.exceeds("[//]\n".repeat(5_000))) + assertEquals(Refusal.NotStrict('/'), JsonDepth.refusal("[//]\n".repeat(5_000))) } @Test fun `a quote inside unquoted text is refused`() { // Android's org.json reads `a"` as one unquoted string, so the brackets after the comma // are arrays nested in it, not text inside a string the quote opened. - assertTrue(JsonDepth.exceeds("[a\",${"[".repeat(5_000)}")) - assertTrue(JsonDepth.exceeds("""{"x":1",${"[".repeat(5_000)}""")) + assertEquals(Refusal.NotStrict('"'), JsonDepth.refusal("[a\",${"[".repeat(5_000)}")) + assertEquals(Refusal.NotStrict('"'), JsonDepth.refusal("""{"x":1",${"[".repeat(5_000)}""")) } @Test fun `the brackets after a double quote inside a single-quoted string count`() { // org.json reads '"' as a one-character string, then recurses into the brackets after it. - assertTrue(JsonDepth.exceeds("['\"',${"[".repeat(200)}", 100)) + assertEquals(Refusal.NotStrict('\''), JsonDepth.refusal("['\"',${"[".repeat(200)}", 100)) } @Test fun `the brackets after a quote where no value starts count`() { // Android's org.json skips the comment, so no string starts at its quote. - assertTrue(JsonDepth.exceeds("[/*\"*/${"[".repeat(200)}", 100)) + assertEquals(Refusal.NotStrict('/'), JsonDepth.refusal("[/*\"*/${"[".repeat(200)}", 100)) } } diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonRpcTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonRpcTest.kt index 81f540244..8e26cbefa 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonRpcTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonRpcTest.kt @@ -111,7 +111,7 @@ class JsonRpcTest { */ @Test fun givenAReplyNestedTenThousandDeep_whenParsed_thenItIsRefusedBeforeAnyParserRuns() { - assertThrows(JsonRpc.TooDeepException::class.java) { JsonRpc.parseReply("[".repeat(10_000)) } + assertThrows(JsonRpc.UnparsedReplyException::class.java) { JsonRpc.parseReply("[".repeat(10_000)) } } @Test @@ -119,7 +119,26 @@ class JsonRpcTest { val nested = "[".repeat(JsonDepth.MAX) + "]".repeat(JsonDepth.MAX) val payload = """{"jsonrpc":"2.0","id":"7","result":{"tools":[],"extra":$nested}}""" - assertThrows(JsonRpc.TooDeepException::class.java) { JsonRpc.parseReply(payload) } + assertThrows(JsonRpc.UnparsedReplyException::class.java) { JsonRpc.parseReply(payload) } + } + + @Test + fun givenAReplyOneLevelPastTheLimit_whenParsed_thenTheDepthIsTheReason() { + val depth = JsonDepth.MAX + 1 + val failure = assertThrows(JsonRpc.UnparsedReplyException::class.java) { + JsonRpc.parseReply("[".repeat(depth) + "]".repeat(depth)) + } + + assertEquals(JsonDepth.Refusal.TooDeep(JsonDepth.MAX).reason, failure.message) + } + + @Test + fun givenAReplyWithAComment_whenParsed_thenNotStrictJsonIsTheReason() { + val payload = """{"jsonrpc":"2.0","id":"7","result":{}} // done""" + + val failure = assertThrows(JsonRpc.UnparsedReplyException::class.java) { JsonRpc.parseReply(payload) } + + assertEquals(JsonDepth.Refusal.NotStrict('/').reason, failure.message) } @Test From 6429174629fc67345c79d71e8bc19452ef334b7d Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 09:22:53 -0800 Subject: [PATCH 61/90] ADFA-7139 AI-Agent-MCP: a save ends the old session with the old credentials, and writes URL, token and headers in one step N5: after J2, the settings pane's save stored the new URL, token and headers and only then ended the old session. Its DELETE read the credentials for the old URL once the server had left it, so it carried none, and a server that wants its token to end a session refused it and kept the session open. M2: the save wrote the URL, then the token, then the headers, and credentialsFor's URL check and its token read were not atomic with those writes. A request reading between the URL write and the token write passed the check for the new URL and sent it the old token and headers; the other order could send the new token to the old URL. The save (McpSettingsViewModel.saveNow) now: 1. takes the server's session out (McpConnections.detach), reading its credentials while the store still holds the URL it was built for; 2. writes the URL, token and headers in one critical section, McpServerStore.saveConnection, under a store-level credentials lock that credentialsFor also takes (McpServerStore.readTogether); 3. ends the old session outside any lock, its DELETE carrying the credentials read in step 1. The lock is the store's own, not McpConnections': it is held across Keystore and SharedPreferences writes, and nothing waiting for the session map should sit behind that. It is taken before the store's list lock, never inside it, and no listener runs under it; the listeners are told once, after. J2's rule holds: the old token goes only to the old URL, and no request pairs the new URL with the old credentials or the old URL with the new. A call that looks the session up between steps 1 and 2 stores one for the old URL, which the next lookup replaces; that one ends with no credentials, as before this change. Every other writer: clearing the credential had N5's order too; it now takes the session out first and clears token and headers in one step (clearCredentialNow, McpServerStore.clearCredentials). saveDetails and remove take the credentials lock as well. setToken and setHeaders, whose only callers were these two, become the internal writeToken and writeHeaders, called only under the lock. Readers that pair a URL with credentials: credentialsFor (and through it keyFor, every request and detach) and saveCredentials, which deleteNow uses, now read the pair under the lock. There is no import path. Tests (SaveServerSessionTest): editing the URL and the token sends the old server a DELETE with the old token and headers, and the new URL's first request the new ones; a request forced from inside the token write, on another thread, gets the new pair (it waits on the lock) and never the new URL with the old token; clearing the credentials ends the session with the ones it had. The first and third fail with the old order restored (DELETE without credentials); the second fails with credentialsFor's lock removed (the new URL gets the old token). MovedServerCredentialTest's expectations are unchanged: a session of the old URL ended once the server has moved (one a lookup stored between the take-out and the write, or a request still running) still gets none of the new credentials. Its KDoc now says that the save itself takes the old session out first. README: the save rule. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- plugins/AI-Agent-MCP/README.md | 11 +- .../aiagentmcp/client/McpConnections.kt | 17 ++- .../aiagentmcp/settings/McpServerStore.kt | 136 +++++++++++++---- .../settings/McpSettingsViewModel.kt | 78 ++++++---- .../client/MovedServerCredentialTest.kt | 9 +- .../settings/McpSettingsHeadersToStoreTest.kt | 7 +- .../settings/SaveServerSessionTest.kt | 139 ++++++++++++++++++ 7 files changed, 332 insertions(+), 65 deletions(-) create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/SaveServerSessionTest.kt diff --git a/plugins/AI-Agent-MCP/README.md b/plugins/AI-Agent-MCP/README.md index 9e45d951b..09bb3a873 100644 --- a/plugins/AI-Agent-MCP/README.md +++ b/plugins/AI-Agent-MCP/README.md @@ -180,9 +180,14 @@ Two dependencies were deliberately not taken: version needs **26.48 or later**, the first release that ships `DebuggerEndpointService` (`plugin.min_ide_version`); users on 26.47 or older cannot install it. 26.48 assumes the release after 26.47 ships it; recheck it against the real release number before merging. -- A server's token and headers go only to the URL it is saved with. When the URL - is edited, the old session is ended, and any of its requests still running - finish, with neither: the token entered for the new URL never reaches the old. +- A server's token and headers go only to the URL it is saved with. A save + writes the URL, token and headers in one step that a request's credential + read waits for, so no request pairs the new URL with the old token, or the + old URL with the new. The old session is taken out before that step and + ended after it, its DELETE carrying the credentials it was opened with, so a + server that wants its token to end a session gets it; any of its requests + still running after the save finish with neither. Clearing the credential + ends the session the same way. - Redirects are never followed automatically. A 3xx is repeated only when it resolves to the same origin, so the bearer token and the user's own headers cannot be replayed to another host in one hop. diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt index d77a22ac4..68b8cb1f8 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt @@ -162,9 +162,10 @@ object McpConnections { * * @return them, or null for a server not stored or credentials that could not be read. */ - fun saveCredentials(serverId: String): SavedCredentials? { - val url = McpServerStore.server(serverId)?.url ?: return null - return runCatchingRecoverable { SavedCredentials(url, credentialsFor(serverId, url)) } + fun saveCredentials(serverId: String): SavedCredentials? = McpServerStore.readTogether { + // The URL and the credentials read together, so they are the pair the server has. + val url = McpServerStore.server(serverId)?.url ?: return@readTogether null + runCatchingRecoverable { SavedCredentials(url, credentialsFor(serverId, url)) } .onFailure { e -> Log.d(TAG, "Could not read the credentials to end '$serverId' with: $e") } .getOrNull() } @@ -249,8 +250,9 @@ object McpConnections { * `close()` and any call still in flight cannot hand the credentials meant for the new URL * to the old one. That holds for an automatic entry, whose replaced endpoint would get the * new process's token, and for a server of the user's, whose old URL would get the token - * and headers the user entered for the new one: the settings pane stores them before it - * ends the old session. + * and headers the user entered for the new one. A user's server's URL is read with its + * credentials, under the store's credentials lock, which a save holds while it writes all + * three: a read between its writes would pair the new URL with the old token and headers. * @return its token and headers; either may be empty. * @throws UnreadableSecretException when a stored credential cannot be decrypted here. Sending * the request without it would earn a 401 and tell the user their token was refused. @@ -262,6 +264,11 @@ object McpConnections { // Read per request, so a token refreshed on the same port is used without a new session. return automaticCredentials(AutomaticServers.endpoint(serverId), url) } + return McpServerStore.readTogether { storedCredentials(serverId, url) } + } + + /** [credentialsFor] for a server of the user's. Call under `McpServerStore.readTogether`. */ + private fun storedCredentials(serverId: String, url: String): McpCredentials { // A server removed since, or moved to another URL, gets nothing; checked before the // Keystore is read, so its secrets are not even decrypted. if (McpServerStore.server(serverId)?.url != url) return McpCredentials("", emptyMap()) diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStore.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStore.kt index 2efd47458..a37eee864 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStore.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStore.kt @@ -49,6 +49,26 @@ object McpServerStore { */ private val lock = Any() + /** + * Held while a server's URL, token or headers are written, and while a request reads its + * credentials together with the URL they are for ([readTogether]). A reader then finds the URL + * with the credentials saved with it, never the new URL with the old token or the old URL with + * the new: a save writes the three one after another, and a request reading between two of + * those writes paired one server's URL with another's credentials. + * + * Its own lock, not [lock] and not `McpConnections`': it is held across Keystore work, which + * nothing waiting for the server list or the session map should sit behind. Taken before + * [lock], never inside it. Nothing runs under it but this store's own reads and writes, the + * Keystore's among them, never a listener. + */ + private val credentialsLock = Any() + + /** + * Runs [read] holding [credentialsLock]: what it reads of one server's URL, token and headers + * was saved together. For a request's credentials, read with the URL they go to. + */ + internal fun readTogether(read: () -> T): T = synchronized(credentialsLock, read) + /** * Registers [listener], called after any change to the servers or their toggles. Adding one * already registered does nothing, so a host that activates the plugin twice still gets one @@ -94,14 +114,80 @@ object McpServerStore { * @return the record as it now stands, for a caller holding a snapshot to refresh from. */ fun saveDetails(server: McpServer): McpServer { - val merged = synchronized(lock) { - mergeDetails(servers().firstOrNull { it.id == server.id }, server) - .also(::upsertLocked) - } + val merged = synchronized(credentialsLock) { saveDetailsLocked(server) } fireChanged() return merged } + /** [saveDetails] without telling the listeners. Call holding [credentialsLock]. */ + private fun saveDetailsLocked(server: McpServer): McpServer = synchronized(lock) { + mergeDetails(servers().firstOrNull { it.id == server.id }, server).also(::upsertLocked) + } + + /** + * What [saveConnection] stored. + * @property server the record as it now stands, for a caller holding a snapshot to refresh + * from. + * @property tokenStored false when a token was given and could not be stored. + * @property headersStored false when headers were given and could not be stored. + */ + data class SavedConnection( + val server: McpServer, + val tokenStored: Boolean, + val headersStored: Boolean, + ) + + /** + * Stores what the add/edit dialog owns: the name and URL, as [saveDetails] does, and when given + * the token and the headers. All in one step under [credentialsLock], so a request reading its + * credentials ([readTogether]) finds the old URL with the old ones or the new URL with the new, + * never one with the other. The listeners are told once, after. + * + * Keystore work, so call this off the main thread. + * + * @param server the candidate, carrying the id plus the edited name and URL. + * @param token the token to store, blank to forget it, or null to keep the stored one. + * @param headers the headers to store, replacing the stored ones, empty to forget them, or null + * to keep them. + * @return the record as it now stands, and which credentials could not be stored. + */ + fun saveConnection( + server: McpServer, + token: String?, + headers: Map?, + ): SavedConnection { + val saved = synchronized(credentialsLock) { + val merged = saveDetailsLocked(server) + SavedConnection( + server = merged, + tokenStored = token?.let { writeToken(server.id, it) } ?: true, + headersStored = headers?.let { writeHeaders(server.id, it) } ?: true, + ) + } + fireChanged() + return saved + } + + /** + * Forgets a server's token and every extra header, in one step under [credentialsLock]. + * + * Keystore work, so call this off the main thread. + * + * @param id the server. + * @return true when neither is stored any more. + */ + fun clearCredentials(id: String): Boolean { + val cleared = synchronized(credentialsLock) { + // Both, whatever the first returned: a token left behind is no reason to keep the + // headers. + val token = writeToken(id, "") + val headers = writeHeaders(id, emptyMap()) + token && headers + } + fireChanged() + return cleared + } + /** * Merges a dialog's edits onto the stored record. * @@ -156,33 +242,34 @@ object McpServerStore { * @param id the server to remove. */ fun remove(id: String) { - synchronized(lock) { - prefs()?.edit() - ?.remove(KEY_TOKEN_PREFIX + id) - ?.remove(KEY_HEADERS_PREFIX + id) - ?.apply() - writeLocked(servers().filterNot { it.id == id }) + // The credentials lock too, like every write of a URL or a credential. + synchronized(credentialsLock) { + synchronized(lock) { + prefs()?.edit() + ?.remove(KEY_TOKEN_PREFIX + id) + ?.remove(KEY_HEADERS_PREFIX + id) + ?.apply() + writeLocked(servers().filterNot { it.id == id }) + } } fireChanged() } /** - * Stores a server's bearer token, encrypted; blank forgets it. + * Stores a server's bearer token, encrypted; blank forgets it. Call holding [credentialsLock], + * through [saveConnection] or [clearCredentials], which tell the listeners: a new credential + * has to reach the agent, or it keeps calling with the old one until something else happens to + * touch the store. * - * Keystore work, so call this off the main thread. + * Internal for the tests, which have no Keystore to write to. * * @param id the server the token belongs to. * @param token the token, or blank to remove it. * @return true once it is on disk, or removed for a blank one; false when encrypting it or the * write itself failed, which is what the pane must not report as saved. */ - fun setToken(id: String, token: String): Boolean { - val stored = secureTokenStore.write(prefs(), KEY_TOKEN_PREFIX + id, token) - // Like every other mutator: a new credential has to reach the agent, or it keeps calling - // with the old one until something else happens to touch the store. - fireChanged() - return stored - } + internal fun writeToken(id: String, token: String): Boolean = + secureTokenStore.write(prefs(), KEY_TOKEN_PREFIX + id, token) /** * Reads a server's bearer token. @@ -235,9 +322,8 @@ object McpServerStore { } /** - * Stores a server's extra headers, encrypted; an empty map forgets them. - * - * Keystore work, so call this off the main thread. + * Stores a server's extra headers, encrypted; an empty map forgets them. Call holding + * [credentialsLock], as for [writeToken]. * * @param id the server the headers belong to. * @param headers the headers to store; unusable pairs are dropped. @@ -245,7 +331,7 @@ object McpServerStore { * or the write itself failed. Forgetting them on a store that was never opened is success: * there is nothing on disk to remove. */ - fun setHeaders(id: String, headers: Map): Boolean { + internal fun writeHeaders(id: String, headers: Map): Boolean { val clean = McpHeaders.sanitize(headers) val key = KEY_HEADERS_PREFIX + id // The empty map goes through write() as a blank, which removes the entry, rather than @@ -261,9 +347,7 @@ object McpServerStore { // A clear with no preferences behind it has nothing to remove, so it succeeded; only a // write with something to store has genuinely failed. val prefs = prefs() ?: return clean.isEmpty() - val stored = secureTokenStore.write(prefs, key, payload) - fireChanged() - return stored + return secureTokenStore.write(prefs, key, payload) } /** Whether any extra header is configured for [id], without decrypting them. */ diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt index c7b6cc229..b7a6c8621 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt @@ -137,10 +137,10 @@ class McpSettingsViewModel( * What the header rows mean when saving, given whether the stored ones could be read. * * The token's rule, applied to headers: the rows replace what is stored only when the dialog - * drew what is stored. Otherwise they mean nothing about it — [setHeaders] replaces the whole - * map, so writing one typed row over a set nobody could read would delete headers the user was - * just told were intact. The dialog refuses such a save instead, and [clearCredential] is the - * way back to none. + * drew what is stored. Otherwise they mean nothing about it — [McpServerStore.saveConnection] + * replaces the whole map, so writing one typed row over a set nobody could read would delete + * headers the user was just told were intact. The dialog refuses such a save instead, and + * [clearCredential] is the way back to none. * * @param collected the header rows as they currently stand. * @param headersKnown whether those rows reflect what is stored. @@ -168,25 +168,43 @@ class McpSettingsViewModel( onDone: (McpServer, String?) -> Unit, ) { viewModelScope.launch { - val outcome = withContext(Dispatchers.IO) { - val merged = McpServerStore.saveDetails(server) - val tokenStored = token?.let { McpServerStore.setToken(server.id, it.trim()) } ?: true - val headersStored = headers?.let { McpServerStore.setHeaders(server.id, it) } ?: true - // A credential change has to invalidate the session, or the old one keeps working. - McpConnections.invalidate(server.id) - McpServerHealth.credentialChanged(server.id) - val failure = when { - !tokenStored -> string(R.string.mcp_token_save_failed) - !headersStored -> string(R.string.mcp_headers_save_failed) - else -> null - } - merged to failure - } + val outcome = withContext(Dispatchers.IO) { saveNow(server, token, headers) } reload() onDone(outcome.first, outcome.second) } } + /** + * [save]'s blocking part, off the main thread. + * + * A credential or URL change has to end the session, or the old one keeps working. It is taken + * out first, its credentials read while the store still holds the URL it was built for; then + * the URL, token and headers are written in one step that a request's credential read waits + * for; then it is ended, outside every lock. So its DELETE carries the old credentials, which a + * server that wants its token to end a session needs, and only to the old URL: the old token + * never reaches the new URL, nor the new token the old. A call that looks the session up in + * between stores one for the old URL, which the next lookup replaces; it ends with no + * credentials, since the server no longer points there. + * + * @return the merged record and a status sentence, null when everything worked. + */ + internal fun saveNow( + server: McpServer, + token: String?, + headers: Map?, + ): Pair { + val released = McpConnections.detach(server.id) + val saved = McpServerStore.saveConnection(server, token?.trim(), headers) + released?.close() + McpServerHealth.credentialChanged(server.id) + val failure = when { + !saved.tokenStored -> string(R.string.mcp_token_save_failed) + !saved.headersStored -> string(R.string.mcp_headers_save_failed) + else -> null + } + return saved.server to failure + } + /** * Forgets a server's stored credential: the token and every extra header. * @@ -199,18 +217,26 @@ class McpSettingsViewModel( */ fun clearCredential(id: String, onDone: (Boolean) -> Unit) { viewModelScope.launch { - val cleared = withContext(Dispatchers.IO) { - val tokenCleared = McpServerStore.setToken(id, "") - val headersCleared = McpServerStore.setHeaders(id, emptyMap()) - // The session was keyed by the credential it no longer has. - McpConnections.invalidate(id) - McpServerHealth.credentialChanged(id) - tokenCleared && headersCleared - } + val cleared = withContext(Dispatchers.IO) { clearCredentialNow(id) } onDone(cleared) } } + /** + * [clearCredential]'s blocking part, off the main thread. The session was keyed by the + * credential it no longer has, so it is ended, in [saveNow]'s order: taken out with the + * credentials it had, so its DELETE carries them, ended once they are cleared. + * + * @return true when nothing is stored any more. + */ + internal fun clearCredentialNow(id: String): Boolean { + val released = McpConnections.detach(id) + val cleared = McpServerStore.clearCredentials(id) + released?.close() + McpServerHealth.credentialChanged(id) + return cleared + } + /** * Removes a server, its token, its session and its cached tools. * @param id the server to remove. diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/MovedServerCredentialTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/MovedServerCredentialTest.kt index 34eb8e8c3..1f27be499 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/MovedServerCredentialTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/MovedServerCredentialTest.kt @@ -24,11 +24,16 @@ import org.junit.Test * A server of the user's moved to another URL never hands the credentials entered for the new URL * to the old one. * - * The settings pane stores the new URL, token and headers, and only then ends the old session. Its + * The settings pane stored the new URL, token and headers, and only then ended the old session. Its * DELETE read the server's credentials without asking which URL they were for, so it went to the * old URL with the new token and headers; so did any request of the old session still running. * The credentials are now released only to a session built for the URL the server has, the rule a * SQLite debugger entry already followed. + * + * The save now takes the old session out before it writes, so that session's DELETE carries the + * old credentials (SaveServerSessionTest). The rule still holds for any session of the old URL + * ended once the server has moved: one a call stored between that take-out and the write, which the + * next lookup replaces, and every request still running on the old session. */ class MovedServerCredentialTest { @@ -89,7 +94,7 @@ class MovedServerCredentialTest { assertFalse("the old URL was sent the user's headers", "x-team" in listing.headerNames) } - /** What the settings pane's save stores, before it ends the old session. */ + /** What the settings pane's save stores; a session of the old URL is ended after it. */ private fun moveToTheNewUrl(saved: McpServer) { McpServerStore.saveDetails(saved.copy(url = url(moved))) token = "new-token" diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsHeadersToStoreTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsHeadersToStoreTest.kt index 7e3ddb306..b1359d0aa 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsHeadersToStoreTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsHeadersToStoreTest.kt @@ -7,9 +7,10 @@ import org.junit.Test /** * What the header rows mean when the dialog saves them. * - * `setHeaders` replaces the whole stored map, so this predicate is the only thing standing between - * a keystore that would not answer and a user losing headers they were just told were intact: the - * rows on screen may replace what is stored only when the dialog drew what is stored. + * `McpServerStore.saveConnection` replaces the whole stored map, so this predicate is the only + * thing standing between a keystore that would not answer and a user losing headers they were just + * told were intact: the rows on screen may replace what is stored only when the dialog drew what is + * stored. */ class McpSettingsHeadersToStoreTest { diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/SaveServerSessionTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/SaveServerSessionTest.kt new file mode 100644 index 000000000..4078ee2d0 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/SaveServerSessionTest.kt @@ -0,0 +1,139 @@ +package com.itsaky.androidide.plugins.aiagentmcp.settings + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.aiagentmcp.testing.awaitFinishedOrBlockedBy +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpToolCatalog +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import kotlin.concurrent.thread +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * Saving a server's new URL and token ends the old session with the old credentials, and a request + * reading the credentials meanwhile gets the old URL's or the new URL's, never one with the other. + * + * The save stored the URL, then the token, then the headers, and only then ended the old session. + * Its DELETE read the credentials for the old URL once the server had left it, so it carried none, + * and a server that wants its token to end a session refused it and kept the session open. A + * request reading the credentials between the URL write and the token write passed the URL check + * for the new URL and sent it the old token and headers. The session is now taken out first, with + * the credentials it had, the three are written in one step a request's read waits for, and the + * session is ended last. + * + * The request between the two writes is made from inside the token write, on another thread, and + * the test waits until it has finished or is blocked on a lock the saving thread holds. Nothing + * sleeps. + */ +class SaveServerSessionTest { + + private val old = FakeMcpServer("old-token", listOf(tool("search", true)), sessionId = "old-session") + private val moved = FakeMcpServer("new-token", listOf(tool("search", true))) + + // The Keystore is not there on the JVM: the store answers what was last written. + @Volatile private var token = "old-token" + @Volatile private var headers = mapOf("X-Old" to "1") + + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } answers { + token.takeIf { it.isNotEmpty() }?.let { KeystoreSecretStore.Stored.Value(it) } + ?: KeystoreSecretStore.Stored.Absent + } + every { McpServerStore.headers(any()) } answers { headers } + every { McpServerStore.writeToken(any(), any()) } answers { token = secondArg(); true } + every { McpServerStore.writeHeaders(any(), any()) } answers { headers = secondArg(); true } + } + + @After + fun tearDown() { + McpConnections.closeAll() + McpToolCatalog.clear() + old.stop() + moved.stop() + plugin.dispose() + unmockkObject(McpServerStore) + } + + @Test + fun `editing the URL and the token ends the old session with the old token, and the new URL gets the new one`() { + val saved = McpServerStore.saveDetails(McpServerStore.newServer("Docs", url(old))) + McpConnections.withSession(saved) { it.initialize() } + + McpSettingsViewModel { null }.saveNow(saved.copy(url = url(moved)), "new-token", mapOf("X-New" to "1")) + + val delete = old.requests.single { it.httpMethod == "DELETE" } + assertEquals("the old session's DELETE did not carry the old token", "Bearer old-token", delete.authorization) + assertTrue("the old session's DELETE did not carry the old headers", "x-old" in delete.headerNames) + assertFalse("the old URL was sent the new headers", "x-new" in delete.headerNames) + + McpConnections.withSession(McpServerStore.server(saved.id)!!) { it.initialize() } + val first = moved.requests.first() + assertEquals("the new URL's first request did not carry the new token", "Bearer new-token", first.authorization) + assertTrue("the new URL's first request did not carry the new headers", "x-new" in first.headerNames) + assertFalse("the new URL was sent the old headers", "x-old" in first.headerNames) + } + + @Test + fun `a request between the URL write and the token write gets the old pair or the new, never a mix`() { + val saved = McpServerStore.saveDetails(McpServerStore.newServer("Docs", url(old))) + val saver = Thread.currentThread() + var lookup: Thread? = null + var found: Thread.State? = null + every { McpServerStore.writeToken(saved.id, any()) } answers { + // The URL is written, the token not yet: a request for the server as it now stands. + val current = McpServerStore.server(saved.id)!! + lookup = thread(name = "lookup") { + runCatching { McpConnections.withSession(current) { it.initialize() } } + } + found = awaitFinishedOrBlockedBy(lookup!!, saver) + token = secondArg() + true + } + + McpSettingsViewModel { null }.saveNow(saved.copy(url = url(moved)), "new-token", mapOf("X-New" to "1")) + lookup!!.join(10_000) + + assertTrue("the request never reached the new URL", moved.requests.isNotEmpty()) + moved.requests.forEach { request -> + assertEquals( + "a request read between the URL write and the token write (found $found) sent the new URL", + "Bearer new-token" to setOf("x-new"), + request.authorization to request.headerNames.filterTo(mutableSetOf()) { it.startsWith("x-") }, + ) + } + } + + @Test + fun `clearing the credentials ends the session with the ones it had`() { + val saved = McpServerStore.saveDetails(McpServerStore.newServer("Docs", url(old))) + McpConnections.withSession(saved) { it.initialize() } + + val cleared = McpSettingsViewModel { null }.clearCredentialNow(saved.id) + + assertTrue(cleared) + val delete = old.requests.single { it.httpMethod == "DELETE" } + assertEquals("the session's DELETE did not carry its token", "Bearer old-token", delete.authorization) + assertTrue("the session's DELETE did not carry its headers", "x-old" in delete.headerNames) + } + + private fun url(server: FakeMcpServer) = "http://127.0.0.1:${server.port}/mcp" +} From 9071b25a8bea18f3b32a0cf74ca77bd773163ade Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 09:31:53 -0800 Subject: [PATCH 62/90] ADFA-7139 AI-Agent-MCP: a stale probe or listing of a moved server neither marks it refused nor replaces its session M1: a health probe, a listing or a call that read the server before its URL was edited asks the old URL, which J2 gives no credentials. Its 401 made recordFailure mark the server degraded(refused=true) after the edit's credentialChanged had cleared that, so the probe skipped the server until the user edited it again. Its lookUp, which checked by id only, also stored the old URL's session under sessions[id] in place of the new URL's, ending that one. McpServers.isConfigured now takes the server: one of the user's counts only when McpServerStore.server(id)?.url == server.url. lookUp returns kept=false for a URL that differs from the stored one, so a stale call neither stores its session nor ends the good one, and withSession ends its own; the health writes in connect, recordFailure and a tool call's success, and the catalog's tool write, check the same, under the locks they already used. A SQLite debugger entry still counts by id: a call that EndpointRetry repeats on the entry's new endpoint records its outcome under the server it started with, whose URL is the old one. Tests (StaleServerAfterEditTest): after a URL edit and a listing of the new URL, a listing of the old URL leaves the server AVAILABLE, not degraded and refused, and does not end the new URL's session. Both fail without the fix. RemovalDuringRecordTest's isConfigured mock takes the server now. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../aiagentmcp/client/McpConnections.kt | 8 +- .../aiagentmcp/debugger/AutomaticServers.kt | 16 +++- .../aiagentmcp/tools/McpToolCatalog.kt | 18 ++-- .../plugins/aiagentmcp/tools/McpToolSource.kt | 7 +- .../tools/RemovalDuringRecordTest.kt | 2 +- .../tools/StaleServerAfterEditTest.kt | 91 +++++++++++++++++++ 6 files changed, 124 insertions(+), 18 deletions(-) create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/StaleServerAfterEditTest.kt diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt index 68b8cb1f8..43134d06f 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt @@ -48,7 +48,9 @@ object McpConnections { * * A server no longer configured gets a session that is not kept: the caller is a call or a * listing that outlived the server's removal, and a session stored for it would outlive the - * server with nothing left to close it. The check is made under this object's lock, which the + * server with nothing left to close it. So does a server of the user's whose URL has been + * edited since the caller read it ([McpServers.isConfigured]): its session, for the old URL, + * would replace the one for the new. The check is made under this object's lock, which the * removal of a SQLite debugger entry takes, to detach its session, only after the entry has * left the list; so either that removal takes the session out or this sees the entry gone. A * server of the user's is removed from the store after its session is ended, so its DELETE @@ -89,7 +91,7 @@ object McpConnections { /** * What [lookUp] found. * @property kept whether [session] is the one stored for its server; false for a server no - * longer configured. + * longer configured, or no longer at the URL the caller had. */ private class Found(val session: McpSession, val kept: Boolean) @@ -107,7 +109,7 @@ object McpConnections { // A supplier, not the values: the session is kept for the life of the process, and a // token in one of its fields would be readable in a heap dump for just as long. val fresh = McpSession(server.url, { credentialsFor(server.id, server.url) }) - if (!McpServers.isConfigured(server.id)) return Found(fresh, kept = false) + if (!McpServers.isConfigured(server)) return Found(fresh, kept = false) stale = current?.second fresh.also { sessions[server.id] = key to it } } diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt index e6b04b98f..d1a4d6c28 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt @@ -328,8 +328,18 @@ object McpServers { fun all(): List = McpServerStore.servers() + AutomaticServers.servers() /** - * Whether [serverId] is configured now: the check that keeps a call or a listing which outlived - * a server's removal from bringing back that server's session or health. + * Whether [server] is configured now: the check that keeps a call or a listing which outlived + * a server's removal from bringing back that server's session, health or tools. + * + * A server of the user's counts only at the URL [server] carries. A probe, a listing or a call + * handed the server before its URL was edited asks the old URL, which gets no credentials + * (`McpConnections.credentialsFor`): its 401 would otherwise mark the server refused after the + * edit had cleared that, so the probe skipped it until the next edit, and its session would + * replace the one for the new URL. A SQLite debugger entry counts by id: a call retried on its + * new endpoint (`EndpointRetry`) records its outcome under the entry it started with, and its + * session is keyed by URL and token anyway. */ - fun isConfigured(serverId: String): Boolean = all().any { it.id == serverId } + fun isConfigured(server: McpServer): Boolean = + if (AutomaticServers.isAutomatic(server.id)) AutomaticServers.endpoint(server.id) != null + else McpServerStore.server(server.id)?.url == server.url } diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt index a76861923..a13550e6e 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt @@ -87,15 +87,17 @@ object McpToolCatalog { exchangeListener: McpExchangeListener = McpExchangeListener.NONE, ): Listing { // Each checked with its write, under the lock a removal takes: a server deleted while the - // handshake was in flight, even just after a check, gets no row back. - McpServerHealth.connectingIfUnknown(server.id, McpServers::isConfigured) + // handshake was in flight, even just after a check, gets no row back, nor one whose URL was + // edited since [server] was read. + val configured = { _: String -> McpServers.isConfigured(server) } + McpServerHealth.connectingIfUnknown(server.id, configured) val listing = try { retry.call(server) { list(it, exchangeListener) } } catch (e: Throwable) { recordFailure(server, e) throw e } - McpServerHealth.available(server.id, McpServers::isConfigured) + McpServerHealth.available(server.id, configured) return listing } @@ -114,13 +116,13 @@ object McpToolCatalog { } val context = McpPlugin.getContext()?.androidContext val refused = failure is McpFailure.TokenRefused || failure is McpFailure.Forbidden - // Not for a server removed meanwhile, checked with the write as in connect. + // Not for a server removed meanwhile, or moved to another URL, checked with the write as in + // connect: a stale caller's 401 from the old URL must not mark the moved server refused. McpServerHealth.degraded( server.id, McpErrorFormatter.format(context, server, error), refused, - McpServers::isConfigured, - ) + ) { McpServers.isConfigured(server) } } /** The handshake-and-list itself; see [connect]. */ @@ -154,10 +156,10 @@ object McpToolCatalog { } } else { val stored = synchronized(lock) { - McpServers.isConfigured(server.id).also { if (it) toolsByServer[server.id] = tools } + McpServers.isConfigured(server).also { if (it) toolsByServer[server.id] = tools } } if (!stored) { - Log.i(TAG, "Dropping a tool list from '${server.name}', removed while it listed") + Log.i(TAG, "Dropping a tool list from '${server.name}', removed or moved while it listed") return Listing(serverName, tools) } McpServerStore.setKnownTools(server.id, tools.map { it.name }) diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt index 5cb513f5c..a350d0601 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt @@ -217,9 +217,10 @@ class McpToolSource internal constructor( McpConnections.withSession(target) { it.callTool(tool.name, arguments, call.handle) } } // A reply of any kind, a tool's own failure included, means the server is answering; - // unless it was removed while the call ran, when recording it would bring back its row. - // Checked with the write, under the lock the removal takes, so it cannot land between. - McpServerHealth.available(server.id, McpServers::isConfigured) + // unless it was removed while the call ran, when recording it would bring back its row, + // or moved to another URL. Checked with the write, under the lock the removal takes, so + // it cannot land between. + McpServerHealth.available(server.id) { McpServers.isConfigured(server) } Outcome(result.success, result.text, result.errorMessage) } catch (e: Throwable) { // Throwable, unlike the other host-facing catches in this plugin: this runs inside diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/RemovalDuringRecordTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/RemovalDuringRecordTest.kt index eeea73c38..8daed3459 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/RemovalDuringRecordTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/RemovalDuringRecordTest.kt @@ -70,7 +70,7 @@ class RemovalDuringRecordTest { val configured = callOriginal() if (trigger() && fired.compareAndSet(false, true)) { val checking = Thread.currentThread() - val id = firstArg() + val id = firstArg().id val removal = thread(name = "removing") { McpSettingsViewModel { null }.deleteNow(id) } removals += removal awaitFinishedOrBlockedBy(removal, checking) diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/StaleServerAfterEditTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/StaleServerAfterEditTest.kt new file mode 100644 index 000000000..f2b6e9aef --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/StaleServerAfterEditTest.kt @@ -0,0 +1,91 @@ +package com.itsaky.androidide.plugins.aiagentmcp.tools + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServer +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * A probe or a listing handed one of the user's servers before its URL was edited neither marks + * the server refused nor replaces its session. + * + * Such a caller asks the old URL, which gets no credentials once the server has moved. Its 401 + * marked the server degraded and refused after the edit had cleared that, so the probe skipped it + * until the user edited it again; and its lookup, by id alone, stored a session for the old URL in + * place of the one for the new, ending that one. A server of the user's now counts as configured + * only at the URL it is stored with. + */ +class StaleServerAfterEditTest { + + private val before = FakeMcpServer("t", listOf(tool("search", true)), sessionId = "before") + private val after = FakeMcpServer("t", listOf(tool("search", true)), sessionId = "after") + + private lateinit var plugin: McpPlugin + private lateinit var stale: McpServer + private lateinit var current: McpServer + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + // The Keystore is not there on the JVM. + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } returns KeystoreSecretStore.Stored.Value("t") + every { McpServerStore.headers(any()) } returns emptyMap() + + // A probe read the server, then the user moved it, and the new URL was listed. + stale = McpServerStore.saveDetails(McpServerStore.newServer("Docs", url(before))) + current = McpServerStore.saveDetails(stale.copy(url = url(after))) + McpServerHealth.credentialChanged(current.id) + McpToolCatalog.connect(current) + } + + @After + fun tearDown() { + McpConnections.closeAll() + McpToolCatalog.clear() + before.stop() + after.stop() + plugin.dispose() + unmockkObject(McpServerStore) + } + + @Test + fun `a listing of the old URL after the edit does not mark the server refused`() { + assertThrows(Exception::class.java) { McpToolCatalog.connect(stale) } + + assertEquals( + "a listing of the old URL changed the moved server's health", + McpServerHealth.Health(McpServerHealth.State.AVAILABLE), + McpServerHealth.of(current.id), + ) + } + + @Test + fun `a listing of the old URL after the edit does not replace the stored session`() { + assertThrows(Exception::class.java) { McpToolCatalog.connect(stale) } + + assertTrue( + "the session for the new URL was ended to store one for the old", + after.requests.none { it.httpMethod == "DELETE" }, + ) + } + + private fun url(server: FakeMcpServer) = "http://127.0.0.1:${server.port}/mcp" +} From cb844f71f296865326260422585f00c3637c2b30 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 09:32:45 -0800 Subject: [PATCH 63/90] ADFA-7139 AI-Agent-MCP: an Error from the check before sending is not logged as a cancel checkBeforeSend (McpHttpClient.post) caught every Throwable to mark the exchange cancelled before rethrowing it. That broke the plugin's rule against catching Throwable, and an Error from beforeSend, an OutOfMemoryError for instance, was recorded in the connection log as a request the user cancelled. It now marks the record only for an Exception, which is how a cancel arrives (McpCallHandle.throwIfCancelled throws InterruptedIOException); an Error propagates unmarked and is recorded as the failure it is. The brief's `passed` flag (try { beforeSend(); passed = true } finally { if (!passed) cancelled = true }) also avoids catching Throwable, but its finally runs for an Error too, so it would still log one as a cancel; catching Exception does both. A cancel landing after the second check, before the answer is asked for, still relies on Android's disconnect() failing the request; that limit is unchanged and stays in McpCallHandle's KDoc. Test (CancelledExchangeLogTest): an OutOfMemoryError from beforeSend leaves a record that is not marked cancelled. It fails without the fix. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../aiagentmcp/transport/McpHttpClient.kt | 19 +++++++++++------- .../transport/CancelledExchangeLogTest.kt | 20 +++++++++++++++++++ 2 files changed, 32 insertions(+), 7 deletions(-) diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt index 0d99e804b..a2b074440 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt @@ -175,8 +175,9 @@ open class McpHttpClient( * the request unsent. A `disconnect()` before the connection exists does nothing, so a cancel * landing just after [onConnected] is caught here or not at all. Without a streaming mode the * write only fills a buffer and the request goes out when the answer is first read, so the - * second run catches a cancel that landed during the write. A request it ends is recorded - * as cancelled, never as sent ([McpExchange.cancelled]). + * second run catches a cancel that landed during the write. A request it ends with an + * Exception is recorded as cancelled, never as sent ([McpExchange.cancelled]); an Error + * propagates and is recorded as the failure it is. * @param exchangeListener receives each request made and what came back, redirects included. * An Exception or a LinkageError it throws is dropped; any other Error propagates. * @return the reply document and any session id the server sent. @@ -218,11 +219,15 @@ open class McpHttpClient( var failure: Throwable? = null // Set when beforeSend ends the request: nothing went out, and its record must not say so. var cancelled = false - fun checkBeforeSend() = try { - beforeSend() - } catch (e: Throwable) { - cancelled = true - throw e + fun checkBeforeSend() { + try { + beforeSend() + } catch (e: Exception) { + // A cancel, which beforeSend throws as an InterruptedIOException. An Error is + // not one: the process is failing, and its record must not read "cancelled". + cancelled = true + throw e + } } val redirect = try { // Connected here rather than by the first write, so beforeSend runs in between: a diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/CancelledExchangeLogTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/CancelledExchangeLogTest.kt index faa4e70e5..d05e36446 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/CancelledExchangeLogTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/CancelledExchangeLogTest.kt @@ -21,6 +21,9 @@ import org.junit.Test * The record was built the same way whether the request had gone out or not, so the log showed * the request's headers and body marked as sent, then "no response". It now says the request was * cancelled before it was sent, and shows none of it as sent. + * + * Only a cancel is recorded so. The check caught every Throwable to mark the record, so an + * OutOfMemoryError while checking was logged as a cancel; an Error now propagates unmarked. */ class CancelledExchangeLogTest { @@ -72,4 +75,21 @@ class CancelledExchangeLogTest { ) assertTrue("the transcript does not say it was cancelled:\n$transcript", "* " in transcript) } + + @Test + fun `an Error from the check before sending is not logged as a cancel`() { + val exchanges = CopyOnWriteArrayList() + + assertThrows(OutOfMemoryError::class.java) { + McpHttpClient().post( + url = "http://127.0.0.1:${server.address.port}/mcp", + token = "", + body = JSONObject().put("jsonrpc", "2.0").put("id", 1).put("method", "tools/call"), + beforeSend = { throw OutOfMemoryError("reading the cancel flag") }, + exchangeListener = { exchange, _ -> exchanges += exchange }, + ) + } + + assertFalse("an OutOfMemoryError was recorded as a cancel", exchanges.single().cancelled) + } } From 2b5ea248901d85e3bc25a4e068b3ffeb6e669d3a Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 09:35:43 -0800 Subject: [PATCH 64/90] ADFA-7139 AI-Agent-MCP: a cancel caught as the request publishes its connection is logged as cancelled McpHttpClient.post ran onConnected(conn), where the call's handle publishes the connection and reads the cancel flag (McpCallHandle.attach), before the try whose finally records the exchange. A cancel caught there threw past the record, so the connection log showed nothing of the request; only a cancel caught by beforeSend was logged as cancelled. onConnected now runs inside the try, marked like beforeSend: an Exception from it ends the request unsent and is recorded as cancelled, and an Error propagates unmarked. Test (CancelledExchangeLogTest): with the handle cancelled before the request, attach throws, nothing reaches the server, and the log holds one exchange marked cancelled. It fails without the fix: no exchange is recorded. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../aiagentmcp/transport/McpHttpClient.kt | 22 +++++++++------- .../transport/CancelledExchangeLogTest.kt | 26 +++++++++++++++++++ 2 files changed, 39 insertions(+), 9 deletions(-) diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt index a2b074440..1e77acc36 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt @@ -169,7 +169,8 @@ open class McpHttpClient( * @param sessionId the session to continue, or null before one exists. * @param protocolVersion the negotiated revision, or null before `initialize` has answered. * @param onConnected receives each request's connection, redirect hops included, before it is - * connected, so a caller can disconnect it to cancel. + * connected, so a caller can disconnect it to cancel. What it throws ends the request unsent, + * and is recorded as [beforeSend]'s is: a cancel it catches, as cancelled. * @param beforeSend runs once that connection is connected, before anything is written to it, * and again once the body is written, before the answer is asked for; what it throws ends * the request unsent. A `disconnect()` before the connection exists does nothing, so a cancel @@ -211,35 +212,38 @@ open class McpHttpClient( doOutput = true } val trace = McpExchangeTrace("POST", target, headers, payload, bytes.size, redactor) - onConnected(conn) // Only a socket that cannot be reused is disconnected: `disconnect()` evicts it from // the pool, so doing it on the success path made every call — initialize, each // tools/list page, each tools/call — pay a fresh TCP and TLS handshake. var reusable = false var failure: Throwable? = null - // Set when beforeSend ends the request: nothing went out, and its record must not say so. + // Set when onConnected or beforeSend ends the request: nothing went out, and its record + // must not say so. var cancelled = false - fun checkBeforeSend() { + fun unsentIfThrows(step: () -> Unit) { try { - beforeSend() + step() } catch (e: Exception) { - // A cancel, which beforeSend throws as an InterruptedIOException. An Error is - // not one: the process is failing, and its record must not read "cancelled". + // A cancel, which both throw as an InterruptedIOException. An Error is not one: + // the process is failing, and its record must not read "cancelled". cancelled = true throw e } } val redirect = try { + // Inside the try, so a cancel caught here, as the call's handle publishes the + // connection, leaves its record in the connection log like one caught below. + unsentIfThrows { onConnected(conn) } // Connected here rather than by the first write, so beforeSend runs in between: a // cancel whose disconnect came before the connection existed dropped nothing, and the // write would connect and send the request regardless. conn.connect() - checkBeforeSend() + unsentIfThrows(beforeSend) conn.outputStream.use { it.write(bytes) } // Again: the write only filled a buffer, and the request goes out at the first read // of the answer, just below. A cancel that landed meanwhile disconnected a connection // the JDK connects again at that read, sending the request after all. - checkBeforeSend() + unsentIfThrows(beforeSend) trace.answered(conn) val next = conn.redirectTargetFrom(target) if (next == null) { diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/CancelledExchangeLogTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/CancelledExchangeLogTest.kt index d05e36446..af814906a 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/CancelledExchangeLogTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/CancelledExchangeLogTest.kt @@ -1,5 +1,6 @@ package com.itsaky.androidide.plugins.aiagentmcp.transport +import com.itsaky.androidide.plugins.aiagentmcp.client.McpCallHandle import com.itsaky.androidide.plugins.aiagentmcp.errors.McpTranscript import com.sun.net.httpserver.HttpServer import java.io.InterruptedIOException @@ -22,6 +23,9 @@ import org.junit.Test * the request's headers and body marked as sent, then "no response". It now says the request was * cancelled before it was sent, and shows none of it as sent. * + * A cancel the call's handle catches as the request publishes its connection, before the checks + * below it, is recorded the same way; it left no record at all, so the log did not show the request. + * * Only a cancel is recorded so. The check caught every Throwable to mark the record, so an * OutOfMemoryError while checking was logged as a cancel; an Error now propagates unmarked. */ @@ -76,6 +80,28 @@ class CancelledExchangeLogTest { assertTrue("the transcript does not say it was cancelled:\n$transcript", "* " in transcript) } + @Test + fun `a request cancelled as its connection is published is logged as cancelled`() { + val exchanges = CopyOnWriteArrayList() + val handle = McpCallHandle().apply { cancel() } + + val cancel = assertThrows(InterruptedIOException::class.java) { + McpHttpClient().post( + url = "http://127.0.0.1:${server.address.port}/mcp", + token = "", + body = JSONObject().put("jsonrpc", "2.0").put("id", 1).put("method", "tools/call"), + onConnected = { handle.attach(it) }, + exchangeListener = { exchange, _ -> exchanges += exchange }, + ) + } + val transcript = McpTranscript.render(exchanges.toList(), cancel, labels) { it } + + assertEquals("the cancelled request reached the server", 0, bodies.get()) + assertEquals("the cancelled request left no record in the connection log", 1, exchanges.size) + assertTrue("the record does not say the request was cancelled", exchanges.single().cancelled) + assertTrue("the transcript does not say it was cancelled:\n$transcript", "* " in transcript) + } + @Test fun `an Error from the check before sending is not logged as a cancel`() { val exchanges = CopyOnWriteArrayList() From 450b78d5cf367f7dcfcc7f2a1dab55cd683140fd Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 09:36:44 -0800 Subject: [PATCH 65/90] ADFA-7139 AI-Agent-MCP: the configured check under the health, catalog and session locks reads no preferences McpServers.isConfigured runs under the health lock, the catalog lock and McpConnections' lock, and it read the stored server list from SharedPreferences and parsed every server's JSON on each call. AutomaticServers.readEndpoints, which takes McpConnections' and the health lock while holding its own, could stall behind that read. I/O under a lock, not a deadlock. McpServerStore now keeps the list it last read or wrote, with the preferences it belongs to: every write puts the list it wrote there (as a read would give it back), and a read puts what it read only by compare-and-set against what it saw first, so a read that raced a write never puts the older list back. servers() and server(id) answer from it, so the check reads nothing and parses nothing. A plugin initialized again with other preferences reads them afresh. The other suggestion, parsing once outside the lock and passing a boolean, would undo what the lock is for: a removal landing between that check and the write would have its health row or tools brought back. Tests (ConfiguredCheckReadTest): the check makes no getString call on the preferences, and answers from the list last written, a move and a removal included. The first fails without the fix. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../aiagentmcp/settings/McpServerStore.kt | 42 ++++++++++-- .../settings/ConfiguredCheckReadTest.kt | 67 +++++++++++++++++++ 2 files changed, 103 insertions(+), 6 deletions(-) create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/ConfiguredCheckReadTest.kt diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStore.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStore.kt index a37eee864..8851e0470 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStore.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStore.kt @@ -11,6 +11,7 @@ import com.itsaky.androidide.plugins.aiagentmcp.transport.McpHeaders import com.itsaky.androidide.plugins.security.KeystoreSecretStore import java.util.UUID import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.atomic.AtomicReference import org.json.JSONArray import org.json.JSONObject @@ -40,6 +41,22 @@ object McpServerStore { private val listeners = CopyOnWriteArrayList<() -> Unit>() + /** + * The server list as last read or written, with the preferences it belongs to. + * + * The check that a server is still configured (`McpServers.isConfigured`) runs under the health, + * catalog and session locks, and a SQLite debugger entry's refresh waits on two of them while it + * holds its own. Read from the preferences, that check parsed every server's JSON under them; + * answered from here, it reads nothing and parses nothing. + * + * Every write puts the list it wrote here. A read puts what it read only by compare-and-set + * against what it saw first, so a read that raced a write never puts the older list back. Kept + * with the preferences it came from: a plugin initialized again reads its own afresh. + */ + private class Snapshot(val prefs: SharedPreferences, val servers: List) + + private val snapshot = AtomicReference(null) + /** * Serialises every read-modify-write of the server list. * @@ -91,18 +108,28 @@ object McpServerStore { * @return the servers; empty before any is configured, or when the stored blob is unreadable. */ fun servers(): List { - val raw = prefs()?.getString(KEY_SERVERS, null) ?: return emptyList() + val prefs = prefs() ?: return emptyList() + val seen = snapshot.get() + if (seen != null && seen.prefs === prefs) return seen.servers + val read = parse(prefs.getString(KEY_SERVERS, null)) + snapshot.compareAndSet(seen, Snapshot(prefs, read)) + return read + } + + /** The stored list in [raw], empty when there is none or it is unreadable. */ + private fun parse(raw: String?): List { + if (raw == null) return emptyList() return try { - val array = JSONArray(raw) - (0 until array.length()).mapNotNull { index -> - array.optJSONObject(index)?.let(::toServer) - } + fromJson(JSONArray(raw)) } catch (e: Exception) { Log.e(TAG, "Stored server list is unreadable; treating it as empty", e) emptyList() } } + private fun fromJson(array: JSONArray): List = + (0 until array.length()).mapNotNull { index -> array.optJSONObject(index)?.let(::toServer) } + /** * Stores the two fields the add/edit dialog owns, leaving every other field as stored. * @@ -397,7 +424,10 @@ object McpServerStore { private fun writeLocked(servers: List) { val array = JSONArray() servers.forEach { array.put(toJson(it)) } - prefs()?.edit()?.putString(KEY_SERVERS, array.toString())?.apply() + val prefs = prefs() ?: return + prefs.edit().putString(KEY_SERVERS, array.toString()).apply() + // As a read would give it back, a blank name already filled in from the URL. + snapshot.set(Snapshot(prefs, fromJson(array))) } private fun toJson(server: McpServer): JSONObject = JSONObject().apply { diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/ConfiguredCheckReadTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/ConfiguredCheckReadTest.kt new file mode 100644 index 000000000..78240ce4a --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/ConfiguredCheckReadTest.kt @@ -0,0 +1,67 @@ +package com.itsaky.androidide.plugins.aiagentmcp.settings + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.debugger.McpServers +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import io.mockk.clearMocks +import io.mockk.every +import io.mockk.mockk +import io.mockk.spyk +import io.mockk.verify +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * The check that a server is still configured, made under the health, catalog and session locks, + * reads no preferences, and so parses no stored JSON there. + * + * It read the stored server list and parsed every server's JSON on each call, under those locks; a + * SQLite debugger entry's refresh, which waits on two of them while holding its own, waited behind + * that read. The store now answers from the list it last read or wrote. + */ +class ConfiguredCheckReadTest { + + private val prefs = spyk(FakeSharedPreferences()) + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns prefs + plugin = McpPlugin().also { it.initialize(context) } + } + + @After + fun tearDown() { + plugin.dispose() + } + + @Test + fun `the configured check reads no preferences`() { + val saved = McpServerStore.saveDetails(McpServerStore.newServer("Docs", "http://127.0.0.1:1/mcp")) + clearMocks(prefs, answers = false, recordedCalls = true, childMocks = false) + + assertTrue(McpServers.isConfigured(saved)) + assertFalse(McpServers.isConfigured(saved.copy(url = "http://127.0.0.1:2/mcp"))) + + verify(exactly = 0) { prefs.getString(any(), any()) } + } + + @Test + fun `the list it answers from is the one last written`() { + val saved = McpServerStore.saveDetails(McpServerStore.newServer("", "http://127.0.0.1:1/mcp")) + val moved = McpServerStore.saveDetails(saved.copy(url = "http://127.0.0.1:2/mcp")) + + assertTrue(McpServers.isConfigured(moved)) + assertFalse(McpServers.isConfigured(saved)) + // As read back from the preferences: a blank name is the URL. + assertEquals("http://127.0.0.1:2/mcp", McpServerStore.server(saved.id)?.name) + McpServerStore.remove(saved.id) + assertFalse(McpServers.isConfigured(moved)) + } +} From bbe6463c874b2a6d425fa6ba5cb5a40716a1d0d5 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 09:42:08 -0800 Subject: [PATCH 66/90] ADFA-7139 AI-Agent-MCP: a teardown that fails late still ends its sessions, and an Error ending one ends the rest If a step of releaseConnections after McpConnections.detachAll() threw (McpToolCatalog.clear() or AutomaticServers.install(null)), the list of sessions taken out was lost with the return value: they never got their DELETE, and their servers kept them open. dispose then also skipped pluginContext = null. endSessions stopped at the first Error from a session's close (which survives only an Exception or a LinkageError), and the sessions after it were never ended. The lifecycle calls now pass teardown a list that releaseConnections fills as soon as detachAll() returns, before the later steps, and each caller ends that list in a finally. dispose clears pluginContext in a finally after that. Ending the sessions moved to McpConnections.endAll, which closeAll uses too: it ends every session, collects an Error from any of them, and throws the first once all have been tried, the rest added as suppressed. lifecycleLock is internal with @VisibleForTesting, and LifecycleSessionCloseTest uses it directly instead of by reflection. Tests: TeardownFailureSessionTest (a deactivation and a disposal whose last teardown step throws still send the session's DELETE; the disposal also clears the context) and EndAllSessionsTest (four sessions, the first and third throwing an OutOfMemoryError: the other two are ended, the first Error is thrown and the second is suppressed into it). Each fails without its fix. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../aiagentmcp/client/McpConnections.kt | 19 +++- .../plugins/aiagentmcp/plugin/McpPlugin.kt | 104 +++++++++++------- .../aiagentmcp/client/EndAllSessionsTest.kt | 74 +++++++++++++ .../plugin/LifecycleSessionCloseTest.kt | 7 +- .../plugin/TeardownFailureSessionTest.kt | 89 +++++++++++++++ 5 files changed, 245 insertions(+), 48 deletions(-) create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/EndAllSessionsTest.kt create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/TeardownFailureSessionTest.kt diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt index 43134d06f..5196045a8 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt @@ -205,7 +205,24 @@ object McpConnections { /** Ends every session, for the plugin shutting down. */ fun closeAll() { - detachAll().forEach { it.close() } + endAll(detachAll()) + } + + /** + * Ends each of [released], best effort, as [Released.close] does one. An Error from one, which + * [Released.close] lets through, does not stop the rest: each is ended, and the first Error is + * thrown once they all have been, the others added to it as suppressed. + */ + fun endAll(released: List) { + var first: Error? = null + for (session in released) { + try { + session.close() + } catch (e: Error) { + first?.addSuppressed(e) ?: run { first = e } + } + } + first?.let { throw it } } /** diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt index 789df403b..ecad1539e 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt @@ -1,6 +1,7 @@ package com.itsaky.androidide.plugins.aiagentmcp.plugin import android.util.Log +import androidx.annotation.VisibleForTesting import com.itsaky.androidide.plugins.IPlugin import com.itsaky.androidide.plugins.PluginContext import com.itsaky.androidide.plugins.PluginLifecycleListener @@ -73,14 +74,17 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { * * Nothing taken under it waits for this plugin's own work or for the network: the host's * listener and service registries do not call back, the coroutines it cancels never take it, - * and [teardown] only takes the sessions out, returning them. The lifecycle call that ran it - * ends them once it has let go ([endSessions]): a session's `close()` sends a DELETE and can - * first wait, up to about 70 s, for a handshake in flight to let go of the session, and a + * and [teardown] only takes the sessions out, into its caller's list. The lifecycle call that + * ran it ends them once it has let go ([endSessions]): a session's `close()` sends a DELETE + * and can first wait, up to about 70 s, for a handshake in flight to let go of the session, and a * lifecycle call or AI Core's registration arriving meanwhile must not wait behind it. Each * call ends only the sessions its own teardown took out, so one arriving meanwhile neither * ends another's nor waits for them. + * + * Internal for the test that holds it while a lifecycle call runs. */ - private val lifecycleLock = Any() + @VisibleForTesting + internal val lifecycleLock = Any() /** * Background work: listing tools is network work and never belongs on the main thread. @@ -243,17 +247,21 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { } override fun activate(): Boolean { - val (activated, released) = synchronized(lifecycleLock) { activateLocked() } - // A failed activation tears down what it started, sessions included. - endSessions(released) - return activated + val released = mutableListOf() + try { + return synchronized(lifecycleLock) { activateLocked(released) } + } finally { + // A failed activation tears down what it started, sessions included. + endSessions(released) + } } /** * [activate] itself, under [lifecycleLock]. - * @return whether it worked, and the sessions a failed one's teardown took out, to end. + * @param released receives the sessions a failed one's teardown took out, to end. + * @return whether it worked. */ - private fun activateLocked(): Pair> = try { + private fun activateLocked(released: MutableList): Boolean = try { // Cancelled and replaced as one step: a host that activates twice would otherwise orphan // the running scope, and the launch below has to use this activation's scope, not whatever // a concurrent lifecycle call has since installed. @@ -292,12 +300,14 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { if (refreshed > 0 && isActive) settingsChanged() probeHealth({ isActive }) } - true to emptyList() + true } catch (e: Exception) { - false to activationFailed(e) + activationFailed(e, released) + false } catch (e: LinkageError) { // A host call outside the guards above, from a host whose plugin-api differs. - false to activationFailed(e) + activationFailed(e, released) + false } /** @@ -307,34 +317,44 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { * stop the scope it had started or remove the listeners it had registered by then. * * @param e what ended the activation. - * @return the sessions the teardown took out, for [activate] to end. + * @param released receives the sessions the teardown took out, for [activate] to end. */ - private fun activationFailed(e: Throwable): List { - val released = teardown() + private fun activationFailed(e: Throwable, released: MutableList) { + teardown(released) runCatchingRecoverable { context.logger.error("McpPlugin: activation failed", e) } - return released } override fun deactivate(): Boolean { - var released = emptyList() - val deactivated = synchronized(lifecycleLock) { - try { - released = teardown() - true - } catch (e: Exception) { - context.logger.error("McpPlugin: deactivation failed", e) - false + val released = mutableListOf() + try { + return synchronized(lifecycleLock) { + try { + teardown(released) + true + } catch (e: Exception) { + context.logger.error("McpPlugin: deactivation failed", e) + false + } } + } finally { + // The sessions taken out before a step of the teardown failed, too. + endSessions(released) } - endSessions(released) - return deactivated } override fun dispose() { - val released = synchronized(lifecycleLock) { teardown() } - // Before the context goes: a session's DELETE reads its credentials through it. - endSessions(released) - pluginContext = null + val released = mutableListOf() + try { + synchronized(lifecycleLock) { teardown(released) } + } finally { + // Before the context goes: a session's DELETE reads its credentials through it. Both + // whatever the teardown threw, the sessions it took out by then included. + try { + endSessions(released) + } finally { + pluginContext = null + } + } context.logger.info("McpPlugin: disposed") } @@ -343,9 +363,7 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { * own [teardown] took out, never another's. Called once that call has let go of * [lifecycleLock], never under it; see there. */ - private fun endSessions(released: List) { - for (session in released) session.close() - } + private fun endSessions(released: List) = McpConnections.endAll(released) /** * Stops what [activate] started: the lifecycle and change listeners, the tool source's @@ -355,10 +373,11 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { * [lifecycleLock]; taken here too, so a new caller cannot forget it. The sessions are only taken * out here; the lifecycle call ends them after it has let go ([endSessions]). * - * @return the sessions taken out, each with the credentials read as it was taken out, for the - * caller alone to end. + * @param released receives the sessions taken out, each with the credentials read as it was + * taken out, for the caller alone to end. Filled as they are taken out, so the caller still + * has them when a later step throws. */ - private fun teardown(): List = synchronized(lifecycleLock) { + private fun teardown(released: MutableList) = synchronized(lifecycleLock) { // Guarded: a host whose plugin-api differs answers with a LinkageError, and one escaping // here would skip every step below, leaving the scope and its probe running. runCatchingRecoverable { context.removePluginLifecycleListener(aiCoreLifecycle) } @@ -371,7 +390,7 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { // Before the connections are closed: an in-flight refresh would otherwise repopulate the // catalogue and the session map straight after they were cleared. stopScope() - releaseConnections() + releaseConnections(released) } /** @@ -561,17 +580,18 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { * Closes the tool source, takes every session out, and forgets the cached tool lists. Under * [lifecycleLock], with [teardown]. * - * @return the sessions taken out, for the lifecycle call to end ([endSessions]). + * @param released receives the sessions taken out, for the lifecycle call to end + * ([endSessions]), before the steps after it run: one of those throwing must not lose them, + * or they would never get their DELETE. */ - private fun releaseConnections(): List { + private fun releaseConnections(released: MutableList) { toolSource?.close() toolSource = null // Before the entries are cleared below: each session's credentials are read as it is taken // out, and a SQLite debugger entry's token leaves with its entry. - val released = McpConnections.detachAll() + released += McpConnections.detachAll() McpToolCatalog.clear() AutomaticServers.install(null) - return released } /** diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/EndAllSessionsTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/EndAllSessionsTest.kt new file mode 100644 index 000000000..bfcc1f19f --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/EndAllSessionsTest.kt @@ -0,0 +1,74 @@ +package com.itsaky.androidide.plugins.aiagentmcp.client + +import com.itsaky.androidide.plugins.aiagentmcp.transport.McpExchangeListener +import com.itsaky.androidide.plugins.aiagentmcp.transport.McpHttpClient +import java.net.HttpURLConnection +import java.util.concurrent.CopyOnWriteArrayList +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertSame +import org.junit.Assert.assertThrows +import org.junit.Test + +/** + * Ending the sessions a lifecycle call took out ends every one of them, even when ending one + * throws an Error, and then throws that Error. + * + * A session's close survives an Exception or a LinkageError and lets any other Error through. The + * loop over the sessions stopped at the first, and every session after it was never ended, so its + * server kept it open. Each is now ended, and the first Error is thrown after the last. + */ +class EndAllSessionsTest { + + private val ended = CopyOnWriteArrayList() + + /** A session with a server-side id, whose DELETE throws [failure], or is recorded when null. */ + private fun session(url: String, failure: Error? = null) = McpSession( + url, + { McpCredentials("", emptyMap()) }, + object : McpHttpClient() { + override fun post( + url: String, + token: String, + body: JSONObject, + sessionId: String?, + protocolVersion: String?, + extraHeaders: Map, + onConnected: (HttpURLConnection) -> Unit, + beforeSend: () -> Unit, + exchangeListener: McpExchangeListener, + ): Response = when (body.optString("method")) { + "initialize" -> Response( + """{"jsonrpc":"2.0","id":${body.get("id")},"result":{"protocolVersion":"2025-03-26"}}""", + "session-of-$url", + ) + else -> Response(null, null) + } + + override fun deleteSession(url: String, token: String, sessionId: String, extraHeaders: Map) { + failure?.let { throw it } + ended += url + } + }, + ).also { it.initialize() } + + @Test + fun `an Error ending one session does not stop the others, and the first is thrown after them`() { + val first = OutOfMemoryError("ending a") + val second = OutOfMemoryError("ending c") + val released = listOf( + session(url("a"), first), + session(url("b")), + session(url("c"), second), + session(url("d")), + ).map { McpConnections.Released(it, "", null) } + + val thrown = assertThrows(OutOfMemoryError::class.java) { McpConnections.endAll(released) } + + assertEquals("the sessions after a failing one were not ended", listOf(url("b"), url("d")), ended) + assertSame("not the first Error", first, thrown) + assertSame("the second Error was lost", second, thrown.suppressed.single()) + } + + private fun url(name: String) = "http://127.0.0.1:1/$name" +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/LifecycleSessionCloseTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/LifecycleSessionCloseTest.kt index 517a9000e..84332c363 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/LifecycleSessionCloseTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/LifecycleSessionCloseTest.kt @@ -133,8 +133,7 @@ class LifecycleSessionCloseTest { * * A health listener holds the deactivation at its teardown's last steps, after the sessions are * taken out, in a wait on the lifecycle lock, which lets that lock go: the window, opened for as - * long as the test needs. The lock is private, so the test reaches it by reflection. Nothing - * sleeps. + * long as the test needs. The lock is internal for this test. Nothing sleeps. */ @Test @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") // wait and notifyAll on the lock's own monitor @@ -146,9 +145,7 @@ class LifecycleSessionCloseTest { McpConnections.session(saved).initialize() // A health row, so the teardown's clearing of the cache tells the health listeners. McpServerHealth.available(saved.id) - val lock = McpPlugin::class.java.getDeclaredField("lifecycleLock") - .apply { isAccessible = true } - .get(plugin) as java.lang.Object + val lock = plugin.lifecycleLock as java.lang.Object val held = CountDownLatch(1) var resume = false val hold = { diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/TeardownFailureSessionTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/TeardownFailureSessionTest.kt new file mode 100644 index 000000000..bde31bd08 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/TeardownFailureSessionTest.kt @@ -0,0 +1,89 @@ +package com.itsaky.androidide.plugins.aiagentmcp.plugin + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticServers +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpToolCatalog +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Before +import org.junit.Test + +/** + * A lifecycle call whose teardown fails after it has taken the sessions out still ends them, and a + * disposal still lets go of the plugin context. + * + * The teardown returned the sessions it took out only once its last step had run. A step after + * the take-out that threw, clearing the SQLite debugger entries here, lost them: nothing ended + * them, so their servers kept them open. A disposal also skipped clearing the context. The + * sessions now go into the caller's list as they are taken out, and the caller ends them whatever + * the teardown threw. + */ +class TeardownFailureSessionTest { + + private val server = FakeMcpServer("", listOf(tool("search", true)), sessionId = "session-1") + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + // The Keystore is not there on the JVM. + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } returns KeystoreSecretStore.Stored.Absent + every { McpServerStore.headers(any()) } returns emptyMap() + val saved = McpServerStore.saveDetails( + McpServerStore.newServer("Docs", "http://127.0.0.1:${server.port}/mcp") + ) + McpConnections.withSession(saved) { it.initialize() } + // The teardown's last step, after the sessions are taken out. + mockkObject(AutomaticServers) + every { AutomaticServers.install(null) } throws IllegalStateException("clearing the entries failed") + } + + @After + fun tearDown() { + unmockkObject(AutomaticServers) + McpConnections.closeAll() + McpToolCatalog.clear() + server.stop() + plugin.dispose() + unmockkObject(McpServerStore) + } + + @Test + fun `a deactivation whose teardown fails after taking the sessions out still ends them`() { + assertFalse(plugin.deactivate()) + + assertEquals( + "the session taken out before the failing step was never ended", + 1, + server.requests.count { it.httpMethod == "DELETE" }, + ) + } + + @Test + fun `a disposal whose teardown fails still ends the sessions and lets go of the context`() { + assertThrows(IllegalStateException::class.java) { plugin.dispose() } + + assertEquals( + "the session taken out before the failing step was never ended", + 1, + server.requests.count { it.httpMethod == "DELETE" }, + ) + assertNull("the disposal kept the plugin context", McpPlugin.getContext()) + } +} From 99f677a75922ff2f0cf870f8896e974134e22461 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 09:48:48 -0800 Subject: [PATCH 67/90] ADFA-7139 AI-Agent-MCP: remove McpConnections.session(), which only tests used After 55e58046 every caller in the plugin looks a session up through withSession, which ends a session it was handed but not kept. session() was left for the tests, and could still return an unkept session that nobody ended. It is removed rather than made to end that session: a session it ended before returning would be useless to its caller. Its KDoc on which servers get an unkept session moved to withSession, and the tests that used it go through withSession, the path the plugin uses. No behaviour changes, so no failing test. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../aiagentmcp/client/McpConnections.kt | 39 +++++++------------ .../settings/McpSettingsViewModel.kt | 2 +- .../client/MovedServerCredentialTest.kt | 4 +- .../client/ReplacedEndpointCredentialTest.kt | 4 +- .../debugger/RemovedEntryCleanupTest.kt | 4 +- .../plugin/LifecycleSessionCloseTest.kt | 4 +- .../settings/DeleteServerSessionTest.kt | 10 ++--- 7 files changed, 27 insertions(+), 40 deletions(-) diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt index 5196045a8..11b8714b9 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt @@ -42,9 +42,11 @@ object McpConnections { private val sessions = ConcurrentHashMap>() /** - * The session for [server], created if needed. - * - * Reads the token and the headers, so call this off the main thread. + * Runs [block] with [server]'s session, created if needed, and ends the session once [block] is + * done when it was not kept. Nothing else would end that one, so the server would keep the + * session its `initialize` assigned. Its DELETE reads the credentials as each of its requests + * did, under the same rule: only for the URL it was built for, while the server still has it, + * so a server that is gone gets none, as the requests did. * * A server no longer configured gets a session that is not kept: the caller is a call or a * listing that outlived the server's removal, and a session stored for it would outlive the @@ -57,23 +59,8 @@ object McpConnections { * still has the credentials; the settings pane ends whatever a lookup stored between the two * once the server is gone. * - * A session that is not kept is the caller's to end; [withSession] does that, and is what a - * request should use. - * - * @param server the server to connect to. - * @return its session, not yet initialized. - */ - fun session(server: McpServer): McpSession = lookUp(server).session - - /** - * Runs [block] with [server]'s session, as [session] finds or builds it, and ends the session - * once [block] is done when it was not kept, for a server no longer configured. Nothing else - * would end that one, so the server would keep the session its `initialize` assigned. Its DELETE - * reads the credentials as each of its requests did, under the same rule: only for the URL it - * was built for, while the server still has it, so a server that is gone gets none, as the - * requests did. - * - * Blocking, like [block]: ending the session sends a DELETE. + * Reads the token and the headers, and is blocking, like [block]: ending the session sends a + * DELETE. Call it off the main thread. * * @param server the server to connect to. * @param block the calls to make; the session is not yet initialized. @@ -95,7 +82,7 @@ object McpConnections { */ private class Found(val session: McpSession, val kept: Boolean) - /** [session] itself, telling a session it kept from one it did not. */ + /** Finds or builds [server]'s session for [withSession], telling one it kept from one it did not. */ private fun lookUp(server: McpServer): Found { val key = keyFor(server) @@ -182,11 +169,11 @@ object McpConnections { * caller that must take it out under a lock of its own and end it once that lock is let go, * since ending it sends a DELETE. * - * Taken under this object's lock, as [session] replaces a session under it. The credentials are - * read once that is let go, still under the caller's lock: for a server of the user's that is a - * Keystore read, never network. Safe to call under another lock: under this one, [session] only - * reads the configured servers, which takes no lock (`McpServers.all`), and it reads the - * credentials before it takes this one. + * Taken under this object's lock, as [withSession] replaces a session under it. The credentials + * are read once that is let go, still under the caller's lock: for a server of the user's that is + * a Keystore read, never network. Safe to call under another lock: under this one, [withSession] + * only checks the server is configured, which takes no lock (`McpServers.isConfigured`), and it + * reads the credentials before it takes this one. * * @return the session taken out, or null when [serverId] had none. */ diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt index b7a6c8621..6b50d99b8 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt @@ -254,7 +254,7 @@ class McpSettingsViewModel( * The session is ended before the server is removed, so its DELETE still has the credentials * the removal deletes. A call or a listing that looked the session up between the two stored * a new one, which would outlive the server; it is ended again once the server is gone, when - * no lookup stores one any more (McpConnections.session keeps none for a server no longer + * no lookup stores one any more (McpConnections.withSession keeps none for a server no longer * configured). That second DELETE carries the credentials read before the server was removed, * whether or not there was a first session, best effort; only to a session built for the URL * they were read for, so none to a session for a URL the server has left. diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/MovedServerCredentialTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/MovedServerCredentialTest.kt index 1f27be499..1083e336e 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/MovedServerCredentialTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/MovedServerCredentialTest.kt @@ -69,7 +69,7 @@ class MovedServerCredentialTest { @Test fun `the old session's DELETE carries none of the credentials entered for the new URL`() { val saved = McpServerStore.saveDetails(McpServerStore.newServer("Docs", url(old))) - McpConnections.session(saved).initialize() + McpConnections.withSession(saved) { it.initialize() } assertEquals("the old session did not carry the old token", "Bearer old-token", old.requests.first().authorization) moveToTheNewUrl(saved) @@ -83,7 +83,7 @@ class MovedServerCredentialTest { @Test fun `a request of the old session after the move carries none of the new credentials`() { val saved = McpServerStore.saveDetails(McpServerStore.newServer("Docs", url(old))) - val session = McpConnections.session(saved).also { it.initialize() } + val session = McpConnections.withSession(saved) { it.also { kept -> kept.initialize() } } moveToTheNewUrl(saved) session.listTools() diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/ReplacedEndpointCredentialTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/ReplacedEndpointCredentialTest.kt index fda4e6a69..633e3732b 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/ReplacedEndpointCredentialTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/ReplacedEndpointCredentialTest.kt @@ -34,13 +34,13 @@ class ReplacedEndpointCredentialTest { var stored = listOf(AutomaticEndpoint(app, old.port, "old-token")) AutomaticServers.install { stored } - val session = McpConnections.session(AutomaticServers.servers().single()) + val session = McpConnections.withSession(AutomaticServers.servers().single()) { it } session.listTools() assertTrue("the session opened against the old endpoint", old.requests.any { it.httpMethod == "POST" }) stored = listOf(AutomaticEndpoint(app, replacement.port, "new-token")) assertTrue(AutomaticServers.refresh()) - McpConnections.session(AutomaticServers.servers().single()) // replaces and closes the old one + McpConnections.withSession(AutomaticServers.servers().single()) { } // replaces and closes the old one val delete = old.requests.single { it.httpMethod == "DELETE" } assertNotEquals("Bearer new-token", delete.authorization) diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/RemovedEntryCleanupTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/RemovedEntryCleanupTest.kt index a532cda8d..7444bee6c 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/RemovedEntryCleanupTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/RemovedEntryCleanupTest.kt @@ -103,7 +103,7 @@ class RemovedEntryCleanupTest { assertTrue(AutomaticServers.refresh()) val restored = AutomaticServers.servers().single() McpToolCatalog.connect(restored) - val session = McpConnections.session(restored) + val session = McpConnections.withSession(restored) { it } releaseRemoval.countDown() removal.join(10_000) @@ -122,7 +122,7 @@ class RemovedEntryCleanupTest { assertSame( "the removal ended the new endpoint's session", session, - McpConnections.session(restored), + McpConnections.withSession(restored) { it }, ) } finally { releaseRemoval.countDown() diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/LifecycleSessionCloseTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/LifecycleSessionCloseTest.kt index 84332c363..c26511a48 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/LifecycleSessionCloseTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/LifecycleSessionCloseTest.kt @@ -108,7 +108,7 @@ class LifecycleSessionCloseTest { ) plugin.activate() // A session with a server-side id, so ending it sends the DELETE the server holds. - McpConnections.session(saved).initialize() + McpConnections.withSession(saved) { it.initialize() } val deactivating = thread(name = "deactivating") { plugin.deactivate() } assertTrue("the deactivation never sent its DELETE", deleteArrived.await(10, TimeUnit.SECONDS)) @@ -142,7 +142,7 @@ class LifecycleSessionCloseTest { McpServerStore.newServer("Docs", "http://127.0.0.1:${server.address.port}/mcp") ) plugin.activate() - McpConnections.session(saved).initialize() + McpConnections.withSession(saved) { it.initialize() } // A health row, so the teardown's clearing of the cache tells the health listeners. McpServerHealth.available(saved.id) val lock = plugin.lifecycleLock as java.lang.Object diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/DeleteServerSessionTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/DeleteServerSessionTest.kt index 910bc0477..107ed5fec 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/DeleteServerSessionTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/DeleteServerSessionTest.kt @@ -62,11 +62,11 @@ class DeleteServerSessionTest { val saved = McpServerStore.saveDetails( McpServerStore.newServer("Docs", "http://127.0.0.1:${server.port}/mcp") ) - McpConnections.session(saved).initialize() + McpConnections.withSession(saved) { it.initialize() } var lookedUp = false every { McpServerStore.remove(saved.id) } answers { // A call landing between the two steps: its lookup stores a session for the server. - McpConnections.session(saved) + McpConnections.withSession(saved) { } lookedUp = true callOriginal() } @@ -92,10 +92,10 @@ class DeleteServerSessionTest { val saved = McpServerStore.saveDetails( McpServerStore.newServer("Guarded", "http://127.0.0.1:${guarded.port}/mcp") ) - McpConnections.session(saved).initialize() + McpConnections.withSession(saved) { it.initialize() } every { McpServerStore.remove(saved.id) } answers { // A call landing between the two steps: its session has a server-side id too. - McpConnections.session(saved).initialize() + McpConnections.withSession(saved) { it.initialize() } callOriginal().also { removed = true } } @@ -129,7 +129,7 @@ class DeleteServerSessionTest { ) every { McpServerStore.remove(saved.id) } answers { // A call landing between the two steps, the server's first session. - McpConnections.session(saved).initialize() + McpConnections.withSession(saved) { it.initialize() } callOriginal().also { removed = true } } From d88b1d8940877950549313f40cf68113fcdb81d2 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 09:43:22 -0800 Subject: [PATCH 68/90] ADFA-7139 AI-Agent-MCP: valid strict JSON is accepted, a reply after a byte order mark included MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A test that the strict scan refuses no valid JSON: a byte order mark before '{', 1e5, -0.5, 1E-3, -0, é raw and escaped, escaped quote, backslash and slash, nested [] and {}, and a batch. JsonDepth accepts all of them at the head. parseReply did not: it trimmed the payload, which leaves a byte order mark in place, then took a reply starting with one for "not a JSON-RPC document". RFC 8259 (8.1) lets a parser ignore a byte order mark, and Android's org.json does. parseReply now drops a leading one. Tests: JsonDepthTest (valid strict JSON is accepted) and JsonRpcTest (a reply after a byte order mark, with 1e5, -0.5, é and nested arrays, is read). The JsonRpcTest case fails without the fix. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../plugins/aiagentmcp/transport/JsonRpc.kt | 7 ++++++- .../plugins/aiagentmcp/transport/JsonDepthTest.kt | 12 ++++++++++++ .../plugins/aiagentmcp/transport/JsonRpcTest.kt | 13 +++++++++++++ 3 files changed, 31 insertions(+), 1 deletion(-) diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonRpc.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonRpc.kt index a4175443f..d4dad5fbd 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonRpc.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonRpc.kt @@ -12,6 +12,8 @@ object JsonRpc { private const val VERSION = "2.0" + private const val BYTE_ORDER_MARK = "\uFEFF" + /** JSON-RPC's own code for a method the server does not implement. */ const val METHOD_NOT_FOUND = -32601 @@ -64,6 +66,7 @@ object JsonRpc { * * A batch — which the spec allows and some servers send even for a single request — is reduced * to its first non-notification member, since this client only ever has one call in flight. + * A leading byte order mark is ignored. * * A document nested deeper than [JsonDepth.MAX], or not strict JSON, is refused before any * parser sees it: parsing recurses once per level, and on Android a server's reply nested @@ -77,7 +80,9 @@ object JsonRpc { * strict JSON, its message naming which. */ fun parseReply(payload: String): Reply? { - val trimmed = payload.trim() + // A byte order mark is dropped: a parser may ignore one (RFC 8259, 8.1), Android's org.json + // does, and the checks below took a reply that starts with one for no JSON at all. + val trimmed = payload.trim().removePrefix(BYTE_ORDER_MARK).trim() JsonDepth.refusal(trimmed)?.let { throw UnparsedReplyException(it.reason) } val json = when { trimmed.startsWith("{") -> JSONObject(trimmed) diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepthTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepthTest.kt index 58a8c5938..a981b3266 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepthTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepthTest.kt @@ -33,6 +33,18 @@ class JsonDepthTest { assertNull(JsonDepth.refusal(text)) } + @Test + fun `valid strict JSON is accepted`() { + listOf( + // A byte order mark, which a JSON parser may ignore and Android's org.json skips. + "\uFEFF{\"a\":1}", + """{"n":1e5,"m":-0.5,"p":1E-3,"z":-0,"t":true,"f":false,"x":null}""", + """{"s":"é","u":"\u00e9","q":"\"\\\/"}""", + """{"a":[[],[[]],{"b":[]}],"o":{}}""", + """[{"jsonrpc":"2.0","id":1,"result":{}}]""", + ).forEach { text -> assertNull("refused: $text", JsonDepth.refusal(text)) } + } + @Test fun `a single-quoted string is refused`() { // Not JSON; Android's org.json reads it, and a quote inside it hides nothing from that parser. diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonRpcTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonRpcTest.kt index 8e26cbefa..99c24680d 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonRpcTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonRpcTest.kt @@ -141,6 +141,19 @@ class JsonRpcTest { assertEquals(JsonDepth.Refusal.NotStrict('/').reason, failure.message) } + @Test + fun givenValidStrictJsonAfterAByteOrderMark_whenParsed_thenItIsRead() { + val payload = "\uFEFF" + + """{"jsonrpc":"2.0","id":"7","result":{"n":1e5,"m":-0.5,"s":"é","a":[[],[[]],{"b":[]}]}}""" + + val result = JsonRpc.parseReply(payload)?.result + + assertEquals(1e5, result?.getDouble("n")) + assertEquals(-0.5, result?.getDouble("m")) + assertEquals("é", result?.getString("s")) + assertEquals(3, result?.getJSONArray("a")?.length()) + } + @Test fun givenAReplyNestedWithinTheLimit_whenParsed_thenItIsRead() { val depth = JsonDepth.MAX - 3 From f097c596ac6937801220fa283277a6857fb3d0c6 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 10:08:02 -0800 Subject: [PATCH 69/90] ADFA-7139 Forget the old credential when its replacement fails to save during a URL change If the Keystore refused the new token or headers while the URL changed, the old value stayed stored and the new URL got it. The save now forgets it in the same locked step, and puts the URL back when forgetting fails too. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- plugins/AI-Agent-MCP/README.md | 6 +- .../aiagentmcp/settings/McpServerStore.kt | 32 ++++- .../settings/McpSettingsViewModel.kt | 4 +- .../settings/FailedCredentialWriteTest.kt | 126 ++++++++++++++++++ 4 files changed, 160 insertions(+), 8 deletions(-) create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/FailedCredentialWriteTest.kt diff --git a/plugins/AI-Agent-MCP/README.md b/plugins/AI-Agent-MCP/README.md index 09bb3a873..8ad06402b 100644 --- a/plugins/AI-Agent-MCP/README.md +++ b/plugins/AI-Agent-MCP/README.md @@ -187,7 +187,11 @@ Two dependencies were deliberately not taken: ended after it, its DELETE carrying the credentials it was opened with, so a server that wants its token to end a session gets it; any of its requests still running after the save finish with neither. Clearing the credential - ends the session the same way. + ends the session the same way. If the Keystore refuses to store a new token + or headers while the URL changes, the old ones are forgotten with the + change, so the new URL never gets them; the pane reports the failure and the + credential has to be entered again. If forgetting them fails too, the URL + stays as it was. - Redirects are never followed automatically. A 3xx is repeated only when it resolves to the same origin, so the bearer token and the user's own headers cannot be replayed to another host in one hop. diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStore.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStore.kt index 8851e0470..d01b2d0aa 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStore.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStore.kt @@ -170,6 +170,12 @@ object McpServerStore { * credentials ([readTogether]) finds the old URL with the old ones or the new URL with the new, * never one with the other. The listeners are told once, after. * + * When the URL changes and a token or headers write fails, the old value is still stored, and + * the new URL must not get it: it is forgotten in the same step. If forgetting it fails too, + * the URL is put back instead, so the old credential stays with the URL it was entered for; + * the returned record then carries the old URL. Either way the failure is reported in the + * result, and the user enters the credential again. + * * Keystore work, so call this off the main thread. * * @param server the candidate, carrying the id plus the edited name and URL. @@ -184,12 +190,26 @@ object McpServerStore { headers: Map?, ): SavedConnection { val saved = synchronized(credentialsLock) { - val merged = saveDetailsLocked(server) - SavedConnection( - server = merged, - tokenStored = token?.let { writeToken(server.id, it) } ?: true, - headersStored = headers?.let { writeHeaders(server.id, it) } ?: true, - ) + val before = server(server.id) + var merged = saveDetailsLocked(server) + val tokenStored = token?.let { writeToken(server.id, it) } ?: true + val headersStored = headers?.let { writeHeaders(server.id, it) } ?: true + if (before != null && before.url != merged.url && !(tokenStored && headersStored)) { + // A write that failed left the old value stored, and the URL has moved: the new + // URL must not get what was entered for the old one. Forget it, still under the + // lock, so no request reads the pair between the writes. + var forgotten = true + if (!tokenStored) forgotten = writeToken(server.id, "") && forgotten + if (!headersStored) forgotten = writeHeaders(server.id, emptyMap()) && forgotten + if (!forgotten) { + // Forgetting failed too, so the old credential is still stored: put the URL + // back, which is the one it belongs to. The user's other edits are kept. + merged = synchronized(lock) { + merged.copy(url = before.url).also(::upsertLocked) + } + } + } + SavedConnection(merged, tokenStored, headersStored) } fireChanged() return saved diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt index 6b50d99b8..66c221263 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt @@ -184,7 +184,9 @@ class McpSettingsViewModel( * server that wants its token to end a session needs, and only to the old URL: the old token * never reaches the new URL, nor the new token the old. A call that looks the session up in * between stores one for the old URL, which the next lookup replaces; it ends with no - * credentials, since the server no longer points there. + * credentials, since the server no longer points there. A token or headers write that fails + * while the URL changes forgets the old value in that step (or keeps the old URL, when + * forgetting fails too), so the new URL is never sent the old credential. * * @return the merged record and a status sentence, null when everything worked. */ diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/FailedCredentialWriteTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/FailedCredentialWriteTest.kt new file mode 100644 index 000000000..bbfcdc8a4 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/FailedCredentialWriteTest.kt @@ -0,0 +1,126 @@ +package com.itsaky.androidide.plugins.aiagentmcp.settings + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpToolCatalog +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Before +import org.junit.Test + +/** + * A failed credential write while a server's URL changes never sends the old credential to the + * new URL. + * + * The save wrote the URL, then the token and the headers, and reported "token save failed" when + * the Keystore refused one. The refused write left the old value stored, so the new URL's first + * request carried the old token or the old headers. The old value is now forgotten in the same + * step as the URL change; when forgetting fails too, the URL is put back. + * + * The secret store here is a fake that refuses every write of a value, and refuses the forgetting + * as well when [forgetFails] is set. + */ +class FailedCredentialWriteTest { + + private val old = FakeMcpServer("old-token", listOf(tool("search", true)), sessionId = "old-session") + private val moved = FakeMcpServer("", listOf(tool("search", true))) + + @Volatile private var token = "old-token" + @Volatile private var headers = mapOf("X-Old" to "1") + @Volatile private var forgetFails = false + + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } answers { + token.takeIf { it.isNotEmpty() }?.let { KeystoreSecretStore.Stored.Value(it) } + ?: KeystoreSecretStore.Stored.Absent + } + every { McpServerStore.headers(any()) } answers { headers } + // The Keystore refuses to store a value; a blank, which removes, lands unless told not to. + every { McpServerStore.writeToken(any(), any()) } answers { + val value = secondArg() + if (value.isNotEmpty() || forgetFails) false else { token = ""; true } + } + every { McpServerStore.writeHeaders(any(), any()) } answers { + val value = secondArg>() + if (value.isNotEmpty() || forgetFails) false else { headers = emptyMap(); true } + } + } + + @After + fun tearDown() { + McpConnections.closeAll() + McpToolCatalog.clear() + old.stop() + moved.stop() + plugin.dispose() + unmockkObject(McpServerStore) + } + + @Test + fun `a refused token write during a URL change leaves the new URL with no token`() { + val saved = McpServerStore.saveDetails(McpServerStore.newServer("Docs", url(old))) + + val (record, failure) = McpSettingsViewModel { null } + .saveNow(saved.copy(url = url(moved)), "new-token", null) + + assertNotNull("the pane was not told the token was not saved", failure) + assertEquals(url(moved), record.url) + // The headers were not part of this save: the user kept them, as for any URL change. + assertNull("the new URL was sent the old token", firstRequestToTheNewUrl(saved.id).authorization) + } + + @Test + fun `a refused headers write during a URL change leaves the new URL with no headers`() { + val saved = McpServerStore.saveDetails(McpServerStore.newServer("Docs", url(old))) + + val (record, failure) = McpSettingsViewModel { null } + .saveNow(saved.copy(url = url(moved)), null, mapOf("X-New" to "1")) + + assertNotNull("the pane was not told the headers were not saved", failure) + assertEquals(url(moved), record.url) + assertFalse( + "the new URL was sent the old headers", + "x-old" in firstRequestToTheNewUrl(saved.id).headerNames, + ) + } + + @Test + fun `when forgetting the old credential fails too, the URL stays where the credential belongs`() { + val saved = McpServerStore.saveDetails(McpServerStore.newServer("Docs", url(old))) + forgetFails = true + + val (record, failure) = McpSettingsViewModel { null } + .saveNow(saved.copy(url = url(moved)), "new-token", mapOf("X-New" to "1")) + + assertNotNull("the pane was not told the save failed", failure) + assertEquals("the URL moved with the old credential still stored", url(old), record.url) + McpConnections.withSession(McpServerStore.server(saved.id)!!) { it.initialize() } + assertEquals("the new URL was contacted", emptyList(), moved.requests.toList()) + } + + private fun firstRequestToTheNewUrl(id: String): FakeMcpServer.Seen { + McpConnections.withSession(McpServerStore.server(id)!!) { it.initialize() } + return moved.requests.first() + } + + private fun url(server: FakeMcpServer) = "http://127.0.0.1:${server.port}/mcp" +} From 2b476922a30fe8c091bb160c95a4d18c670681ed Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 10:16:00 -0800 Subject: [PATCH 70/90] ADFA-7139 Keep every session when an Error interrupts detachAll An Error from one session's credential read escaped after the sessions had left the map, so the rest were never ended. Each session now goes into the caller's list as it leaves the map, the one whose read failed with empty credentials, and the Error is thrown after the others are safe. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../aiagentmcp/client/McpConnections.kt | 43 +++++++-- .../plugins/aiagentmcp/plugin/McpPlugin.kt | 2 +- .../aiagentmcp/client/DetachAllErrorTest.kt | 87 +++++++++++++++++++ 3 files changed, 126 insertions(+), 6 deletions(-) create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/DetachAllErrorTest.kt diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt index 11b8714b9..faca6aed8 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt @@ -190,9 +190,24 @@ object McpConnections { fun detachRemoved(serverId: String, endpoint: AutomaticEndpoint): Released? = release(serverId) { url -> automaticCredentials(endpoint, url) } - /** Ends every session, for the plugin shutting down. */ + /** + * Ends every session, for the plugin shutting down. Every one taken out is ended, even when + * reading one's credentials threw an Error; that Error is thrown once they have all been ended. + */ fun closeAll() { - endAll(detachAll()) + val released = ArrayList() + var failure: Error? = null + try { + detachAll(released) + } catch (e: Error) { + failure = e + } + try { + endAll(released) + } catch (e: Error) { + failure?.addSuppressed(e) ?: run { failure = e } + } + failure?.let { throw it } } /** @@ -217,11 +232,29 @@ object McpConnections { * the map under a lock of its own and ends the sessions once that lock is let go, since each * close sends a DELETE and can wait for a handshake in flight. * - * @return the sessions taken out, each with its credentials. + * Every session that leaves the map is added to [into] as it leaves, so a caller that ends + * [into] in a `finally` loses none. An Error from reading one session's credentials, which + * [runCatchingRecoverable] lets through, does not stop the others: that session goes into + * [into] with no credentials, so it is ended with none, the rest are taken out, and the first + * Error is thrown after the last, the others added to it as suppressed. + * + * @param into receives the sessions taken out, each with its credentials. + * @return [into]. */ - fun detachAll(): List { + fun detachAll(into: MutableList = ArrayList()): List { val taken = synchronized(this) { sessions.toMap().also { sessions.clear() } } - return taken.map { (id, entry) -> released(entry, id) { url -> credentialsFor(id, url) } } + var first: Error? = null + for ((id, entry) in taken) { + try { + into += released(entry, id) { url -> credentialsFor(id, url) } + } catch (e: Error) { + // Explicit empty credentials: a close with none given would read them again, and throw. + into += Released(entry.second, entry.first.url, McpCredentials("", emptyMap())) + first?.addSuppressed(e) ?: run { first = e } + } + } + first?.let { throw it } + return into } /** Takes [serverId]'s session out; see [detach]. */ diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt index ecad1539e..f6eed0d32 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt @@ -589,7 +589,7 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { toolSource = null // Before the entries are cleared below: each session's credentials are read as it is taken // out, and a SQLite debugger entry's token leaves with its entry. - released += McpConnections.detachAll() + McpConnections.detachAll(released) McpToolCatalog.clear() AutomaticServers.install(null) } diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/DetachAllErrorTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/DetachAllErrorTest.kt new file mode 100644 index 000000000..9d20198e0 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/DetachAllErrorTest.kt @@ -0,0 +1,87 @@ +package com.itsaky.androidide.plugins.aiagentmcp.client + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpToolCatalog +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame +import org.junit.Assert.assertThrows +import org.junit.Before +import org.junit.Test + +/** + * Taking every session out loses none of them when reading one session's credentials throws an + * Error. + * + * `detachAll` emptied the map, then read each session's credentials as it built the list it + * returned. An Error from one read, which a recoverable read lets through, escaped with the list + * unbuilt: the sessions were out of the map and nobody held them, so none got its DELETE. Each + * session now reaches the caller's list as it leaves the map, the one whose read failed with no + * credentials, and the Error is thrown after the others are safe. + */ +class DetachAllErrorTest { + + private val servers = List(3) { FakeMcpServer("", listOf(tool("search", true)), sessionId = "session-$it") } + private val failure = OutOfMemoryError("reading the second token") + @Volatile private var failing = false + + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + mockkObject(McpServerStore) + every { McpServerStore.headers(any()) } returns emptyMap() + } + + @After + fun tearDown() { + failing = false + McpConnections.closeAll() + McpToolCatalog.clear() + servers.forEach { it.stop() } + plugin.dispose() + unmockkObject(McpServerStore) + } + + @Test + fun `an Error reading one session's credentials does not lose the others, and reaches the caller`() { + val saved = servers.mapIndexed { i, server -> + McpServerStore.saveDetails(McpServerStore.newServer("S$i", "http://127.0.0.1:${server.port}/mcp")) + } + every { McpServerStore.token(any()) } answers { + val id = firstArg() + if (failing && id == saved[1].id) throw failure + KeystoreSecretStore.Stored.Value("token-of-$id") + } + saved.forEach { McpConnections.withSession(it) { session -> session.initialize() } } + // After the sessions exist, so only the take-out's read throws. + failing = true + + val thrown = assertThrows(OutOfMemoryError::class.java) { McpConnections.closeAll() } + + assertSame("not the Error from the read", failure, thrown) + servers.forEachIndexed { i, server -> + val delete = server.requests.singleOrNull { it.httpMethod == "DELETE" } + assertEquals("session $i was never ended", true, delete != null) + if (i == 1) { + assertNull("the session whose read failed was sent a token", delete!!.authorization) + } else { + assertEquals("Bearer token-of-${saved[i].id}", delete!!.authorization) + } + } + } +} From 0de62cc47c4dff0a1d92cbeaa67779a515491ae9 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 13:11:48 -0800 Subject: [PATCH 71/90] ADFA-7139 AI-Agent-MCP: End the detached session when a save or clear throws saveNow and clearCredentialNow took the session out of the map first and closed it after the store call. A throw from the store left it open on the server with nothing left to end it. Close it in a finally. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../settings/McpSettingsViewModel.kt | 23 ++++++++++---- .../settings/SaveServerSessionTest.kt | 30 +++++++++++++++++++ 2 files changed, 48 insertions(+), 5 deletions(-) diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt index 66c221263..2fdba1cc6 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt @@ -188,6 +188,9 @@ class McpSettingsViewModel( * while the URL changes forgets the old value in that step (or keeps the old URL, when * forgetting fails too), so the new URL is never sent the old credential. * + * The session is ended even when the save throws: it is out of the map by then, so nothing else + * would end it. The exception then propagates, and the health row is left as it was. + * * @return the merged record and a status sentence, null when everything worked. */ internal fun saveNow( @@ -196,8 +199,13 @@ class McpSettingsViewModel( headers: Map?, ): Pair { val released = McpConnections.detach(server.id) - val saved = McpServerStore.saveConnection(server, token?.trim(), headers) - released?.close() + val saved = try { + McpServerStore.saveConnection(server, token?.trim(), headers) + } finally { + // Also when the save throws: the session is out of the map, so nothing else would end + // it, and it would stay open on the server. + released?.close() + } McpServerHealth.credentialChanged(server.id) val failure = when { !saved.tokenStored -> string(R.string.mcp_token_save_failed) @@ -227,14 +235,19 @@ class McpSettingsViewModel( /** * [clearCredential]'s blocking part, off the main thread. The session was keyed by the * credential it no longer has, so it is ended, in [saveNow]'s order: taken out with the - * credentials it had, so its DELETE carries them, ended once they are cleared. + * credentials it had, so its DELETE carries them, ended once they are cleared, or once clearing + * throws. * * @return true when nothing is stored any more. */ internal fun clearCredentialNow(id: String): Boolean { val released = McpConnections.detach(id) - val cleared = McpServerStore.clearCredentials(id) - released?.close() + val cleared = try { + McpServerStore.clearCredentials(id) + } finally { + // Also when clearing throws, as in [saveNow]: the session is already out of the map. + released?.close() + } McpServerHealth.credentialChanged(id) return cleared } diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/SaveServerSessionTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/SaveServerSessionTest.kt index 4078ee2d0..35662fa68 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/SaveServerSessionTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/SaveServerSessionTest.kt @@ -135,5 +135,35 @@ class SaveServerSessionTest { assertTrue("the session's DELETE did not carry its headers", "x-old" in delete.headerNames) } + @Test + fun `a save that throws still ends the detached session with the old credentials`() { + val saved = McpServerStore.saveDetails(McpServerStore.newServer("Docs", url(old))) + McpConnections.withSession(saved) { it.initialize() } + every { McpServerStore.saveConnection(any(), any(), any()) } throws IllegalStateException("disk full") + + val thrown = runCatching { + McpSettingsViewModel { null }.saveNow(saved.copy(url = url(moved)), "new-token", mapOf("X-New" to "1")) + }.exceptionOrNull() + + assertTrue("the save's failure was swallowed", thrown is IllegalStateException) + val delete = old.requests.singleOrNull { it.httpMethod == "DELETE" } + assertTrue("the detached session was left open on the server", delete != null) + assertEquals("the DELETE did not carry the old token", "Bearer old-token", delete!!.authorization) + } + + @Test + fun `clearing that throws still ends the detached session with the old credentials`() { + val saved = McpServerStore.saveDetails(McpServerStore.newServer("Docs", url(old))) + McpConnections.withSession(saved) { it.initialize() } + every { McpServerStore.clearCredentials(any()) } throws IllegalStateException("disk full") + + val thrown = runCatching { McpSettingsViewModel { null }.clearCredentialNow(saved.id) }.exceptionOrNull() + + assertTrue("the clear's failure was swallowed", thrown is IllegalStateException) + val delete = old.requests.singleOrNull { it.httpMethod == "DELETE" } + assertTrue("the detached session was left open on the server", delete != null) + assertEquals("the DELETE did not carry the old token", "Bearer old-token", delete!!.authorization) + } + private fun url(server: FakeMcpServer) = "http://127.0.0.1:${server.port}/mcp" } From 659364b2c8b5f9b1cbfeff2405855ccbf4777da7 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 13:23:22 -0800 Subject: [PATCH 72/90] ADFA-7139 AI-Agent-MCP: Read the dialog's token and headers together loadForm read the token, the headers and whether each is stored one at a time, outside the lock a save writes them under, so a save landing in between showed a token from after it beside headers from before it. Read them in one readTogether, as loadFormNow so a test can reach it. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../settings/McpSettingsViewModel.kt | 63 +++++++++------- .../settings/LoadFormTogetherTest.kt | 75 +++++++++++++++++++ 2 files changed, 111 insertions(+), 27 deletions(-) create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/LoadFormTogetherTest.kt diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt index 2fdba1cc6..127ba361a 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt @@ -95,37 +95,46 @@ class McpSettingsViewModel( */ fun loadForm(id: String, onLoaded: (FormState) -> Unit) { viewModelScope.launch { - val state = withContext(Dispatchers.IO) { - val token = McpServerStore.token(id) - var headersUnreadable = false - var headersUnavailable = false - val headers = try { - McpServerStore.headers(id) - } catch (e: UnreadableSecretException) { - headersUnreadable = true - null - } catch (e: UnavailableSecretException) { - headersUnavailable = true - null - } - // Reported per credential, never folded together: a token that decrypts beside - // headers that do not must not put "could not be read" on the token's own field, - // which is the mis-attribution this pane exists to avoid. - FormState( - hasToken = McpServerStore.hasToken(id), - hasHeaders = McpServerStore.hasHeaders(id), - tokenUnreadable = token is KeystoreSecretStore.Stored.Unreadable, - tokenUnavailable = token is KeystoreSecretStore.Stored.Unavailable, - headersKnown = headers != null, - headersUnreadable = headersUnreadable, - headersUnavailable = headersUnavailable, - headers = headers.orEmpty(), - ) - } + val state = withContext(Dispatchers.IO) { loadFormNow(id) } onLoaded(state) } } + /** + * [loadForm]'s blocking part, off the main thread. + * + * The token, the headers and whether each is stored are read in one [McpServerStore.readTogether], + * the lock a save writes them under: read one at a time, a save landing between them showed a + * token from after the save beside headers from before it. + */ + internal fun loadFormNow(id: String): FormState = McpServerStore.readTogether { + val token = McpServerStore.token(id) + var headersUnreadable = false + var headersUnavailable = false + val headers = try { + McpServerStore.headers(id) + } catch (e: UnreadableSecretException) { + headersUnreadable = true + null + } catch (e: UnavailableSecretException) { + headersUnavailable = true + null + } + // Reported per credential, never folded together: a token that decrypts beside + // headers that do not must not put "could not be read" on the token's own field, + // which is the mis-attribution this pane exists to avoid. + FormState( + hasToken = McpServerStore.hasToken(id), + hasHeaders = McpServerStore.hasHeaders(id), + tokenUnreadable = token is KeystoreSecretStore.Stored.Unreadable, + tokenUnavailable = token is KeystoreSecretStore.Stored.Unavailable, + headersKnown = headers != null, + headersUnreadable = headersUnreadable, + headersUnavailable = headersUnavailable, + headers = headers.orEmpty(), + ) + } + /** * What an empty token field means when saving: leave whatever is stored alone. * @param typed the current contents of the token field. diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/LoadFormTogetherTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/LoadFormTogetherTest.kt new file mode 100644 index 000000000..2d80d8db1 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/LoadFormTogetherTest.kt @@ -0,0 +1,75 @@ +package com.itsaky.androidide.plugins.aiagentmcp.settings + +import com.itsaky.androidide.plugins.aiagentmcp.testing.awaitFinishedOrBlockedBy +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import io.mockk.every +import io.mockk.mockkObject +import io.mockk.unmockkObject +import kotlin.concurrent.thread +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Before +import org.junit.Test + +/** + * The settings dialog's load shows the token and the headers as stored together, never a token + * from after a save beside headers from before it. + * + * The load read the token, then the headers, outside the lock a save writes them under. A save + * landing between the two reads showed "no token" with the old headers. The load is made from + * inside the headers write of a clear, which has already forgotten the token, on another thread; + * the test waits until it has finished or is blocked on a lock the clearing thread holds. + */ +class LoadFormTogetherTest { + + @Volatile private var token = "old-token" + @Volatile private var headers = mapOf("X-Old" to "1") + + @Before + fun setUp() { + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } answers { + token.takeIf { it.isNotEmpty() }?.let { KeystoreSecretStore.Stored.Value(it) } + ?: KeystoreSecretStore.Stored.Absent + } + every { McpServerStore.headers(any()) } answers { headers } + every { McpServerStore.hasToken(any()) } answers { token.isNotEmpty() } + every { McpServerStore.hasHeaders(any()) } answers { headers.isNotEmpty() } + every { McpServerStore.writeToken(any(), any()) } answers { token = secondArg(); true } + } + + @After + fun tearDown() { + unmockkObject(McpServerStore) + } + + @Test + fun `a load between the token write and the headers write shows both before or both after`() { + val clearer = Thread.currentThread() + var load: Thread? = null + var state: McpSettingsViewModel.FormState? = null + every { McpServerStore.writeHeaders(any(), any()) } answers { + // The token is forgotten, the headers not yet. + load = thread(name = "load") { state = McpSettingsViewModel { null }.loadFormNow("s") } + awaitFinishedOrBlockedBy(load!!, clearer) + headers = secondArg() + true + } + + McpServerStore.clearCredentials("s") + load!!.join(10_000) + + val shown = assertNotNull_(state) + assertEquals( + "the load showed a token and headers from different saves", + shown.hasToken, + shown.headers.isNotEmpty(), + ) + } + + private fun assertNotNull_(value: McpSettingsViewModel.FormState?): McpSettingsViewModel.FormState { + assertNotNull("the load never finished", value) + return value!! + } +} From 87d65f9e042029d4c097e547b12202dc4922ca61 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 13:35:05 -0800 Subject: [PATCH 73/90] ADFA-7139 AI-Agent-MCP: Name a single quote in the not-strict-JSON reason A single quote outside a string read "found '''" in the reason a server's author is shown. Say "found a single quote"; every other character stays in single quotes. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../plugins/aiagentmcp/transport/JsonDepth.kt | 10 ++++++++-- .../plugins/aiagentmcp/transport/JsonDepthTest.kt | 14 ++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepth.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepth.kt index 44cce643a..4c97c79ec 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepth.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepth.kt @@ -29,14 +29,20 @@ internal object JsonDepth { override val reason: String get() = "nests arrays and objects more than $limit levels deep" } - /** [found] outside a string, where strict JSON never has it. */ + /** + * [found] outside a string, where strict JSON never has it. A single quote is named in + * words, since three in a row read as noise; every other character is shown in quotes. + */ data class NotStrict(val found: Char) : Refusal { override val reason: String get() = "is not strict JSON: a comment, single quote, ';', '=' or stray '\"' outside " + - "a string (found '$found')" + "a string (found ${describe(found)})" } } + /** [c] as a reason shows it: in single quotes, or in words for a single quote itself. */ + private fun describe(c: Char): String = if (c == '\'') "a single quote" else "'$c'" + /** * Why [text] may not be parsed: it opens more than [limit] arrays or objects one inside * another, or it is not strict JSON where that could hide brackets; null when it may. One diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepthTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepthTest.kt index a981b3266..5b17e6890 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepthTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepthTest.kt @@ -83,4 +83,18 @@ class JsonDepthTest { // Android's org.json skips the comment, so no string starts at its quote. assertEquals(Refusal.NotStrict('/'), JsonDepth.refusal("[/*\"*/${"[".repeat(200)}", 100)) } + + @Test + fun `a single quote is named in words and every other character is shown in quotes`() { + assertEquals( + "a single quote", + Refusal.NotStrict('\'').reason.substringAfter("string (found ").removeSuffix(")"), + ) + listOf('/', ';', '=', '#', '"').forEach { c -> + assertEquals( + "'$c'", + Refusal.NotStrict(c).reason.substringAfter("string (found ").removeSuffix(")"), + ) + } + } } From 50e36859542ae17bfd5e3170847f053ad61b88fa Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 13:57:51 -0800 Subject: [PATCH 74/90] ADFA-7139 AI-Agent-MCP: Test the token-to-headers window of a credential read The existing test forced a request only between the URL write and the token write. Add one from inside the headers write, after the token is written: the request must get the old pair or the new, never the new token with the old headers. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../settings/SaveServerSessionTest.kt | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/SaveServerSessionTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/SaveServerSessionTest.kt index 35662fa68..3957b3bd3 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/SaveServerSessionTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/SaveServerSessionTest.kt @@ -122,6 +122,37 @@ class SaveServerSessionTest { } } + @Test + fun `a request between the token write and the headers write gets the old pair or the new, never a mix`() { + val saved = McpServerStore.saveDetails(McpServerStore.newServer("Docs", url(old))) + val saver = Thread.currentThread() + var lookup: Thread? = null + var found: Thread.State? = null + every { McpServerStore.writeHeaders(saved.id, any()) } answers { + // The URL and the token are written, the headers not yet: a request for the server as + // it now stands. + val current = McpServerStore.server(saved.id)!! + lookup = thread(name = "lookup") { + runCatching { McpConnections.withSession(current) { it.initialize() } } + } + found = awaitFinishedOrBlockedBy(lookup!!, saver) + headers = secondArg() + true + } + + McpSettingsViewModel { null }.saveNow(saved.copy(url = url(moved)), "new-token", mapOf("X-New" to "1")) + lookup!!.join(10_000) + + assertTrue("the request never reached the new URL", moved.requests.isNotEmpty()) + moved.requests.forEach { request -> + assertEquals( + "a request read between the token write and the headers write (found $found) sent the new URL", + "Bearer new-token" to setOf("x-new"), + request.authorization to request.headerNames.filterTo(mutableSetOf()) { it.startsWith("x-") }, + ) + } + } + @Test fun `clearing the credentials ends the session with the ones it had`() { val saved = McpServerStore.saveDetails(McpServerStore.newServer("Docs", url(old))) From c99f782b4defcea29c95a0980bde8d2e44e8c10c Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 13:58:04 -0800 Subject: [PATCH 75/90] ADFA-7139 AI-Agent-MCP: Document that a blank token keeps the stored one on a URL change The README, the in-app help and the KDoc said a server's credentials go only to the URL they were saved with. Say that a blank token field means keep, so a URL change with it blank sends the stored token to the new URL on purpose, and that Clear stored credential is the way to none. Headers keep only when the stored ones could not be read; drawn rows replace them. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- plugins/AI-Agent-MCP/README.md | 6 ++++++ plugins/AI-Agent-MCP/src/main/assets/docs/index.html | 5 ++++- .../plugins/aiagentmcp/settings/McpServerStore.kt | 3 +++ .../plugins/aiagentmcp/settings/McpSettingsViewModel.kt | 4 ++++ 4 files changed, 17 insertions(+), 1 deletion(-) diff --git a/plugins/AI-Agent-MCP/README.md b/plugins/AI-Agent-MCP/README.md index 8ad06402b..65bd18842 100644 --- a/plugins/AI-Agent-MCP/README.md +++ b/plugins/AI-Agent-MCP/README.md @@ -192,6 +192,12 @@ Two dependencies were deliberately not taken: change, so the new URL never gets them; the pane reports the failure and the credential has to be entered again. If forgetting them fails too, the URL stays as it was. + Limit, on purpose: a blank token field means "keep the stored token", so + changing only the URL and leaving the token blank sends the stored token to + the new URL. Headers behave the same only when the stored ones could not be + read, which the pane cannot draw; rows it did draw replace the stored set, + so none left in the pane forgets them. To send the new URL no token, use + **Clear stored credential**. - Redirects are never followed automatically. A 3xx is repeated only when it resolves to the same origin, so the bearer token and the user's own headers cannot be replayed to another host in one hop. diff --git a/plugins/AI-Agent-MCP/src/main/assets/docs/index.html b/plugins/AI-Agent-MCP/src/main/assets/docs/index.html index 7f4380192..74cadb3f6 100644 --- a/plugins/AI-Agent-MCP/src/main/assets/docs/index.html +++ b/plugins/AI-Agent-MCP/src/main/assets/docs/index.html @@ -55,7 +55,10 @@

Adding a server

  • Enter the endpoint URL. It usually ends in /mcp.
  • Add an access token if the server needs one. It is encrypted with a key held in the Android Keystore, and sent only to that server, as an - Authorization: Bearer header.
  • + Authorization: Bearer header. Leaving the field empty keeps the + stored token, so if you change a server's URL and leave it empty, the stored + token is sent to the new URL. To send the new URL no token, use + Clear stored credential first.
  • The URL must be https:// unless the server runs on this device. Plain http:// is accepted only for localhost, 127.0.0.1 or [::1], such as a server started in the diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStore.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStore.kt index d01b2d0aa..051186673 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStore.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStore.kt @@ -176,6 +176,9 @@ object McpServerStore { * the returned record then carries the old URL. Either way the failure is reported in the * result, and the user enters the credential again. * + * A null [token] or [headers] keeps the stored value, also when the URL changes: the new URL + * is then sent that stored credential, on purpose. Pass blank or empty to forget it. + * * Keystore work, so call this off the main thread. * * @param server the candidate, carrying the id plus the edited name and URL. diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt index 127ba361a..7915b0936 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt @@ -197,6 +197,10 @@ class McpSettingsViewModel( * while the URL changes forgets the old value in that step (or keeps the old URL, when * forgetting fails too), so the new URL is never sent the old credential. * + * One limit, on purpose: a null [token] means "keep the stored one", so a URL change with the + * token field left blank sends the stored token to the new URL. [clearCredentialNow] is the way + * to a URL with no token. + * * The session is ended even when the save throws: it is out of the map by then, so nothing else * would end it. The exception then propagates, and the health row is left as it was. * From dacbc71456af6a7f07b249ca34b8fd86ff3bf97e Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 13:58:04 -0800 Subject: [PATCH 76/90] ADFA-7139 Bump AI-Agent-MCP to 2.0.0 MAJOR: this PR raises plugin.min_ide_version from 26.42 to 26.48, so users on 26.47 or older can no longer install it. versionCode 2 to 3. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- plugins/AI-Agent-MCP/build.gradle.kts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/plugins/AI-Agent-MCP/build.gradle.kts b/plugins/AI-Agent-MCP/build.gradle.kts index ba33d82d3..5dc962237 100644 --- a/plugins/AI-Agent-MCP/build.gradle.kts +++ b/plugins/AI-Agent-MCP/build.gradle.kts @@ -15,8 +15,8 @@ android { applicationId = "com.itsaky.androidide.plugins.aiagentmcp" minSdk = 33 targetSdk = 36 - versionCode = 2 - versionName = "1.1.0" + versionCode = 3 + versionName = "2.0.0" } buildFeatures { From 63fa40ca16ddd0fedc68031cd732a831d9ab1ce5 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 14:56:20 -0800 Subject: [PATCH 77/90] ADFA-7139 AI-Agent-MCP: Test a save landing between the form's token and headers reads The form-load test only made the load from inside a clear's headers write. Add the other direction: a save started from inside the load's token read must wait for the load, so the form shows the old token status with the old headers, never one save's token beside another's headers. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../settings/LoadFormTogetherTest.kt | 45 ++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/LoadFormTogetherTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/LoadFormTogetherTest.kt index 2d80d8db1..385a5d96f 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/LoadFormTogetherTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/LoadFormTogetherTest.kt @@ -1,8 +1,12 @@ package com.itsaky.androidide.plugins.aiagentmcp.settings +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences import com.itsaky.androidide.plugins.aiagentmcp.testing.awaitFinishedOrBlockedBy import com.itsaky.androidide.plugins.security.KeystoreSecretStore import io.mockk.every +import io.mockk.mockk import io.mockk.mockkObject import io.mockk.unmockkObject import kotlin.concurrent.thread @@ -19,15 +23,22 @@ import org.junit.Test * The load read the token, then the headers, outside the lock a save writes them under. A save * landing between the two reads showed "no token" with the old headers. The load is made from * inside the headers write of a clear, which has already forgotten the token, on another thread; - * the test waits until it has finished or is blocked on a lock the clearing thread holds. + * the test waits until it has finished or is blocked on a lock the clearing thread holds. The + * other direction is covered too: a save made from inside the load's token read, which must wait + * for the load to finish. */ class LoadFormTogetherTest { @Volatile private var token = "old-token" @Volatile private var headers = mapOf("X-Old" to "1") + private lateinit var plugin: McpPlugin + @Before fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } mockkObject(McpServerStore) every { McpServerStore.token(any()) } answers { token.takeIf { it.isNotEmpty() }?.let { KeystoreSecretStore.Stored.Value(it) } @@ -37,10 +48,12 @@ class LoadFormTogetherTest { every { McpServerStore.hasToken(any()) } answers { token.isNotEmpty() } every { McpServerStore.hasHeaders(any()) } answers { headers.isNotEmpty() } every { McpServerStore.writeToken(any(), any()) } answers { token = secondArg(); true } + every { McpServerStore.writeHeaders(any(), any()) } answers { headers = secondArg(); true } } @After fun tearDown() { + plugin.dispose() unmockkObject(McpServerStore) } @@ -68,6 +81,36 @@ class LoadFormTogetherTest { ) } + @Test + fun `a save between the token read and the headers read does not mix the two`() { + val saved = McpServerStore.saveDetails(McpServerStore.newServer("Docs", "https://example.invalid/mcp")) + val reader = Thread.currentThread() + var saver: Thread? = null + var found: Thread.State? = null + every { McpServerStore.token(saved.id) } answers { + val read = token.takeIf { it.isNotEmpty() }?.let { KeystoreSecretStore.Stored.Value(it) } + ?: KeystoreSecretStore.Stored.Absent + if (saver == null) { + // The token is read, the headers not yet: a save that forgets the token and + // replaces the headers. + saver = thread(name = "saver") { + McpServerStore.saveConnection(saved, "", mapOf("X-New" to "1")) + } + found = awaitFinishedOrBlockedBy(saver!!, reader) + } + read + } + + val shown = McpSettingsViewModel { null }.loadFormNow(saved.id) + saver!!.join(10_000) + + assertEquals( + "the form mixed one save's token with another's headers (saver found $found)", + true to mapOf("X-Old" to "1"), + shown.hasToken to shown.headers, + ) + } + private fun assertNotNull_(value: McpSettingsViewModel.FormState?): McpSettingsViewModel.FormState { assertNotNull("the load never finished", value) return value!! From cb0fd5de8bb2cb66afacd2c838a6be45126ea532 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 14:56:20 -0800 Subject: [PATCH 78/90] ADFA-7139 AI-Agent-MCP: Document that the form load holds the global credentials lock The settings dialog's load now reads the token and headers under the store's one credentials lock, across two Keystore decrypts. Say in the KDoc and the README that a save of any server and a request's credential read wait for it, the same accepted window the saves hold. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- plugins/AI-Agent-MCP/README.md | 4 ++++ .../plugins/aiagentmcp/settings/McpSettingsViewModel.kt | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/plugins/AI-Agent-MCP/README.md b/plugins/AI-Agent-MCP/README.md index 65bd18842..10dfe6daa 100644 --- a/plugins/AI-Agent-MCP/README.md +++ b/plugins/AI-Agent-MCP/README.md @@ -198,6 +198,10 @@ Two dependencies were deliberately not taken: read, which the pane cannot draw; rows it did draw replace the stored set, so none left in the pane forgets them. To send the new URL no token, use **Clear stored credential**. + Also accepted: the credentials lock is one lock for every server, held across + the Keystore writes of a save and the two Keystore decrypts of the settings + dialog's load, so a slow Keystore stalls the credential reads of other servers + for that long. - Redirects are never followed automatically. A 3xx is repeated only when it resolves to the same origin, so the bearer token and the user's own headers cannot be replayed to another host in one hop. diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt index 7915b0936..df01a9433 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt @@ -106,6 +106,10 @@ class McpSettingsViewModel( * The token, the headers and whether each is stored are read in one [McpServerStore.readTogether], * the lock a save writes them under: read one at a time, a save landing between them showed a * token from after the save beside headers from before it. + * + * Accepted limit: that is the store's one global credentials lock, held across the Keystore + * decrypts of this load. A save of any server waits for a load, and a request's credential read + * waits for it too. Both are two decrypts long, the same window the saves already hold. */ internal fun loadFormNow(id: String): FormState = McpServerStore.readTogether { val token = McpServerStore.token(id) From 9d31f5e7eb1d364e036299421ee5c3a2460fa94a Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 16:32:50 -0800 Subject: [PATCH 79/90] ADFA-7139 AI-Agent-MCP: Keep a tool toggled during a failed credential write when the URL is restored The rollback wrote the record captured before the Keystore writes, so it undid a setToolEnabled made meanwhile. It now re-reads the current record under the lock and restores only the URL. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../aiagentmcp/settings/McpServerStore.kt | 6 ++++- .../settings/FailedCredentialWriteTest.kt | 22 +++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStore.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStore.kt index 051186673..8a450a162 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStore.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStore.kt @@ -207,8 +207,12 @@ object McpServerStore { if (!forgotten) { // Forgetting failed too, so the old credential is still stored: put the URL // back, which is the one it belongs to. The user's other edits are kept. + // Re-read the record: a toggle made during the Keystore writes lives only + // there, and restoring the older snapshot would undo it. merged = synchronized(lock) { - merged.copy(url = before.url).also(::upsertLocked) + val current = servers().firstOrNull { it.id == server.id } + if (current == null) merged + else current.copy(url = before.url).also(::upsertLocked) } } } diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/FailedCredentialWriteTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/FailedCredentialWriteTest.kt index bbfcdc8a4..c897e9660 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/FailedCredentialWriteTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/FailedCredentialWriteTest.kt @@ -40,6 +40,7 @@ class FailedCredentialWriteTest { @Volatile private var token = "old-token" @Volatile private var headers = mapOf("X-Old" to "1") @Volatile private var forgetFails = false + @Volatile private var duringTokenWrite: (() -> Unit)? = null private lateinit var plugin: McpPlugin @@ -57,6 +58,7 @@ class FailedCredentialWriteTest { // The Keystore refuses to store a value; a blank, which removes, lands unless told not to. every { McpServerStore.writeToken(any(), any()) } answers { val value = secondArg() + if (value.isNotEmpty()) duringTokenWrite?.invoke() if (value.isNotEmpty() || forgetFails) false else { token = ""; true } } every { McpServerStore.writeHeaders(any(), any()) } answers { @@ -117,6 +119,26 @@ class FailedCredentialWriteTest { assertEquals("the new URL was contacted", emptyList(), moved.requests.toList()) } + @Test + fun `restoring the URL keeps a tool switched off while the Keystore was writing`() { + val saved = McpServerStore.saveDetails(McpServerStore.newServer("Docs", url(old))) + McpServerStore.setToolEnabled(saved.id, "search", true) + duringTokenWrite = { McpServerStore.setToolEnabled(saved.id, "search", false) } + forgetFails = true + + val (record, failure) = McpSettingsViewModel { null } + .saveNow(McpServerStore.server(saved.id)!!.copy(url = url(moved)), "new-token", null) + + assertNotNull("the pane was not told the save failed", failure) + assertEquals("the URL was not put back", url(old), record.url) + assertEquals(url(old), McpServerStore.server(saved.id)!!.url) + assertFalse( + "the rollback undid the toggle made meanwhile", + "search" in McpServerStore.server(saved.id)!!.enabledTools, + ) + assertFalse("search" in record.enabledTools) + } + private fun firstRequestToTheNewUrl(id: String): FakeMcpServer.Seen { McpConnections.withSession(McpServerStore.server(id)!!) { it.initialize() } return moved.requests.first() From d17ba511fbcf5313976513986ffc7f5a2c6e810d Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 16:35:37 -0800 Subject: [PATCH 80/90] ADFA-7139 AI-Agent-MCP: Scrub the status line in the connection log The status line was recorded as the server sent it, so a reason phrase repeating the assigned session id or the request's token showed in the log. It now passes through the request's redactor like the headers and bodies. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../aiagentmcp/transport/McpExchangeTrace.kt | 8 +++- .../client/AssignedSessionRedactionTest.kt | 37 +++++++++++++++++++ 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpExchangeTrace.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpExchangeTrace.kt index 352ece7fa..2dc218e7f 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpExchangeTrace.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpExchangeTrace.kt @@ -38,8 +38,12 @@ internal class McpExchangeTrace( conn.getHeaderField(McpHttpClient.HEADER_SESSION_ID)?.takeIf { it.isNotBlank() } ?.let { redactor = redactor.with(it) } val fields = conn.headerFields.orEmpty().entries - status = fields.firstOrNull { it.key == null }?.value?.firstOrNull() - ?: "HTTP $code ${conn.responseMessage.orEmpty()}".trim() + // Scrubbed like the headers and the body: a status line's reason phrase is the server's + // free text, and may repeat the session id it assigned or a credential it was sent. + status = redactor.scrub( + fields.firstOrNull { it.key == null }?.value?.firstOrNull() + ?: "HTTP $code ${conn.responseMessage.orEmpty()}".trim() + ) responseHeaders = fields // `X-Android-*` is the platform's own bookkeeping, not something the server sent. .filter { (name, _) -> name != null && !name.startsWith("X-Android-", ignoreCase = true) } diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/AssignedSessionRedactionTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/AssignedSessionRedactionTest.kt index 329d6e4bc..1905a479c 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/AssignedSessionRedactionTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/AssignedSessionRedactionTest.kt @@ -1,8 +1,12 @@ package com.itsaky.androidide.plugins.aiagentmcp.client import com.itsaky.androidide.plugins.aiagentmcp.transport.McpExchangeLog +import com.itsaky.androidide.plugins.aiagentmcp.transport.McpExchangeTrace import com.itsaky.androidide.plugins.aiagentmcp.transport.McpRedactor import com.sun.net.httpserver.HttpServer +import io.mockk.every +import io.mockk.mockk +import java.net.HttpURLConnection import java.net.InetSocketAddress import org.json.JSONObject import org.junit.After @@ -62,7 +66,40 @@ class AssignedSessionRedactionTest { assertTrue("the echo was not masked: $reply", reply.contains("Your session is ${McpRedactor.MASK}.")) } + @Test + fun `a session id the server assigns is masked in the status line that repeats it`() { + val trace = trace(McpRedactor(emptyList(), emptyList())) + + trace.answered(connection("HTTP/1.1 200 Session $SESSION_ID ready", sessionId = SESSION_ID)) + + val status = requireNotNull(trace.toExchange(null).status) + assertFalse("the status line shows the assigned session id: $status", status.contains(SESSION_ID)) + assertTrue("the status line was not masked: $status", status.contains(McpRedactor.MASK)) + } + + @Test + fun `the request's bearer token is masked in a status line that repeats it`() { + val trace = trace(McpRedactor(listOf(BEARER), emptyList())) + + trace.answered(connection("HTTP/1.1 401 Bad token $BEARER", sessionId = null)) + + val status = requireNotNull(trace.toExchange(null).status) + assertFalse("the status line shows the bearer token: $status", status.contains(BEARER)) + } + + private fun trace(redactor: McpRedactor) = + McpExchangeTrace("POST", "http://127.0.0.1/mcp", emptyList(), "{}", 2, redactor) + + private fun connection(statusLine: String, sessionId: String?): HttpURLConnection = + mockk().also { + every { it.responseCode } returns 200 + every { it.responseMessage } returns "" + every { it.getHeaderField("Mcp-Session-Id") } returns sessionId + every { it.headerFields } returns mapOf(null to listOf(statusLine)) + } + private companion object { const val SESSION_ID = "sess-7d41c9e2a8b3f650" + const val BEARER = "bearer-9f3a71c2d8e45b60" } } From 5673bf40c77f679a5c7f5677f5ae2bb3c811a3c4 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 16:37:58 -0800 Subject: [PATCH 81/90] ADFA-7139 AI-Agent-MCP: Complete every accepted call when the tool source closes close() only shut the executor down, so a queued call's future never completed and a running call stayed blocked in its socket read. It now cancels each call's handle and each in-flight future before clearing the maps. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../plugins/aiagentmcp/tools/McpToolSource.kt | 8 +- .../tools/CloseWithCallsInFlightTest.kt | 149 ++++++++++++++++++ 2 files changed, 156 insertions(+), 1 deletion(-) create mode 100644 plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/CloseWithCallsInFlightTest.kt diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt index a350d0601..065fdcbcf 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt @@ -173,9 +173,15 @@ class McpToolSource internal constructor( inFlight.remove(callId)?.cancel(true) } - /** Ends the executor, for the plugin shutting down. */ + /** + * Ends the executor and every call it accepted, for the plugin shutting down: no new work is + * taken, each running call's connection is dropped so its blocked read ends, and each future, + * a queued call's included, completes (cancelled) so nobody waits on one that will never run. + */ fun close() { executor.shutdownNow() + for (call in calls.values) call.handle.cancel() + for (future in inFlight.values) future.cancel(true) inFlight.clear() calls.clear() } diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/CloseWithCallsInFlightTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/CloseWithCallsInFlightTest.kt new file mode 100644 index 000000000..2e6ad2178 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/CloseWithCallsInFlightTest.kt @@ -0,0 +1,149 @@ +package com.itsaky.androidide.plugins.aiagentmcp.tools + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServer +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import com.itsaky.androidide.plugins.services.ToolSourceRegistry +import com.sun.net.httpserver.HttpExchange +import com.sun.net.httpserver.HttpServer +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import java.net.InetSocketAddress +import java.util.concurrent.CompletableFuture +import java.util.concurrent.CountDownLatch +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import org.json.JSONArray +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * Closing the tool source ends every call it accepted, running or queued. + * + * `close()` shut the executor down and cleared its maps. A call queued behind a running one was + * never started, so its future never completed and the host waited on it; the running call's + * worker stayed blocked in a socket read until the server answered or the read timed out. + * + * One worker runs the held call, so the second call is queued behind it. The server answers the + * held call only when [release] is counted down, which happens after the assertions: both futures + * must be done by then. Nothing sleeps. + */ +class CloseWithCallsInFlightTest { + + private val pool = Executors.newSingleThreadExecutor() + private val source = McpToolSource(pool) + + /** Counted down when the held `tools/call` reaches the server. */ + private val arrived = CountDownLatch(1) + private val release = CountDownLatch(1) + + private val handlers = Executors.newCachedThreadPool() + private lateinit var http: HttpServer + private lateinit var plugin: McpPlugin + private lateinit var docs: McpServer + private lateinit var name: String + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } returns KeystoreSecretStore.Stored.Absent + every { McpServerStore.headers(any()) } returns emptyMap() + http = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply { + executor = handlers + createContext("/mcp") { exchange -> answer(exchange) } + start() + } + docs = McpServerStore.saveDetails( + McpServerStore.newServer("Docs", "http://127.0.0.1:${http.address.port}/mcp") + ) + McpToolCatalog.connect(docs) + McpServerStore.setToolEnabled(docs.id, "search", true) + name = source.listTools().single().name + } + + @After + fun tearDown() { + release.countDown() + source.close() + pool.shutdownNow() + McpConnections.closeAll() + McpToolCatalog.clear() + http.stop(0) + handlers.shutdownNow() + plugin.dispose() + unmockkObject(McpServerStore) + } + + private fun answer(exchange: HttpExchange) { + if (exchange.requestMethod == "DELETE") { + exchange.sendResponseHeaders(200, -1) + exchange.close() + return + } + val request = JSONObject(exchange.requestBody.use { String(it.readBytes()) }) + val id = request.opt("id") + if (id == null) { + exchange.sendResponseHeaders(202, -1) + exchange.close() + return + } + val result = when (request.getString("method")) { + "initialize" -> JSONObject().put("protocolVersion", "2025-03-26") + "tools/list" -> JSONObject().put("tools", JSONArray(listOf(tool("search", true)))) + "tools/call" -> { + arrived.countDown() + release.await(10, TimeUnit.SECONDS) + JSONObject().put( + "content", + JSONArray().put(JSONObject().put("type", "text").put("text", "ok")), + ) + } + else -> JSONObject() + } + val bytes = JSONObject().put("jsonrpc", "2.0").put("id", id).put("result", result) + .toString().toByteArray() + exchange.responseHeaders.add("Content-Type", "application/json") + // The client is dropped by close(); the write failing then is expected. + runCatching { + exchange.sendResponseHeaders(200, bytes.size.toLong()) + exchange.responseBody.use { it.write(bytes) } + } + exchange.close() + } + + private fun invoke(id: String): CompletableFuture = + source.invoke( + mockk { + every { toolName } returns name + every { arguments } returns mapOf("who" to id) + every { callId } returns id + } + ) + + @Test + fun `close completes a running call and a queued one before the server answers`() { + val running = invoke("running") + assertTrue("the call never reached the server", arrived.await(10, TimeUnit.SECONDS)) + val queued = invoke("queued") + + source.close() + + assertTrue("the running call's future is still pending after close", running.isDone) + assertTrue("the queued call's future is still pending after close", queued.isDone) + assertEquals("a call was left registered", 0, source.pendingCalls()) + } +} From fe01a3497fb0439bf08338ab1ba3ebb71f4f6a77 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 16:40:03 -0800 Subject: [PATCH 82/90] ADFA-7139 AI-Agent-MCP: Clear a refusal under the health lock when the credential changes credentialChanged ran without the lock a refused write takes, so the write could land after it and leave the server refused until the next edit. It now takes the lock; no listener runs under it. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../aiagentmcp/tools/McpServerHealth.kt | 6 ++++- .../aiagentmcp/tools/McpServerHealthTest.kt | 22 +++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpServerHealth.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpServerHealth.kt index 0691db9ef..3ee4639b5 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpServerHealth.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpServerHealth.kt @@ -92,7 +92,11 @@ object McpServerHealth { /** Lets the probe ask a server that refused its credential again, once the user changed it. */ fun credentialChanged(serverId: String) { - byServer.computeIfPresent(serverId) { _, health -> health.copy(refused = false) } + // Under the lock a refused write takes, so it cannot land after this and leave the server + // refused until the next edit. No listener runs here. + synchronized(lock) { + byServer.computeIfPresent(serverId) { _, health -> health.copy(refused = false) } + } } /** Forgets a server that was removed. */ diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpServerHealthTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpServerHealthTest.kt index cf9c2967a..24c495de9 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpServerHealthTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpServerHealthTest.kt @@ -1,10 +1,14 @@ package com.itsaky.androidide.plugins.aiagentmcp.tools +import com.itsaky.androidide.plugins.aiagentmcp.testing.awaitFinishedOrBlockedBy import org.junit.After import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test +import kotlin.concurrent.thread /** * Tests [McpServerHealth], which the agent's per-server tags read: a change is announced once, @@ -95,4 +99,22 @@ class McpServerHealthTest { assertEquals(McpServerHealth.State.DEGRADED, McpServerHealth.of(SERVER)?.state) assertEquals(1, changes) } + + @Test + fun givenARefusalBeingRecorded_whenTheCredentialChangesMeanwhile_thenTheRefusalIsCleared() { + McpServerHealth.degraded(SERVER, "refused", refused = true) + var changing: Thread? = null + + // The credential changes while the refused write holds the lock, between its check and + // its write; the change must wait for the write and then clear it. + McpServerHealth.degraded(SERVER, "refused", refused = true) { + changing = thread(name = "changing") { McpServerHealth.credentialChanged(SERVER) } + awaitFinishedOrBlockedBy(changing!!, Thread.currentThread()) + true + } + changing!!.join(10_000) + + assertFalse("the refusal outlived the credential change", McpServerHealth.of(SERVER)!!.refused) + assertTrue(McpServerHealth.of(SERVER)?.state == McpServerHealth.State.DEGRADED) + } } From 78bca24459c396214ad1e5fe09e8fc76a4a83813 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 16:42:46 -0800 Subject: [PATCH 83/90] ADFA-7139 AI-Agent-MCP: Ignore a tool list from a URL the server has left setKnownTools applied a listing without checking the server's URL, so a list from the old endpoint dropped the enabled tools of the new one. It now takes the URL the listing used and does nothing when the record's URL differs. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../aiagentmcp/settings/McpServerStore.kt | 6 +++- .../aiagentmcp/tools/McpToolCatalog.kt | 2 +- .../settings/McpServerStoreLockTest.kt | 28 +++++++++++++++++-- 3 files changed, 31 insertions(+), 5 deletions(-) diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStore.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStore.kt index 8a450a162..e648bebb7 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStore.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStore.kt @@ -409,12 +409,16 @@ object McpServerStore { /** * Records the tools a server advertised, dropping toggles for tools it no longer has. + * Does nothing when the server's URL is no longer the one the listing used: that list belongs + * to the old endpoint, and applying it would drop the toggles of tools the new one may have. * @param id the server. + * @param listedUrl the URL the tools were listed from. * @param toolNames the tools it just listed. */ - fun setKnownTools(id: String, toolNames: List) { + fun setKnownTools(id: String, listedUrl: String, toolNames: List) { synchronized(lock) { val server = servers().firstOrNull { it.id == id } ?: return + if (server.url != listedUrl) return val updated = server.copy( knownTools = toolNames, enabledTools = server.enabledTools.filterTo(mutableSetOf()) { it in toolNames }, diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt index a13550e6e..4c04fe342 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt @@ -162,7 +162,7 @@ object McpToolCatalog { Log.i(TAG, "Dropping a tool list from '${server.name}', removed or moved while it listed") return Listing(serverName, tools) } - McpServerStore.setKnownTools(server.id, tools.map { it.name }) + McpServerStore.setKnownTools(server.id, server.url, tools.map { it.name }) } Log.i(TAG, "Server '${server.name}' listed ${tools.size} tool(s)") return Listing(serverName, tools) diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStoreLockTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStoreLockTest.kt index 8e7532f2e..067d8e06a 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStoreLockTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStoreLockTest.kt @@ -32,6 +32,8 @@ class McpServerStoreLockTest { const val READ_DELAY_MS = 2L const val JOIN_TIMEOUT_SECONDS = 30L + + const val URL = "https://example.test/mcp" } private val prefs = FakeSharedPreferences() @@ -48,7 +50,7 @@ class McpServerStoreLockTest { plugin = McpPlugin() plugin.initialize(context) serverId = McpServerStore.saveDetails( - McpServerStore.newServer("Docs", "https://example.test/mcp") + McpServerStore.newServer("Docs", URL) ).id } @@ -60,7 +62,7 @@ class McpServerStoreLockTest { @Test fun givenConcurrentToolToggles_whenTheyInterleave_thenNoWriteIsLost() { val tools = (1..WRITERS).map { "tool_$it" } - McpServerStore.setKnownTools(serverId, tools) + McpServerStore.setKnownTools(serverId, URL, tools) prefs.readDelayMillis = READ_DELAY_MS runTogether(tools) { McpServerStore.setToolEnabled(serverId, it, true) } @@ -71,7 +73,7 @@ class McpServerStoreLockTest { @Test fun givenAToggleAndAWholeServerSwitchAtOnce_whenTheyInterleave_thenNeitherIsLost() { val tools = (1..WRITERS).map { "tool_$it" } - McpServerStore.setKnownTools(serverId, tools) + McpServerStore.setKnownTools(serverId, URL, tools) prefs.readDelayMillis = READ_DELAY_MS runTogether(tools + "disable") { work -> @@ -87,6 +89,26 @@ class McpServerStoreLockTest { assertFalse("the whole-server switch must survive the toggles", stored?.enabled ?: true) } + @Test + fun givenAListingFromTheOldUrl_whenTheUrlChangedMeanwhile_thenItChangesNothing() { + McpServerStore.setKnownTools(serverId, URL, listOf("x")) + McpServerStore.setToolEnabled(serverId, "x", true) + val moved = "https://moved.example.test/mcp" + McpServerStore.saveDetails(McpServerStore.server(serverId)!!.copy(url = moved)) + + McpServerStore.setKnownTools(serverId, URL, listOf("y")) + + val stale = McpServerStore.server(serverId)!! + assertEquals("the old endpoint's list was applied", listOf("x"), stale.knownTools) + assertEquals("the enabled tool was dropped", setOf("x"), stale.enabledTools) + + McpServerStore.setKnownTools(serverId, moved, listOf("y")) + + val applied = McpServerStore.server(serverId)!! + assertEquals(listOf("y"), applied.knownTools) + assertEquals(emptySet(), applied.enabledTools) + } + /** * Runs [work] on one thread per item, all released at once. * From efb74b701f2ff05b4ca53bcd6a484b54ac08e01c Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 16:45:06 -0800 Subject: [PATCH 84/90] ADFA-7139 AI-Agent-MCP: Test: release the held deactivation when a lifecycle assertion fails The test's finally only removed the listener, so a failed assertion left the deactivating thread waiting for resume and hung the run. It now sets resume under the lock, notifies, and joins both threads with a timeout. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../plugin/LifecycleSessionCloseTest.kt | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/LifecycleSessionCloseTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/LifecycleSessionCloseTest.kt index c26511a48..8e43f8001 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/LifecycleSessionCloseTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/LifecycleSessionCloseTest.kt @@ -157,10 +157,13 @@ class LifecycleSessionCloseTest { } } McpServerHealth.addChangeListener(hold) + // Outside the try, so the finally can reach them when an assertion fails part way. + var deactivating: Thread? = null + var activating: Thread? = null try { - val deactivating = thread(name = "deactivating") { plugin.deactivate() } + deactivating = thread(name = "deactivating") { plugin.deactivate() } assertTrue("the deactivation's teardown never took its sessions out", held.await(10, TimeUnit.SECONDS)) - val activating = thread(name = "activating") { plugin.activate() } + activating = thread(name = "activating") { plugin.activate() } // Whichever comes first: the activate ending, or a DELETE sent while the deactivation is held. val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10) while (activating.isAlive && deleteArrived.count > 0 && System.nanoTime() < deadline) activating.join(10) @@ -181,6 +184,16 @@ class LifecycleSessionCloseTest { assertFalse("deactivate never finished", deactivating.isAlive) } finally { McpServerHealth.removeChangeListener(hold) + // Whatever failed above, the deactivating thread may still be waiting on the lock for + // `resume`, and it is not a daemon: left there, the failed assertion would hang the run + // instead of reporting it. + synchronized(lock) { + resume = true + lock.notifyAll() + } + releaseDelete.countDown() + deactivating?.join(10_000) + activating?.join(10_000) } } } From 5966e12c0edb6a15d089864003bfd2349311c206 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 16:47:10 -0800 Subject: [PATCH 85/90] ADFA-7139 AI-Agent-MCP: Test: end the HTTP handler threads of the lifecycle close test The server's cached pool was never shut down, so idle threads lived on for up to 60 s. It is now a field, shut down in tearDown, which also asserts it terminated. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../plugins/aiagentmcp/plugin/LifecycleSessionCloseTest.kt | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/LifecycleSessionCloseTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/LifecycleSessionCloseTest.kt index 8e43f8001..cd20ae9ae 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/LifecycleSessionCloseTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/LifecycleSessionCloseTest.kt @@ -46,9 +46,12 @@ class LifecycleSessionCloseTest { private val deleteArrived = CountDownLatch(1) private val releaseDelete = CountDownLatch(1) + /** Kept so [tearDown] can end it; an idle pool thread otherwise lives on for up to 60 s. */ + private val handlers = Executors.newCachedThreadPool() + private val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply { // Its own threads, so the held DELETE does not hold the next activation's listing. - executor = Executors.newCachedThreadPool() + executor = handlers createContext("/mcp") { exchange -> if (exchange.requestMethod == "DELETE") { deleteArrived.countDown() @@ -98,7 +101,9 @@ class LifecycleSessionCloseTest { McpConnections.closeAll() McpToolCatalog.clear() server.stop(0) + handlers.shutdownNow() unmockkObject(McpServerStore) + assertTrue("the HTTP handler threads outlived the test", handlers.awaitTermination(10, TimeUnit.SECONDS)) } @Test From 4e7a8c26c86f8b822747e32369f9b147ae23e1c0 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 16:48:19 -0800 Subject: [PATCH 86/90] ADFA-7139 AI-Agent-MCP: Test: prove the concurrent lifecycle test registered and unregistered The test could pass without any registration. It now counts registrations, captures worker exceptions, and asserts exactly one registration that the deactivation unregistered by identity. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../plugin/ConcurrentLifecycleTest.kt | 35 ++++++++++++++++--- 1 file changed, 31 insertions(+), 4 deletions(-) diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/ConcurrentLifecycleTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/ConcurrentLifecycleTest.kt index c3b0c8bca..19ef53130 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/ConcurrentLifecycleTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/ConcurrentLifecycleTest.kt @@ -40,6 +40,14 @@ class ConcurrentLifecycleTest { /** What the registry holds now. */ private val registered = CopyOnWriteArrayList() + /** Every source ever registered and every one unregistered, in order, so a test can tell + * that the registration happened and that the deactivation undid that very source. */ + private val registrations = CopyOnWriteArrayList() + private val unregistrations = CopyOnWriteArrayList() + + /** What the worker threads threw, which a thread would otherwise only print. */ + private val failures = CopyOnWriteArrayList() + private val registering = CountDownLatch(1) private val releaseRegistration = CountDownLatch(1) @@ -52,10 +60,12 @@ class ConcurrentLifecycleTest { override fun registerToolSource(source: ToolSourceRegistry.ToolSource) { registering.countDown() assertTrue("the test never released the registration", releaseRegistration.await(10, TimeUnit.SECONDS)) + registrations += source registered += source } override fun unregisterToolSource(source: ToolSourceRegistry.ToolSource) { + unregistrations += source registered.removeAll { it === source } } } @@ -84,9 +94,9 @@ class ConcurrentLifecycleTest { fun `a deactivate that arrives while activate registers the tool source leaves none registered`() { SharedServices.register(ToolSourceRegistry::class.java, registry) - val activating = thread(name = "activating") { plugin.activate() } + val activating = worker("activating") { plugin.activate() } assertTrue("activate never registered the tool source", registering.await(10, TimeUnit.SECONDS)) - val deactivating = thread(name = "deactivating") { plugin.deactivate() } + val deactivating = worker("deactivating") { plugin.deactivate() } awaitFinishedOrBlockedBy(deactivating, activating) releaseRegistration.countDown() activating.join(10_000) @@ -95,6 +105,10 @@ class ConcurrentLifecycleTest { assertFalse("activate never finished", activating.isAlive) assertFalse("deactivate never finished", deactivating.isAlive) assertEquals("a tool source is still registered after the deactivate", 0, registered.size) + assertEquals("a worker failed: $failures", emptyList(), failures.toList()) + assertEquals("the tool source was not registered exactly once", 1, registrations.size) + assertEquals("the deactivation did not unregister the registered source", 1, unregistrations.size) + assertTrue("the unregistered source is not the registered one", unregistrations.single() === registrations.single()) } @Test @@ -104,11 +118,11 @@ class ConcurrentLifecycleTest { assertEquals(0, registered.size) SharedServices.register(ToolSourceRegistry::class.java, registry) - val registeringThread = thread(name = "ai-core-activated") { + val registeringThread = worker("ai-core-activated") { lifecycleListener.captured.onPluginActivated(AI_CORE_PLUGIN_ID) } assertTrue("the listener never registered the tool source", registering.await(10, TimeUnit.SECONDS)) - val deactivating = thread(name = "deactivating") { plugin.deactivate() } + val deactivating = worker("deactivating") { plugin.deactivate() } awaitFinishedOrBlockedBy(deactivating, registeringThread) releaseRegistration.countDown() registeringThread.join(10_000) @@ -117,6 +131,19 @@ class ConcurrentLifecycleTest { assertFalse("the registration never finished", registeringThread.isAlive) assertFalse("deactivate never finished", deactivating.isAlive) assertEquals("a tool source is still registered after the deactivate", 0, registered.size) + assertEquals("a worker failed: $failures", emptyList(), failures.toList()) + assertEquals("the tool source was not registered exactly once", 1, registrations.size) + assertEquals("the deactivation did not unregister the registered source", 1, unregistrations.size) + assertTrue("the unregistered source is not the registered one", unregistrations.single() === registrations.single()) + } + + /** A thread running [block] that records what it throws in [failures]. */ + private fun worker(name: String, block: () -> Unit): Thread = thread(name = name) { + try { + block() + } catch (e: Throwable) { + failures += e + } } private companion object { From 13d77040bbe20d10f75651e77219c0e2d9df12f0 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 16:49:49 -0800 Subject: [PATCH 87/90] ADFA-7139 AI-Agent-MCP: Test: assert the values of the X-* headers a save sends The fake server recorded only header names, so a wrong value passed. It now records the X-* values and the save tests assert them, the concurrent-save cases included. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- .../aiagentmcp/settings/SaveServerSessionTest.kt | 14 +++++++------- .../plugins/aiagentmcp/testing/FakeMcpServer.kt | 12 +++++++++++- 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/SaveServerSessionTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/SaveServerSessionTest.kt index 3957b3bd3..19fa319cf 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/SaveServerSessionTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/SaveServerSessionTest.kt @@ -82,13 +82,13 @@ class SaveServerSessionTest { val delete = old.requests.single { it.httpMethod == "DELETE" } assertEquals("the old session's DELETE did not carry the old token", "Bearer old-token", delete.authorization) - assertTrue("the old session's DELETE did not carry the old headers", "x-old" in delete.headerNames) + assertEquals("the old session's DELETE did not carry the old header's value", "1", delete.customHeaders["x-old"]) assertFalse("the old URL was sent the new headers", "x-new" in delete.headerNames) McpConnections.withSession(McpServerStore.server(saved.id)!!) { it.initialize() } val first = moved.requests.first() assertEquals("the new URL's first request did not carry the new token", "Bearer new-token", first.authorization) - assertTrue("the new URL's first request did not carry the new headers", "x-new" in first.headerNames) + assertEquals("the new URL's first request did not carry the new header's value", "1", first.customHeaders["x-new"]) assertFalse("the new URL was sent the old headers", "x-old" in first.headerNames) } @@ -116,8 +116,8 @@ class SaveServerSessionTest { moved.requests.forEach { request -> assertEquals( "a request read between the URL write and the token write (found $found) sent the new URL", - "Bearer new-token" to setOf("x-new"), - request.authorization to request.headerNames.filterTo(mutableSetOf()) { it.startsWith("x-") }, + "Bearer new-token" to mapOf("x-new" to "1"), + request.authorization to request.customHeaders, ) } } @@ -147,8 +147,8 @@ class SaveServerSessionTest { moved.requests.forEach { request -> assertEquals( "a request read between the token write and the headers write (found $found) sent the new URL", - "Bearer new-token" to setOf("x-new"), - request.authorization to request.headerNames.filterTo(mutableSetOf()) { it.startsWith("x-") }, + "Bearer new-token" to mapOf("x-new" to "1"), + request.authorization to request.customHeaders, ) } } @@ -163,7 +163,7 @@ class SaveServerSessionTest { assertTrue(cleared) val delete = old.requests.single { it.httpMethod == "DELETE" } assertEquals("the session's DELETE did not carry its token", "Bearer old-token", delete.authorization) - assertTrue("the session's DELETE did not carry its headers", "x-old" in delete.headerNames) + assertEquals("the session's DELETE did not carry its header's value", "1", delete.customHeaders["x-old"]) } @Test diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/testing/FakeMcpServer.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/testing/FakeMcpServer.kt index 44092d8bd..1ff532fcb 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/testing/FakeMcpServer.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/testing/FakeMcpServer.kt @@ -25,8 +25,15 @@ class FakeMcpServer( /** * One request as the server saw it. * @property headerNames the names of every header it carried, in lower case. + * @property customHeaders the first value of each `X-*` header it carried, by lower-case name, + * so a test can tell the value a header was sent with, not only that it was sent. */ - data class Seen(val httpMethod: String, val authorization: String?, val headerNames: Set = emptySet()) + data class Seen( + val httpMethod: String, + val authorization: String?, + val headerNames: Set = emptySet(), + val customHeaders: Map = emptyMap(), + ) val requests = java.util.concurrent.CopyOnWriteArrayList() @@ -36,6 +43,9 @@ class FakeMcpServer( exchange.requestMethod, exchange.requestHeaders.getFirst("Authorization"), exchange.requestHeaders.keys.mapTo(mutableSetOf()) { it.lowercase() }, + exchange.requestHeaders.entries + .filter { (name, _) -> name.startsWith("x-", ignoreCase = true) } + .associate { (name, values) -> name.lowercase() to values.first() }, ) if (exchange.requestMethod == "DELETE") { exchange.sendResponseHeaders(200, -1) From 2ffd629a036f2477233eea090c1a2ff511eda681 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 16:50:11 -0800 Subject: [PATCH 88/90] ADFA-7139 AI-Agent-MCP: Docs: name three rare session races as known limits Names the credential-only Save or Clear session leak, the debugger entry health that follows the entry rather than the port, and the double-404 extra handshake (ADFA-7250) in the README, the plugin page and the in-app help. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- plugins/AI-Agent-MCP/README.md | 13 +++++++++++++ plugins/AI-Agent-MCP/ai-agent-mcp.html | 8 ++++++++ .../AI-Agent-MCP/src/main/assets/docs/index.html | 13 +++++++++++++ 3 files changed, 34 insertions(+) diff --git a/plugins/AI-Agent-MCP/README.md b/plugins/AI-Agent-MCP/README.md index 10dfe6daa..19de0c896 100644 --- a/plugins/AI-Agent-MCP/README.md +++ b/plugins/AI-Agent-MCP/README.md @@ -147,6 +147,19 @@ Two dependencies were deliberately not taken: - `errors/` — HTTP and JSON-RPC failures reduced to one translated sentence - `security/SecureTokenStore.kt` — this plugin's Keystore alias, over the IDE's `KeystoreSecretStore` +## Known limits + +Three rare session races, accepted for now: + +- A Save or Clear that changes only the credentials can leave one session on a + third-party server that needs the old token to end it; the session expires on + the server. +- A SQLite debugger entry's health follows the entry, not the port, so after the + app moves to a new port a result from the old one can show for up to one + 20-second probe cycle. +- Two requests that both get a 404 for the same expired session can start an + extra handshake and leave one session to expire; tracked in ADFA-7250. + ## Security notes - Tool names and descriptions from a server are **untrusted remote text**. Names diff --git a/plugins/AI-Agent-MCP/ai-agent-mcp.html b/plugins/AI-Agent-MCP/ai-agent-mcp.html index 066c9e781..fd2995767 100644 --- a/plugins/AI-Agent-MCP/ai-agent-mcp.html +++ b/plugins/AI-Agent-MCP/ai-agent-mcp.html @@ -178,6 +178,14 @@

    Limitations

    not used.
  • The tool list is answered from memory, so a server that was unreachable at startup needs a Connect before its tools appear.
  • +
  • A Save or Clear that changes only the credentials can leave + one session open on a third-party server that needs the old token to end + it. The session expires on the server.
  • +
  • A SQLite debugger entry's health follows the entry, not the port. After the + app moves to a new port, a result from the old one can show for up to one + 20-second probe cycle.
  • +
  • Two requests that both get a 404 for the same expired session can start an + extra handshake and leave one session to expire. Tracked in ADFA-7250.
  • Troubleshooting

    diff --git a/plugins/AI-Agent-MCP/src/main/assets/docs/index.html b/plugins/AI-Agent-MCP/src/main/assets/docs/index.html index 74cadb3f6..d835d20ca 100644 --- a/plugins/AI-Agent-MCP/src/main/assets/docs/index.html +++ b/plugins/AI-Agent-MCP/src/main/assets/docs/index.html @@ -116,6 +116,19 @@

    Which servers work

    transport cannot be used, and the deprecated HTTP+SSE transport is not supported.

    +

    Known limits

    +

    Three rare session races are accepted for now:

    +
      +
    • A Save or Clear that changes only the credentials can leave + one session open on a third-party server that needs the old token to end + it. The session expires on the server.
    • +
    • A SQLite debugger entry's health follows the entry, not the port. After the + app moves to a new port, a result from the old one can show for up to one + 20-second probe cycle.
    • +
    • Two requests that both get a 404 for the same expired session can start an + extra handshake and leave one session to expire. Tracked in ADFA-7250.
    • +
    +

    Troubleshooting

    When Connect fails, tap Show details under the message to see every request it sent and everything the server answered: status line, From ac0d914d431b571569c3162be98149b5c247eacf Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sat, 21 Nov 2026 21:21:43 -0800 Subject: [PATCH 89/90] ADFA-7139 AI-Agent-MCP: Docs: name the credential a put-back URL keeps A save that moves a server to a new URL puts the URL back when a token or headers write fails and forgetting the old value fails too. A credential the Keystore did store for the new URL in that save stays stored, so requests to the old URL carry it. This needs two refused Keystore writes and one accepted write in one save; accepted as rare (CodeRabbit thread 4655483257). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- plugins/AI-Agent-MCP/README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/plugins/AI-Agent-MCP/README.md b/plugins/AI-Agent-MCP/README.md index 19de0c896..dc6bc5d5f 100644 --- a/plugins/AI-Agent-MCP/README.md +++ b/plugins/AI-Agent-MCP/README.md @@ -205,6 +205,11 @@ Three rare session races, accepted for now: change, so the new URL never gets them; the pane reports the failure and the credential has to be entered again. If forgetting them fails too, the URL stays as it was. + Accepted as rare: when the URL is put back, a token or headers that the + Keystore did store for the new URL in that save stay stored, and requests to + the old URL carry them. That case needs two refused Keystore writes and one + accepted write in the same save; the pane reports the failure, and **Clear + stored credential** removes them. Limit, on purpose: a blank token field means "keep the stored token", so changing only the URL and leaving the token blank sends the stored token to the new URL. Headers behave the same only when the stored ones could not be From 744da895a92e4da5672a1acd380fc88d014307f5 Mon Sep 17 00:00:00 2001 From: David Schachter Date: Sun, 22 Nov 2026 13:09:25 -0800 Subject: [PATCH 90/90] ADFA-7139 AI-Agent-MCP: say read-only SQLite debugger tools can be allowed for the chat AI-Core 3.6.0 (addons#167, c8579952) lets a contributed tool that its provider declares read-only get "Always Allow" for the rest of the chat. The text here still said every remote tool asks on every call and never gets "always allow". Changed (text and comments only, no behaviour change): - README.md: approval paragraph and the SQLite debugger entry's approval bullet - ai-agent-mcp.html: feature list, getting-started step, design principles - src/main/assets/docs/index.html: Approval section - McpPlugin.kt: plugin tooltip detail - ReadOnlyTrust.kt, McpToolSource.kt: KDoc The new text says: the grant covers one tool of one app for the rest of one chat, ignores the arguments, rests on the plugin's own read-only claim, needs AI-Core 3.6.0 or later, and every other remote tool still asks on every call. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01Vh2DAYT7GPoC2cDzo8LErn --- plugins/AI-Agent-MCP/README.md | 25 ++++++++++++++----- plugins/AI-Agent-MCP/ai-agent-mcp.html | 14 +++++++---- .../src/main/assets/docs/index.html | 14 ++++++++--- .../aiagentmcp/debugger/ReadOnlyTrust.kt | 9 ++++--- .../plugins/aiagentmcp/plugin/McpPlugin.kt | 4 ++- .../plugins/aiagentmcp/tools/McpToolSource.kt | 7 +++--- 6 files changed, 50 insertions(+), 23 deletions(-) diff --git a/plugins/AI-Agent-MCP/README.md b/plugins/AI-Agent-MCP/README.md index dc6bc5d5f..29218cbf9 100644 --- a/plugins/AI-Agent-MCP/README.md +++ b/plugins/AI-Agent-MCP/README.md @@ -45,9 +45,11 @@ Configuration → MCP servers**: field never shows what is stored and an empty field keeps it, so this is the only way back to a server that needs no credential. -Every remote tool asks for approval on every call, and there is no "always -allow" for contributed tools — they run outside the Agent's own path -containment, so the dialog is the only gate. +Every remote tool asks for approval on every call, with one exception: a tool +of the automatic SQLite debugger entry that declares itself read-only may be +given "Always Allow" for the rest of the chat (details under "The SQLite +debugger entry"). Remote tools run outside the Agent's own path containment, so +the dialog is the only gate. ### The SQLite debugger entry @@ -105,9 +107,20 @@ Servers you add yourself keep the name prefix taken from their label. at most 12 contributed tools per message (4 for a small on-device model), in order, and drops the rest; every app has its own entry. Switching the others on will come with showing this entry in the settings screen (phase 2). -- The Agent still asks for approval on every call: AI-Core makes every - contributed tool ask (it ignores the tool's own `requiresApproval`). Approving - read-only calls automatically is tracked in ADFA-7147. +- Approval. This plugin declares each of that entry's tools read-only when the + server sends `readOnlyHint: true` for it (`McpToolSource.Spec.isReadOnly`). + AI-Core 3.6.0 or later then offers "Always Allow" in the approval dialog for + those tools (ADFA-7147). One tap covers that tool for the rest of the chat, + and the Agent asks again in a new chat. Each tool is its own grant, and so is + each app: AI-Core keys a grant by this plugin, the tool's name and a digest of + its description and schema, and the description names the app. The grant + ignores the arguments, so after one tap the Agent can call that tool with any + arguments. It rests on the plugin's own read-only claim, which Code on the Go + cannot check. AI-Core still asks on every call for the tools that are not + read-only, for every tool of a server you add yourself, and, on an AI-Core + older than 3.6.0, for every tool: this plugin does not check AI-Core's + version. AI-Core ignores the tool's own `requiresApproval` and always asks at + least once. ## Transport diff --git a/plugins/AI-Agent-MCP/ai-agent-mcp.html b/plugins/AI-Agent-MCP/ai-agent-mcp.html index fd2995767..c857fc016 100644 --- a/plugins/AI-Agent-MCP/ai-agent-mcp.html +++ b/plugins/AI-Agent-MCP/ai-agent-mcp.html @@ -71,8 +71,10 @@

    Core functionality

  • Per-tool switches, off by default — you choose which of a server's tools the Agent may see. One popular GitHub server advertises around ninety tools, enough to fill a phone-sized context window on its own.
  • -
  • Approval on every call — a remote tool always asks, showing the - arguments it would send, and can never be granted "always allow".
  • +
  • Approval on every call — a remote tool asks each time, showing the + arguments it would send. The one exception is a read-only tool of the + SQLite debugger: you may choose "Always Allow" for it, for the rest of + that chat (needs AI Core 3.6.0 or later).
  • Encrypted tokens — bearer tokens are encrypted with an Android Keystore key and sent only to the server they belong to: never over cleartext http:// except to a server on the device itself, and @@ -142,7 +144,8 @@

    Usage

  • Tap Connect. The server is saved, contacted, and the tools it offers are listed right there.
  • Switch on the tools you want, and save. Ask the Agent for something those - tools cover; it will request your approval before each call.
  • + tools cover; it will request your approval before each call (a read-only SQLite + debugger tool can be allowed for the rest of the chat).
    New tools always arrive switched off, including on the connection @@ -163,8 +166,9 @@

    Key benefits

  • Context stays affordable — per-tool switches, off by default, keep a ninety-tool server from crowding out the conversation on a phone.
  • Nothing runs unattended — every remote call is approved - individually, with its arguments visible, and no "always allow" exists for - contributed tools.
  • + individually, with its arguments visible. The only exception is a + read-only SQLite debugger tool that you choose to allow for the rest of one + chat.
  • Extensible without code — supporting a new service means adding its URL in settings; neither this plugin nor AI Core changes.
  • diff --git a/plugins/AI-Agent-MCP/src/main/assets/docs/index.html b/plugins/AI-Agent-MCP/src/main/assets/docs/index.html index d835d20ca..be9b9b44b 100644 --- a/plugins/AI-Agent-MCP/src/main/assets/docs/index.html +++ b/plugins/AI-Agent-MCP/src/main/assets/docs/index.html @@ -91,10 +91,16 @@

    Choosing tools

    Approval

    Every remote tool asks for your approval before it runs, showing the - arguments it would send, and there is no "always allow" for them. That includes - the four SQLite debugger tools that start switched on. The Agent's - own file tools are confined to the open project; a remote tool is confined by - nothing this device controls, so the dialog is the only gate — read it.

    + arguments it would send. The exception is a read-only tool of the SQLite + debugger, such as the four that start switched on: its dialog offers + "Always Allow", which covers that tool for the rest of the chat. The grant is + for that tool and that app only, it ends when you start or open another chat, + and it ignores the arguments, so the Agent can then call the tool with any + arguments. It rests on the plugin's own claim that the tool only reads, which + Code on the Go cannot check. This needs AI Core 3.6.0 or later; an older AI + Core asks on every call. The Agent's own file tools are confined to the open + project; a remote tool is confined by nothing this device controls, so the + dialog is the only gate — read it.

    What is sent

      diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReadOnlyTrust.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReadOnlyTrust.kt index 36efda224..6741e97ac 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReadOnlyTrust.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReadOnlyTrust.kt @@ -6,9 +6,10 @@ import com.itsaky.androidide.plugins.aiagentmcp.client.McpTool * Which tools of an automatic SQLite debugger entry start switched on, and which this plugin declares * read-only. * - * Declaring a tool read-only does not skip the approval dialog today: AI-Core overrides - * `requiresApproval` to true for every contributed tool (`ContributedToolHandler`), so the Agent still - * asks on each call until automatic approval exists (ADFA-7147). + * Declaring a tool read-only does not skip the approval dialog: AI-Core overrides `requiresApproval` + * to true for every contributed tool (`ContributedToolHandler`). It does let AI-Core 3.6.0 or later + * offer "Always Allow" for that tool, for the rest of the chat (ADFA-7147). Each app's tool is its own + * grant, and the grant ignores the arguments. On an older AI-Core the Agent asks on each call. * * Only that entry may use this: the hint is the server's own claim, and the SQLite debugger endpoint * is the one server whose code the IDE itself installed. A server the user adds by hand is never asked. @@ -44,7 +45,7 @@ object ReadOnlyTrust { * Reads the hint from one `tools/list` entry's `annotations`. * * Exactly boolean true counts. The string "true", 1, false, null and a missing key do not: an - * approval skipped on a loose reading (once AI-Core honours the declaration) cannot be taken back. + * "Always Allow" offered on a loose reading cannot be taken back for the rest of the chat. * * @param hint the value under `readOnlyHint`, or null when absent. */ diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt index f6eed0d32..2434288e8 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt @@ -649,7 +649,9 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { for an app you build with the SQLite debugger: four of its read-only tools start on (list databases, get schema, query, and get events). This version doesn't list that entry on the MCP servers screen.

      The Agent asks for - your approval every time it uses a tool, including those four. + your approval every time it uses a tool. For those four, you can choose + Always Allow, which lasts for the rest of the chat (needs AI Core 3.6.0 or + later). """.trimIndent(), buttons = listOf( PluginTooltipButton( diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt index 065fdcbcf..610c2ee52 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt @@ -352,9 +352,10 @@ class McpToolSource internal constructor( * know what a server's tool does, and guessing on the permissive side is the one guess that * cannot be undone. The one exception is [preApproved]: a readOnlyHint tool of the automatic * debugger entry, whose server Code on the Go itself installed, declares no approval needed. - * That is a declaration only: AI-Core currently overrides `requiresApproval` to true for every - * contributed tool (`ContributedToolHandler`), so the Agent still asks on each call. Honouring - * the declaration is tracked in ADFA-7147. The contract is a Java interface, so its accessors are implemented as + * AI-Core overrides `requiresApproval` to true for every contributed tool + * (`ContributedToolHandler`), so the Agent still asks. For a read-only tool, AI-Core 3.6.0 or + * later offers "Always Allow" for the rest of the chat (ADFA-7147); an older AI-Core asks on each + * call. The contract is a Java interface, so its accessors are implemented as * functions: Kotlin synthesises properties for *reading* a Java getter, never for overriding one. */ private class Spec(