diff --git a/libs/plugin-api.jar b/libs/plugin-api.jar index b3f00fb02..0165f1762 100644 Binary files a/libs/plugin-api.jar and b/libs/plugin-api.jar differ diff --git a/plugins/AI-Agent-MCP/README.md b/plugins/AI-Agent-MCP/README.md index 50a6d7788..3e1f4544c 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.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. + +- 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,14 @@ 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.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/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/AI-Agent-MCP/src/main/AndroidManifest.xml b/plugins/AI-Agent-MCP/src/main/AndroidManifest.xml index 4c179768d..e1ed9f715 100644 --- a/plugins/AI-Agent-MCP/src/main/AndroidManifest.xml +++ b/plugins/AI-Agent-MCP/src/main/AndroidManifest.xml @@ -39,23 +39,29 @@ android:name="plugin.author" android:value="App Dev for All" /> - + + android:value="26.47" /> - + + 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..c899401be --- /dev/null +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt @@ -0,0 +1,225 @@ +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. + * + * @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) { + // 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. */ + 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) + } + + /** 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(keepGoing: () -> Boolean = { true }): 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) { + if (!keepGoing()) return false + 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..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 @@ -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,9 @@ 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. + startDebuggerEntry { isActive } val refreshed = McpToolCatalog.refreshAll { isActive } if (refreshed > 0 && isActive) settingsChanged() probeHealth { isActive } @@ -197,11 +218,15 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { override fun deactivate(): Boolean = try { context.removePluginLifecycleListener(aiCoreLifecycle) McpServerStore.removeChangeListener(settingsChanged) + AutomaticServers.removeChangeListener(settingsChanged) 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) { @@ -212,9 +237,11 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { override fun dispose() { runCatching { context.removePluginLifecycleListener(aiCoreLifecycle) } McpServerStore.removeChangeListener(settingsChanged) + AutomaticServers.removeChangeListener(settingsChanged) McpServerHealth.removeChangeListener(healthChanged) unregisterToolSource() stopScope() + AutomaticServers.removeEndpointListener(relistAutomatic) releaseConnections() pluginContext = null context.logger.info("McpPlugin: disposed") @@ -237,7 +264,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 +286,44 @@ 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. + * + * 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) { + null + } + if (service == null) { + context.logger.info("McpPlugin: this IDE has no debugger endpoint service") + return + } + 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) @@ -353,6 +419,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/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/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/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) + } +} 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..c2c6383da --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/testing/FakeMcpServer.kt @@ -0,0 +1,81 @@ +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. + * + * 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, + 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") { + 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") + 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) } + } + 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)) } + } +} diff --git a/plugins/README.md b/plugins/README.md index 2eb07e5c4..835e1f8cd 100644 --- a/plugins/README.md +++ b/plugins/README.md @@ -148,7 +148,10 @@ 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 (`PluginSecurityManager.validatePlugin`, before +the loader's warn-and-drop of unknown keys is reached), so a plugin declaring `debugger.endpoints` +needs `plugin.min_ide_version` of at least 26.47, the first release that knows it. ---