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..8a1461e13 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. @@ -36,7 +37,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 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 @@ -47,6 +49,42 @@ 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.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. + +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 +`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 +"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. +- 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. + ## Transport MCP's **Streamable HTTP** transport over `HttpURLConnection`: @@ -105,10 +143,15 @@ 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.47 and older reject a + manifest that names a permission they do not know (`PluginSecurityManager.validatePlugin`), so this + 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/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/ai-agent-mcp.html b/plugins/AI-Agent-MCP/ai-agent-mcp.html index 5277617f4..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.

@@ -141,7 +143,9 @@

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 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/AndroidManifest.xml b/plugins/AI-Agent-MCP/src/main/AndroidManifest.xml index 4c179768d..bb853f280 100644 --- a/plugins/AI-Agent-MCP/src/main/AndroidManifest.xml +++ b/plugins/AI-Agent-MCP/src/main/AndroidManifest.xml @@ -39,23 +39,31 @@ android:name="plugin.author" android:value="App Dev for All" /> - + + android:value="26.48" /> - + + android:value="network.access,debugger.endpoints" /> 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.

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/client/McpConnections.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt index 3f9b28fdd..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 @@ -1,6 +1,8 @@ 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 @@ -58,25 +60,25 @@ 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 } } 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() } @@ -87,13 +89,22 @@ 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 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 // legacy token saved with a stray newline is one `setRequestProperty` refuses to send. @@ -123,7 +134,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/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 77fe5ca22..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 @@ -1,6 +1,8 @@ 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 @@ -192,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) } @@ -314,6 +321,9 @@ class McpSession( name = name, description = entry.optString("description"), inputSchema = entry.optJSONObject("inputSchema")?.let(::toMap).orEmpty(), + readOnlyHint = ReadOnlyTrust.isReadOnlyHint( + entry.optJSONObject("annotations")?.opt("readOnlyHint") + ), ) } diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpTool.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpTool.kt index 9b6b5a628..aba868cc2 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpTool.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpTool.kt @@ -6,11 +6,14 @@ package com.itsaky.androidide.plugins.aiagentmcp.client * @property name the tool's own name, unique within its server. * @property description what it does, as the server describes it — untrusted remote text. * @property inputSchema JSON Schema for the arguments, empty when the server sends none. + * @property readOnlyHint whether `annotations.readOnlyHint` was exactly boolean true. A claim by + * the server: only the automatic debugger entry acts on it. */ data class McpTool( val name: String, val description: String, val inputSchema: Map = 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..643762385 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt @@ -0,0 +1,272 @@ +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 +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" + +/** 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 + + /** + * 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>() + + /** + * 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") }, + ) + + /** + * Where endpoints come from; null (deactivation) clears every entry. + */ + 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. + * + * @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 + 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. + * + * 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) + } + + 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. + * 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. 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. + * + * 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. + * + * @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, ticket) = synchronized(this) { + val current = source ?: return false + current to ++readsStarted + } + val fresh = try { + read().associateBy { idFor(it.applicationId) } + } catch (e: CancellationException) { + throw e + } 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 + } 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 + } + val moved = mutableListOf() + val removed: List + val changed = synchronized(this) { + if (source !== read || !keepGoing() || ticket < storedRead) return false + storedRead = ticket + 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) runCatchingRecoverable { 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 + + /** 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) runCatchingRecoverable { 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..36efda224 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReadOnlyTrust.kt @@ -0,0 +1,52 @@ +package com.itsaky.androidide.plugins.aiagentmcp.debugger + +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). + * + * 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 [CORE_TOOLS] that declared `annotations.readOnlyHint` as boolean true. + */ + fun enabledTools(tools: List): Set = + tools.filter { it.readOnlyHint && it.name in CORE_TOOLS }.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/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 e3f00c588..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 @@ -1,10 +1,15 @@ 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 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 import com.itsaky.androidide.plugins.aiagentmcp.tools.McpServerHealth @@ -15,8 +20,10 @@ 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.CoroutineExceptionHandler import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job @@ -29,12 +36,15 @@ 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. * * 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 { @@ -115,6 +125,21 @@ 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. + * + * 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) + } + @Volatile private var pluginContext: PluginContext? = null @@ -141,9 +166,22 @@ 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 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 = { - resolveToolSourceRegistry()?.notifyToolsChanged(PLUGIN_ID) + try { + resolveToolSourceRegistry()?.notifyToolsChanged(PLUGIN_ID) + } 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") + } } /** @@ -153,12 +191,28 @@ 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}") } } + /** + * 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) { + runCatchingRecoverable { McpToolCatalog.connect(server) } + if (isActive) settingsChanged() + } + } + } + override fun initialize(context: PluginContext): Boolean { this.context = context pluginContext = context @@ -174,6 +228,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,9 +239,12 @@ 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 } + probeHealth({ isActive }) } true } catch (e: Exception) { @@ -195,13 +253,20 @@ 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) 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) { @@ -210,11 +275,13 @@ 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) unregisterToolSource() stopScope() + AutomaticServers.removeEndpointListener(relistAutomatic) releaseConnections() pluginContext = null context.logger.info("McpPlugin: disposed") @@ -230,14 +297,20 @@ 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++ - val due = McpServerStore.servers().filter { server -> + // 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 || health?.state != McpServerHealth.State.AVAILABLE) @@ -248,7 +321,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 } @@ -258,8 +331,53 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { } } - /** A fresh scope for this activation; the previous one is cancelled, never reused. */ - private fun newScope() = CoroutineScope(SupervisorJob() + Dispatchers.IO) + /** + * 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) + } + + /** + * 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, 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 = runCatchingRecoverable { + context.services.get(DebuggerEndpointService::class.java) + }.getOrNull() + 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. + * + * [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. 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) /** * Installs [next] as the current scope and cancels whichever scope it displaced. @@ -310,9 +428,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. */ @@ -326,24 +445,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 } @@ -353,17 +478,19 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { toolSource = null McpConnections.closeAll() McpToolCatalog.clear() + AutomaticServers.install(null) } /** * 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 } @@ -404,8 +531,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( 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..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 @@ -13,6 +13,9 @@ 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 with tools that start on (four read-only ones, + * see `ReadOnlyTrust.CORE_TOOLS`). */ data class McpServer( val id: String, @@ -21,6 +24,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/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 8fbb514db..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 @@ -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 @@ -13,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" @@ -27,6 +31,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 +72,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 +102,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 +122,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) } @@ -123,12 +147,15 @@ 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. */ 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 @@ -136,9 +163,18 @@ object McpToolCatalog { try { connect(server) refreshed++ + } catch (e: CancellationException) { + throw e } 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}") + 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") } } return refreshed 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..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 @@ -4,14 +4,16 @@ 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 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.io.InterruptedIOException import java.util.concurrent.CompletableFuture import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ExecutorService @@ -42,6 +44,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. @@ -57,8 +69,9 @@ 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, ) } @@ -68,7 +81,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 +106,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, @@ -113,6 +126,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. @@ -140,21 +154,34 @@ 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) + 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 { + 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.name, e)) + } finally { + running -= callId + cancelled -= callId } /** @@ -169,10 +196,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> = - McpServerStore.servers() + private fun enabledTools(servers: List): List> = + servers .filter { it.enabled } .flatMap { server -> McpToolCatalog.tools(server.id) @@ -200,8 +228,23 @@ class McpToolSource : val exposed = mutableListOf() val taken = mutableSetOf() - for ((server, tool) in enabledTools()) { - val base = McpToolText.exposedName(server.name, tool.name) + // 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( + servers.filter { it.automatic }.map { AutomaticServers.applicationIdOf(it.id) }, + ) + for ((server, tool) in enabledTools(servers)) { + 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 @@ -215,7 +258,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 } @@ -226,26 +269,47 @@ 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. * - * 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/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..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,13 +26,55 @@ 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? { + 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]). + * @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 - val prefix = identifier(serverName).take(MAX_PREFIX_LENGTH).trim('_') 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/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/AppToolNamesTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AppToolNamesTest.kt new file mode 100644 index 000000000..48b210049 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AppToolNamesTest.kt @@ -0,0 +1,157 @@ +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 io.mockk.verify +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_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) } + 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 `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)) + 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/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..1f950d2eb --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServersTest.kt @@ -0,0 +1,334 @@ +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 +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +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("query", "", readOnlyHint = true))) + + current = listOf(endpoint(port = 4002)) + AutomaticServers.refresh() + + val server = AutomaticServers.servers().single() + assertEquals(listOf("query"), server.knownTools) + assertEquals(setOf("query"), 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)) + } + + /** 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)) + } + + /** + * 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) + } + + /** 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) + } + } + + /** 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()) + 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 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("query", "", readOnlyHint = true), + McpTool("get_stats", "", readOnlyHint = true), + McpTool("get_schema", "", readOnlyHint = false), + McpTool("get_events", ""), + ), + ) + + val server = AutomaticServers.servers().single() + 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 new file mode 100644 index 000000000..08134d1d6 --- /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_databases", 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_databases", 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()) + } +} 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..74c724506 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReadOnlyHintParsingTest.kt @@ -0,0 +1,81 @@ +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 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 new file mode 100644 index 000000000..918a694ab --- /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_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`() { + 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_databases")) + 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/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) + } + } +} 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..2b9f30e7a --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginHostErrorTest.kt @@ -0,0 +1,193 @@ +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.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 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.assertNull +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 } + + 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() + } 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) + } + } + + /** + * 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() + 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()) + } +} 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..2704fc576 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginProbeHealthTest.kt @@ -0,0 +1,98 @@ +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 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 +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. The same + * holds for the endpoint retry's refresh. + */ +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()) + } + + @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()) + } +} 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/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.***")) + } } diff --git a/plugins/README.md b/plugins/README.md index 2eb07e5c4..c38ee3ada 100644 --- a/plugins/README.md +++ b/plugins/README.md @@ -148,7 +148,11 @@ 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 26.48 or later, the first release that knows it (26.47 +shipped without it; recheck 26.48 against the real release number before merging). ---