diff --git a/libs/plugin-api.jar b/libs/plugin-api.jar index e20b8aca1..2c4afef3d 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..29218cbf9 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,16 +37,90 @@ 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 field never shows what is stored and an empty field keeps it, so this is the only way back to a server that needs no credential. -Every remote tool asks for approval on every call, and there is no "always -allow" for contributed tools — they run outside the Agent's own path -containment, so the dialog is the only gate. +Every remote tool asks for approval on every call, with one exception: a tool +of the automatic SQLite debugger entry that declares itself read-only may be +given "Always Allow" for the rest of the chat (details under "The SQLite +debugger entry"). Remote tools run outside the Agent's own path containment, so +the dialog is the only gate. + +### The SQLite debugger entry + +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. An app that +stops reporting loses its entry, and the entry's tools, health and session go +with it in the same step (the session ended with the entry's token, which the +app's server requires); if the app comes back before that step has finished +its cleanup, the new entry keeps its own. A call or a listing still running +when the entry goes leaves no session or health behind for it. + +When the entry cannot reach its app, the reason the Agent tab shows says what to +do, told apart by exception type (`SocketTimeoutException` or `ConnectException`, +anywhere in the cause chain): + +- **No answer** (a socket timeout): "The app did not answer. If + the app is in the background, Android may have paused it. Bring the app to the + front and try again." Some phones freeze an app in the background: a Galaxy + Note 20 froze one about 13 minutes after it left the screen. +- **Refused** (nothing listens on the port): "The app is not + running with the SQLite debugger. Open the app again from Code on the Go." The + app's process has ended, or the app was rebuilt without the SQLite debugger. + +Any other failure of the entry, and every failure of a server you add yourself, +keeps the generic reason, such as "Could not reach : ". + +Each app's tools are told apart for the model. Their names start with `db_` and +the first seven characters of the application ID's last segment +(`db_notes_query` for `com.example.notes`, `db_myappli_query` for +`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`). If that prefix is still another app's, as +when two apps' digits agree or the prefix equals another app's `db_` prefix, the +app uses the segment's first character and eight hex digits (`n_3fa1c2d4_query`), +and past that `db_` and a number in application-ID order (`db_1_query`). An app +keeps the first prefix that no other app shares, so the names never depend on +which app was read first. Each description starts with the application ID, as +"com.example.notes (SQLite debugger): ...", and the approval dialog shows it. +Servers you add yourself keep the name prefix taken from their label. + +- 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). +- Approval. This plugin declares each of that entry's tools read-only when the + server sends `readOnlyHint: true` for it (`McpToolSource.Spec.isReadOnly`). + AI-Core 3.6.0 or later then offers "Always Allow" in the approval dialog for + those tools (ADFA-7147). One tap covers that tool for the rest of the chat, + and the Agent asks again in a new chat. Each tool is its own grant, and so is + each app: AI-Core keys a grant by this plugin, the tool's name and a digest of + its description and schema, and the description names the app. The grant + ignores the arguments, so after one tap the Agent can call that tool with any + arguments. It rests on the plugin's own read-only claim, which Code on the Go + cannot check. AI-Core still asks on every call for the tools that are not + read-only, for every tool of a server you add yourself, and, on an AI-Core + older than 3.6.0, for every tool: this plugin does not check AI-Core's + version. AI-Core ignores the tool's own `requiresApproval` and always asks at + least once. ## Transport @@ -74,13 +149,30 @@ Two dependencies were deliberately not taken: parallel with no ordering - `transport/` — `JsonRpc` framing, `SseChunk` line parsing, `McpHttpClient` - `client/` — `McpSession` (handshake, `tools/list`, `tools/call`), - `McpConnections` (one session per server) + `McpConnections` (one session per server, shared by every call and listing), + `McpCallHandle` (one tool call's cancel: its flag and its own connection) - `tools/` — `McpToolSource` (the `ToolSourceRegistry.ToolSource`), - `McpToolCatalog` (what each server last advertised), `McpToolText` (sanitising) + `McpToolCatalog` (what each server last advertised; a SQLite debugger entry's + list is kept beside its endpoint in `debugger/AutomaticServers`, under the lock + that checks the endpoint, so a listing of a replaced endpoint cannot overwrite + the new one's), `McpToolText` (sanitising) - `settings/` — server CRUD, per-tool toggles, the settings pane - `errors/` — HTTP and JSON-RPC failures reduced to one translated sentence - `security/SecureTokenStore.kt` — this plugin's Keystore alias, over the IDE's `KeystoreSecretStore` +## Known limits + +Three rare session races, accepted for now: + +- A Save or Clear that changes only the credentials can leave one session on a + third-party server that needs the old token to end it; the session expires on + the server. +- A SQLite debugger entry's health follows the entry, not the port, so after the + app moves to a new port a result from the old one can show for up to one + 20-second probe cycle. +- Two requests that both get a 404 for the same expired session can start an + extra handshake and leave one session to expire; tracked in ADFA-7250. + ## Security notes - Tool names and descriptions from a server are **untrusted remote text**. Names @@ -105,11 +197,64 @@ 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. +- A server's token and headers go only to the URL it is saved with. A save + writes the URL, token and headers in one step that a request's credential + read waits for, so no request pairs the new URL with the old token, or the + old URL with the new. The old session is taken out before that step and + ended after it, its DELETE carrying the credentials it was opened with, so a + server that wants its token to end a session gets it; any of its requests + still running after the save finish with neither. Clearing the credential + ends the session the same way. If the Keystore refuses to store a new token + or headers while the URL changes, the old ones are forgotten with the + change, so the new URL never gets them; the pane reports the failure and the + credential has to be entered again. If forgetting them fails too, the URL + stays as it was. + Accepted as rare: when the URL is put back, a token or headers that the + Keystore did store for the new URL in that save stay stored, and requests to + the old URL carry them. That case needs two refused Keystore writes and one + accepted write in the same save; the pane reports the failure, and **Clear + stored credential** removes them. + Limit, on purpose: a blank token field means "keep the stored token", so + changing only the URL and leaving the token blank sends the stored token to + the new URL. Headers behave the same only when the stored ones could not be + read, which the pane cannot draw; rows it did draw replace the stored set, + so none left in the pane forgets them. To send the new URL no token, use + **Clear stored credential**. + Also accepted: the credentials lock is one lock for every server, held across + the Keystore writes of a save and the two Keystore decrypts of the settings + dialog's load, so a slow Keystore stalls the credential reads of other servers + for that long. - Redirects are never followed automatically. A 3xx is repeated only when it resolves to the same origin, so the bearer token and the user's own headers cannot be replayed to another host in one hop. - Error bodies stay in logcat. The transcript gets one sentence. +- The connection log masks every credential the request carried wherever the + server echoes it, escaped or not (`McpRedactor`), and the session id a reply + assigns wherever that reply echoes it. The body of a `202 Accepted` + is kept only in part, cut at a fixed length; when the cut falls inside a + credential, what was kept of it is masked too, so the log never shows the + start of one. +- A server's JSON is parsed only when it nests arrays and objects at most 100 + levels deep, brackets inside strings not counted (`JsonDepth`): parsing + recurses once per level, and a body of nothing but `[` would run Code on the + Go out of stack. The scan reads strict JSON and refuses any text that is not: + Android's org.json also reads `;` and `=` separators, comments, + single-quoted strings and unquoted text, each a way to make it nest through + brackets a strict scan took as text. A refused reply fails its call or + listing with the rule it broke, "nests arrays and objects more than 100 + levels deep" or "is not strict JSON" with the character found, so the + server's author knows which to look for; a refused body in the connection log + is shown as it came. +- A `202 Accepted` body is read and thrown away, for at most 1 MiB of characters + and 10 seconds; one that runs past either is abandoned and its socket + disconnected, not reused. The worst case is the 10 seconds plus one read + timeout, since a read already blocked ends only at its own timeout. 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..c857fc016 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.

@@ -70,8 +71,10 @@

Core functionality

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

    Technical architecture

    McpToolSourceThe tool source AI Core sees. Publishes the enabled tools of the enabled servers, runs a call on its own thread pool, and drops that call's own connection when an Agent run is - stopped, leaving any concurrent call against another server alone. + stopped. Any other call, and the health check's listing, is left alone, + whether it is against the same server or another. McpToolCatalogWhat each server last advertised, held in memory. The Agent reads its tool list on a UI-adjacent path, so that - list is answered from memory and never blocks on the network. + list is answered from memory and never blocks on the network. A SQLite + debugger entry's list is kept beside its endpoint, so a listing of an + endpoint a relaunch replaced cannot overwrite the new one's. McpSessionOne protocol conversation per server: initialize, tools/list, tools/call, session lifetime, and one clean re-handshake when a server drops a @@ -119,7 +125,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.

    @@ -137,11 +144,14 @@

    Usage

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

    Key benefits

  • Context stays affordable — per-tool switches, off by default, keep a ninety-tool server from crowding out the conversation on a phone.
  • Nothing runs unattended — every remote call is approved - individually, with its arguments visible, and no "always allow" exists for - contributed tools.
  • + individually, with its arguments visible. The only exception is a + read-only SQLite debugger tool that you choose to allow for the rest of one + chat.
  • Extensible without code — supporting a new service means adding its URL in settings; neither this plugin nor AI Core changes.
  • @@ -171,6 +182,14 @@

    Limitations

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

    @@ -184,6 +203,12 @@

    Troubleshooting

    Stored rather than the value, so typing replaces it. Tools missing from the AgentCheck the server is enabled, at least one tool is switched on, and AI Core is installed and active. + "The app … did not answer"The SQLite debugger entry's app + gave no answer. Android may pause an app in the background: bring the app + to the front and try again. + "The app … is not running with the SQLite debugger"The app + has stopped, or it was rebuilt without the SQLite debugger. Open the app + again from Code on the Go. diff --git a/plugins/AI-Agent-MCP/build.gradle.kts b/plugins/AI-Agent-MCP/build.gradle.kts index ba33d82d3..5dc962237 100644 --- a/plugins/AI-Agent-MCP/build.gradle.kts +++ b/plugins/AI-Agent-MCP/build.gradle.kts @@ -15,8 +15,8 @@ android { applicationId = "com.itsaky.androidide.plugins.aiagentmcp" minSdk = 33 targetSdk = 36 - versionCode = 2 - versionName = "1.1.0" + versionCode = 3 + versionName = "2.0.0" } buildFeatures { 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
  • Enter the endpoint URL. It usually ends in /mcp.
  • Add an access token if the server needs one. It is encrypted with a key held in the Android Keystore, and sent only to that server, as an - Authorization: Bearer header.
  • + Authorization: Bearer header. Leaving the field empty keeps the + stored token, so if you change a server's URL and leave it empty, the stored + token is sent to the new URL. To send the new URL no token, use + Clear stored credential first.
  • The URL must be https:// unless the server runs on this device. Plain http:// is accepted only for localhost, 127.0.0.1 or [::1], such as a server started in the @@ -72,23 +75,39 @@

    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 - own file tools are confined to the open project; a remote tool is confined by - nothing this device controls, so the dialog is the only gate — read it.

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

    What is sent

    • 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 @@ -103,6 +122,19 @@

      Which servers work

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

      +

      Known limits

      +

      Three rare session races are accepted for now:

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

      Troubleshooting

      When Connect fails, tap Show details under the message to see every request it sent and everything the server answered: status line, @@ -132,6 +164,13 @@

      Troubleshooting

      least one tool is switched on, and AI Core is installed and active.
    • Everything times out on mobile data — some servers are slow to handshake; try again on Wi-Fi before assuming the URL is wrong.
    • +
    • "The app … did not answer" — the SQLite debugger entry's app gave + no answer. Android may pause an app in the background: bring the app to the + front and try again.
    • +
    • "The app … is not running with the SQLite debugger" — nothing + answers on the app's SQLite debugger port: the app has stopped, or it was + rebuilt without the SQLite debugger. Open the app again from Code on the + Go.
    diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpCallHandle.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpCallHandle.kt new file mode 100644 index 000000000..799c3c0d6 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpCallHandle.kt @@ -0,0 +1,97 @@ +package com.itsaky.androidide.plugins.aiagentmcp.client + +import android.util.Log +import com.itsaky.androidide.plugins.aiagentmcp.errors.runCatchingRecoverable +import com.itsaky.androidide.plugins.aiagentmcp.logging.LOG_PREFIX +import java.io.InterruptedIOException +import java.net.HttpURLConnection +import java.util.concurrent.atomic.AtomicReference + +private const val TAG = "$LOG_PREFIX.McpCallHandle" + +/** + * One tool call's way to be stopped: its cancel flag and the connection its current request uses. + * + * Per call, not per session. Every call to a server, the health probe's listing and the relisting + * of a SQLite debugger entry share one [McpSession]; a connection slot on the session held whichever + * request had published last, so a cancel dropped another request's socket (the probe's listing + * was then marked degraded) and the cancelled call ran on to its timeout. A listing passes no + * handle, so no call's cancel can reach it. + * + * The handshake, the same one the tool worker uses with its flag: a request publishes its + * connection and then reads the flag ([attach]); [cancel] sets the flag and then takes the + * connection. Both sides are volatile, so however the two interleave, one sees the other: either + * the request finds the flag, or the cancel finds the connection. A cancel that lands before the + * request has a connection at all, while it reads its credentials from the Keystore for instance, + * is caught by the first. + * + * Finding the connection is not enough on its own: [attach] runs before the connection is + * connected, and a `disconnect()` then does nothing (Android's and the JDK's both return early with + * no connection to drop), so the first write would connect and send the request anyway. The + * request reads the flag a second time once its connection is up, before it writes anything, and a + * third time after the write, before it asks for the answer ([throwIfCancelled]): without a + * streaming mode the write only fills a buffer, and the request goes out with that first read of + * the answer. A cancel before the last read is caught there. One after it disconnects a connection + * that is up: Android's should then fail the request rather than send it, which is inferred, not + * run. (The JDK, which only the tests run on, reconnects instead.) + */ +class McpCallHandle { + + @Volatile private var cancelled = false + + private val connection = AtomicReference(null) + + /** Whether [cancel] has been called. */ + val isCancelled: Boolean get() = cancelled + + /** + * Stops the call: a request not yet sent never is, and one in flight loses its socket. + * + * A disconnect that fails with an Exception or a LinkageError is survived, since the call is + * being abandoned anyway; any other Error, an OutOfMemoryError above all, propagates. + */ + fun cancel() { + cancelled = true + connection.getAndSet(null)?.let { conn -> + runCatchingRecoverable { conn.disconnect() } + .onFailure { e -> Log.d(TAG, "Dropping a cancelled call's connection failed: $e") } + } + } + + /** + * Publishes [conn] as the connection this call's current request uses, then reads the flag. + * + * Called before [conn] is connected; [throwIfCancelled] reads the flag again once it is. + * + * @param conn the request's connection, opened but not yet connected. + * @throws InterruptedIOException when the call was cancelled, which is how a dropped connection + * reports a cancel too. + */ + internal fun attach(conn: HttpURLConnection) { + connection.set(conn) + if (cancelled) { + connection.compareAndSet(conn, null) + throw InterruptedIOException("The tool call was cancelled before its request was sent") + } + } + + /** + * Reads the flag again, once the request's connection is connected and before anything is + * written to it: a cancel that landed after [attach] read the flag disconnected a connection + * that was not connected yet, which does nothing. Read once more after the write, before the + * request goes out: the write only filled a buffer. + * + * @throws InterruptedIOException when the call was cancelled. + */ + internal fun throwIfCancelled() { + if (cancelled) throw InterruptedIOException("The tool call was cancelled before its request was sent") + } + + /** + * Forgets the connection once its request has ended, so a late [cancel] does not disconnect a + * connection whose socket may have gone back to the pool. + */ + internal fun detach() { + connection.set(null) + } +} 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..faca6aed8 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpConnections.kt @@ -1,6 +1,10 @@ package com.itsaky.androidide.plugins.aiagentmcp.client import android.util.Log +import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticEndpoint +import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticServers +import com.itsaky.androidide.plugins.aiagentmcp.debugger.McpServers +import com.itsaky.androidide.plugins.aiagentmcp.errors.runCatchingRecoverable 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 @@ -38,14 +42,48 @@ object McpConnections { private val sessions = ConcurrentHashMap>() /** - * The session for [server], created if needed. + * Runs [block] with [server]'s session, created if needed, and ends the session once [block] is + * done when it was not kept. Nothing else would end that one, so the server would keep the + * session its `initialize` assigned. Its DELETE reads the credentials as each of its requests + * did, under the same rule: only for the URL it was built for, while the server still has it, + * so a server that is gone gets none, as the requests did. * - * Reads the token and the headers, so call this off the main thread. + * A server no longer configured gets a session that is not kept: the caller is a call or a + * listing that outlived the server's removal, and a session stored for it would outlive the + * server with nothing left to close it. So does a server of the user's whose URL has been + * edited since the caller read it ([McpServers.isConfigured]): its session, for the old URL, + * would replace the one for the new. The check is made under this object's lock, which the + * removal of a SQLite debugger entry takes, to detach its session, only after the entry has + * left the list; so either that removal takes the session out or this sees the entry gone. A + * server of the user's is removed from the store after its session is ended, so its DELETE + * still has the credentials; the settings pane ends whatever a lookup stored between the two + * once the server is gone. + * + * Reads the token and the headers, and is blocking, like [block]: ending the session sends a + * DELETE. Call it off the main thread. * * @param server the server to connect to. - * @return its session, not yet initialized. + * @param block the calls to make; the session is not yet initialized. + * @return what [block] returned. + */ + fun withSession(server: McpServer, block: (McpSession) -> T): T { + val found = lookUp(server) + try { + return block(found.session) + } finally { + if (!found.kept) found.session.close() + } + } + + /** + * What [lookUp] found. + * @property kept whether [session] is the one stored for its server; false for a server no + * longer configured, or no longer at the URL the caller had. */ - fun session(server: McpServer): McpSession { + private class Found(val session: McpSession, val kept: Boolean) + + /** Finds or builds [server]'s session for [withSession], telling one it kept from one it did not. */ + private fun lookUp(server: McpServer): Found { val key = keyFor(server) // Locked, so two tool calls arriving together cannot each build a session and leave one of @@ -54,30 +92,189 @@ object McpConnections { var stale: McpSession? = null val session = synchronized(this) { val current = sessions[server.id] - if (current != null && current.first == key) return current.second - stale = current?.second + if (current != null && current.first == key) return Found(current.second, kept = true) // A supplier, not the values: the session is kept for the life of the process, and a // token in one of its fields would be readable in a heap dump for just as long. - McpSession(server.url, { credentialsFor(server.id) }) - .also { sessions[server.id] = key to it } + val fresh = McpSession(server.url, { credentialsFor(server.id, server.url) }) + if (!McpServers.isConfigured(server)) return Found(fresh, kept = false) + stale = current?.second + fresh.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 Found(session, kept = true) + } + + /** + * A session taken out of use, with the credentials its DELETE is to carry, read as it was taken + * out. It is ended later, outside the caller's lock, and by then the credentials may have gone + * with the server: a SQLite debugger entry's token leaves with its entry, a deleted server's + * with the server. Read at the DELETE they would be empty, and the server would refuse it and + * keep its session open. + * + * @property url the URL the session was built for. + * @property credentials what the DELETE carries; null when they could not be read, when + * [close] reads them again. + */ + class Released internal constructor( + private val session: McpSession, + private val url: String, + private val credentials: McpCredentials?, + ) { + /** + * Ends the session, best effort: sends a DELETE when it has a server-side id, so never under + * a lock. An Exception or a LinkageError is survived; any other Error propagates. + * + * @param saved credentials the caller read before they could go, carried in place of the + * ones saved here when they were read for this session's URL, and ignored for any other: + * they do not belong there. + */ + fun close(saved: SavedCredentials? = null) { + val carried = saved?.takeIf { it.url == url }?.credentials ?: credentials + runCatchingRecoverable { if (carried != null) session.close(carried) else session.close() } } - return session + } + + /** + * A server's credentials as read for one URL, for a DELETE sent once they may have gone with + * the server; see [saveCredentials]. + */ + class SavedCredentials internal constructor(internal val url: String, internal val credentials: McpCredentials) + + /** + * [serverId]'s credentials, read now for the URL it has now: for a caller about to delete one of + * the user's servers, which may find a session to end once the deletion has taken them away. + * [Released.close] carries them only to a session built for that URL. + * + * @return them, or null for a server not stored or credentials that could not be read. + */ + fun saveCredentials(serverId: String): SavedCredentials? = McpServerStore.readTogether { + // The URL and the credentials read together, so they are the pair the server has. + val url = McpServerStore.server(serverId)?.url ?: return@readTogether null + runCatchingRecoverable { SavedCredentials(url, credentialsFor(serverId, url)) } + .onFailure { e -> Log.d(TAG, "Could not read the credentials to end '$serverId' with: $e") } + .getOrNull() } /** 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() } } + detach(serverId)?.close() } - /** Ends every session, for the plugin shutting down. */ + /** + * Takes the session for [serverId] out without ending it, with its credentials read now, for a + * caller that must take it out under a lock of its own and end it once that lock is let go, + * since ending it sends a DELETE. + * + * Taken under this object's lock, as [withSession] replaces a session under it. The credentials + * are read once that is let go, still under the caller's lock: for a server of the user's that is + * a Keystore read, never network. Safe to call under another lock: under this one, [withSession] + * only checks the server is configured, which takes no lock (`McpServers.isConfigured`), and it + * reads the credentials before it takes this one. + * + * @return the session taken out, or null when [serverId] had none. + */ + fun detach(serverId: String): Released? = release(serverId) { url -> credentialsFor(serverId, url) } + + /** + * As [detach], for a SQLite debugger entry that has already left the list, its app gone: its + * token can no longer be read, so it is taken from [endpoint], the one the entry had. As for a + * request, it goes only to the URL it belongs to. `AutomaticServers` does this, in the same step + * that removes the entry. + * + * @param endpoint the endpoint the entry had when it was removed. + */ + fun detachRemoved(serverId: String, endpoint: AutomaticEndpoint): Released? = + release(serverId) { url -> automaticCredentials(endpoint, url) } + + /** + * Ends every session, for the plugin shutting down. Every one taken out is ended, even when + * reading one's credentials threw an Error; that Error is thrown once they have all been ended. + */ fun closeAll() { - sessions.values.forEach { (_, session) -> runCatching { session.close() } } - sessions.clear() + val released = ArrayList() + var failure: Error? = null + try { + detachAll(released) + } catch (e: Error) { + failure = e + } + try { + endAll(released) + } catch (e: Error) { + failure?.addSuppressed(e) ?: run { failure = e } + } + failure?.let { throw it } + } + + /** + * Ends each of [released], best effort, as [Released.close] does one. An Error from one, which + * [Released.close] lets through, does not stop the rest: each is ended, and the first Error is + * thrown once they all have been, the others added to it as suppressed. + */ + fun endAll(released: List) { + var first: Error? = null + for (session in released) { + try { + session.close() + } catch (e: Error) { + first?.addSuppressed(e) ?: run { first = e } + } + } + first?.let { throw it } + } + + /** + * Takes every session out without ending it, as [detach] does one: for a caller that empties + * the map under a lock of its own and ends the sessions once that lock is let go, since each + * close sends a DELETE and can wait for a handshake in flight. + * + * Every session that leaves the map is added to [into] as it leaves, so a caller that ends + * [into] in a `finally` loses none. An Error from reading one session's credentials, which + * [runCatchingRecoverable] lets through, does not stop the others: that session goes into + * [into] with no credentials, so it is ended with none, the rest are taken out, and the first + * Error is thrown after the last, the others added to it as suppressed. + * + * @param into receives the sessions taken out, each with its credentials. + * @return [into]. + */ + fun detachAll(into: MutableList = ArrayList()): List { + val taken = synchronized(this) { sessions.toMap().also { sessions.clear() } } + var first: Error? = null + for ((id, entry) in taken) { + try { + into += released(entry, id) { url -> credentialsFor(id, url) } + } catch (e: Error) { + // Explicit empty credentials: a close with none given would read them again, and throw. + into += Released(entry.second, entry.first.url, McpCredentials("", emptyMap())) + first?.addSuppressed(e) ?: run { first = e } + } + } + first?.let { throw it } + return into + } + + /** Takes [serverId]'s session out; see [detach]. */ + private fun release(serverId: String, credentials: (url: String) -> McpCredentials): Released? { + val entry = synchronized(this) { sessions.remove(serverId) } ?: return null + return released(entry, serverId, credentials) + } + + /** + * [entry]'s session with its credentials, read for the URL it was built for. A failed read + * leaves them unread: the close tries again, which beats not ending the session. + */ + private fun released( + entry: Pair, + serverId: String, + credentials: (url: String) -> McpCredentials, + ): Released { + val read = runCatchingRecoverable { credentials(entry.first.url) } + .onFailure { e -> Log.d(TAG, "Could not read the credentials to end '$serverId' with: $e") } + return Released(entry.second, entry.first.url, read.getOrNull()) } /** @@ -87,13 +284,33 @@ 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. A server's credentials are released + * only while it still points there; a session for a URL it has left gets none, so its + * `close()` and any call still in flight cannot hand the credentials meant for the new URL + * to the old one. That holds for an automatic entry, whose replaced endpoint would get the + * new process's token, and for a server of the user's, whose old URL would get the token + * and headers the user entered for the new one. A user's server's URL is read with its + * credentials, under the store's credentials lock, which a save holds while it writes all + * three: a read between its writes would pair the new URL with the old token and headers. * @return its token and headers; either may be empty. * @throws UnreadableSecretException when a stored credential cannot be decrypted here. Sending * the request without it would earn a 401 and tell the user their token was refused. * @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. + return automaticCredentials(AutomaticServers.endpoint(serverId), url) + } + return McpServerStore.readTogether { storedCredentials(serverId, url) } + } + + /** [credentialsFor] for a server of the user's. Call under `McpServerStore.readTogether`. */ + private fun storedCredentials(serverId: String, url: String): McpCredentials { + // A server removed since, or moved to another URL, gets nothing; checked before the + // Keystore is read, so its secrets are not even decrypted. + if (McpServerStore.server(serverId)?.url != url) return McpCredentials("", emptyMap()) 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. @@ -111,6 +328,18 @@ object McpConnections { return McpCredentials(token, McpServerStore.headers(serverId)) } + /** + * A SQLite debugger entry's credentials from [endpoint]: its token, but only while [url] is + * that endpoint's own, so a session for a replaced endpoint cannot hand the new process's token + * to the old port. + * @param endpoint the entry's endpoint, or null when it has none. + * @param url the URL the session was built for. + */ + private fun automaticCredentials(endpoint: AutomaticEndpoint?, url: String): McpCredentials { + val token = if (endpoint != null && AutomaticServers.urlFor(endpoint) == url) endpoint.token else "" + return McpCredentials(token, emptyMap()) + } + /** * What [server]'s session was built from, credentials included as digests. * @@ -123,7 +352,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..fb1da8a18 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSession.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSession.kt @@ -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 @@ -20,6 +22,11 @@ private const val TAG = "$LOG_PREFIX.McpSession" * Every call is blocking and belongs off the main thread; the callers are a background executor * (tool invocation) and the settings pane's IO dispatcher (Connect). * + * The session is shared: every tool call to its server, the health probe's listing and the + * relisting of a SQLite debugger entry use it, at the same time. So it holds no connection of its + * own for a cancel to drop; a tool call brings an [McpCallHandle], and only that call's requests + * are published to it. + * * @param endpoint the server's MCP URL. * @param credentials read once per request; see [McpCredentials] for why they are not held here. * @param http the transport; injectable so the protocol can be exercised without a socket. @@ -67,9 +74,6 @@ class McpSession( @Volatile private var initialized = false - /** The connection a call is currently using, so [cancel] can drop it mid-flight. */ - @Volatile private var liveConnection: HttpURLConnection? = null - /** Who is watching the exchanges made on each thread; see [recording]. */ private val recorder = ThreadLocal() @@ -82,8 +86,21 @@ class McpSession( * * @throws IOException when the server cannot be reached or refuses the handshake. */ + fun initialize() = initialize(handle = null) + + /** + * As [initialize], with the `initialize` request published to [handle], so a call cancelled + * while it waits on the handshake stops waiting. A cancelled handshake is not recorded, and the + * next caller repeats it. + * + * `notifications/initialized` is sent without the handle: once the server has answered, the + * handshake is finished for every caller, and a session marked initialized whose server was + * never told so would have each later request answered "not initialized". + * + * @param handle the calling tool call's, or null for a listing. + */ @Synchronized - fun initialize() { + private fun initialize(handle: McpCallHandle?) { if (initialized) return val params = JSONObject().apply { @@ -98,7 +115,7 @@ class McpSession( ) } - val result = call(METHOD_INITIALIZE, params) + val result = call(METHOD_INITIALIZE, params, handle) negotiatedVersion = result.optString("protocolVersion").takeIf { it.isNotBlank() } ?: PREFERRED_PROTOCOL_VERSION serverName = result.optJSONObject("serverInfo")?.optString("name")?.takeIf { it.isNotBlank() } @@ -142,11 +159,19 @@ class McpSession( * * @param name the tool's own name, as the server listed it. * @param arguments the call arguments. + * @param handle this call's own, so a cancel stops this call's requests and no one else's; + * null for a call nothing will cancel. * @return the outcome, successful or not. * @throws IOException when the server cannot be reached. + * @throws java.io.InterruptedIOException when [handle] was cancelled; a request not yet sent + * is not sent. */ - fun callTool(name: String, arguments: Map): McpCallResult { - initialize() + fun callTool( + name: String, + arguments: Map, + handle: McpCallHandle? = null, + ): McpCallResult { + initialize(handle) val params = JSONObject().apply { put("name", name) @@ -154,7 +179,7 @@ class McpSession( } val result = try { - call("tools/call", params) + call("tools/call", params, handle) } catch (e: McpProtocolException) { // A protocol-level error for a single call is the tool failing, not the session dying. return McpCallResult(false, "", e.message ?: "The server rejected the call.") @@ -187,17 +212,29 @@ class McpSession( } } - /** Drops the connection a call is blocked on, so a stopped agent run does not wait it out. */ - fun cancel() { - runCatching { liveConnection?.disconnect() } - } + /** + * 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. + */ + fun close() = close(credentials) + + /** + * As [close], with credentials read earlier: for a session taken out of use while they could + * still be read, and ended once they may have gone with the server, as when a SQLite debugger + * entry is removed or the plugin deactivates. Read at the DELETE, they would be empty, and the + * server would refuse it and keep the session open. + * + * @param saved what the DELETE carries. + */ + fun close(saved: McpCredentials) = close { saved } - /** Ends the server-side session, if there is one, and forgets the handshake. */ @Synchronized - fun close() { + private fun close(read: () -> McpCredentials) { sessionId?.let { id -> - runCatching { - val current = credentials() + runCatchingRecoverable { + val current = read() http.deleteSession(endpoint, current.token, id, current.headers) } } @@ -237,15 +274,20 @@ class McpSession( * * @param method the MCP method. * @param params its parameters, or null. + * @param handle the calling tool call's, or null for a listing. * @return the `result` object. * @throws McpProtocolException when the server answers a JSON-RPC error. * @throws IOException on transport failure or a reply that is not one. */ - private fun call(method: String, params: JSONObject? = null): JSONObject { + private fun call( + method: String, + params: JSONObject? = null, + handle: McpCallHandle? = null, + ): JSONObject { val envelope = JsonRpc.request(nextId.getAndIncrement().toString(), method, params) val response = try { - send(envelope) + send(envelope, handle) } catch (e: McpHttpException) { val retryable = e.statusCode == HttpURLConnection.HTTP_NOT_FOUND && sessionId != null && @@ -254,8 +296,8 @@ class McpSession( Log.i(TAG, "Session expired; re-initializing before retrying $method") sessionId = null initialized = false - initialize() - send(envelope) + initialize(handle) + send(envelope, handle) } else { throw e } @@ -266,6 +308,10 @@ class McpSession( val reply = try { JsonRpc.parseReply(document) + } catch (e: JsonRpc.UnparsedReplyException) { + // Refused rather than parsed, so the call or listing fails with the rule the reply broke + // instead of a StackOverflowError ending Code on the Go. + throw IOException("The server's reply to '$method' ${e.message}; it was not read.", e) } catch (e: Exception) { throw IOException("The server's reply to '$method' was not JSON-RPC: ${e.message}") } ?: throw IOException("The server's reply to '$method' carried no result.") @@ -276,12 +322,19 @@ class McpSession( return reply.result ?: JSONObject() } - /** POSTs one envelope, tracking the connection so [cancel] can reach it. */ - private fun send(envelope: JSONObject): McpHttpClient.Response { + /** + * POSTs one envelope. + * + * @param handle the calling tool call's: its connection is published there before anything is + * sent, and the request is refused if the call was cancelled meanwhile, while the credentials + * were read for instance, or after that, before the connection was connected or while the + * body was written. Null for a listing, which no call's cancel reaches. + */ + private fun send(envelope: JSONObject, handle: McpCallHandle? = null): McpHttpClient.Response { // Read here rather than held on the session, so the plaintext lives for one request. val current = credentials() - // Cleared in a finally: a call that threw would otherwise leave [cancel] holding a - // connection that is already closed, and the next cancel would reach nothing live. + // Forgotten in a finally, so a late cancel does not disconnect a connection whose request + // has ended and whose socket may be back in the pool. val response = try { http.post( url = endpoint, @@ -290,11 +343,12 @@ class McpSession( sessionId = sessionId, protocolVersion = negotiatedVersion, extraHeaders = current.headers, - onConnected = { liveConnection = it }, + onConnected = { conn -> handle?.attach(conn) }, + beforeSend = { handle?.throwIfCancelled() }, exchangeListener = recorder.get() ?: McpExchangeListener.NONE, ) } finally { - liveConnection = null + handle?.detach() } response.sessionId?.let { sessionId = it } return response @@ -314,6 +368,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..d1a4d6c28 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt @@ -0,0 +1,345 @@ +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.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:" + + /** + * One entry: its endpoint and the tools that endpoint listed. Kept together, and replaced + * together under this object's lock, so a list can only ever be stored beside the endpoint it + * came from; see [recordTools]. + */ + private class State(val endpoint: AutomaticEndpoint, val tools: List = emptyList()) + + @Volatile private var states: Map = emptyMap() + + @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. + * + * The first read tells no endpoint listener (see [addEndpointListener]): whoever installs a + * source lists every entry straight after, as the plugin's activation does with + * `McpToolCatalog.refreshAll`, and a listener told of each entry would list it a second time. + * Change listeners are told as on any read. + * + * @param keepGoing false once the activation installing [source] is over. The first read blocks + * and cannot be cancelled, so an activation that ended during it must neither keep [source] + * nor publish what it read: deactivation has already cleared everything, and a later + * activation owns the state now. + */ + fun install(source: () -> List, keepGoing: () -> Boolean) { + synchronized(this) { + if (!keepGoing()) return + this.source = source + } + readEndpoints(keepGoing, tellEndpointListeners = false) + } + + /** 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) } + } + + /** + * Registers [listener], called after the set of entries, a port, a token or a tool list + * changed. Adding one already registered does nothing, so a host that activates the plugin + * twice still gets one call per change, and one [removeChangeListener] takes it out. + */ + fun addChangeListener(listener: () -> Unit) { + listeners.addIfAbsent(listener) + } + + fun removeChangeListener(listener: () -> Unit) { + listeners.remove(listener) + } + + /** How many change listeners are registered; a test seam for a listener registered twice. */ + internal val changeListenerCount: Int get() = listeners.size + + /** + * Registers [listener], called with the id of an entry that appeared or whose port or token + * changed, so the owner can list its tools at once instead of at the next probe. Adding one + * already registered does nothing, as for [addChangeListener]. + * + * Guarded like the change listeners: an Exception or a LinkageError from [listener] costs only + * that call, and any other Error propagates to [refresh]'s caller; see [runCatchingRecoverable]. + */ + fun addEndpointListener(listener: (String) -> Unit) { + endpointListeners.addIfAbsent(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. + * + * An entry that went away loses its tools with its entry, and its health and session are taken + * out in the same step, under this object's lock: by ID they would also be the resources of an + * entry a later read restores, so cleaning up after the lock was let go could take the health + * and session of the app's new endpoint. Only the session taken out is closed, after the lock + * is let go, since closing it sends a DELETE; the health listeners are told then too. The DELETE + * carries the token the entry had, taken from the entry as it is removed: once it has left the + * list no token can be read for it, and the app's server refuses a DELETE without one. + * + * A read that fails with an Exception or a LinkageError leaves the entries as they were; any + * other Error, an OutOfMemoryError above all, propagates to the caller. So does one from a + * change, health or endpoint listener, or from closing the session of an entry that went away. + * Such an Error comes after the new entries are stored, and the resources of the entries that + * went away are taken out with them, so it skips only what was still to run for this read: + * closing the remaining sessions taken out, telling the health listeners, the remaining + * endpoint listeners, the reset of a refused credential for the remaining moved entries, and + * the change listeners. No later read repeats them, since it finds those entries unchanged. + * That is accepted rather than guarded against: the Error is the process failing, and the + * IDE's uncaught-exception handler, which it is on its way to, ends it. + * + * @param keepGoing checked after the read, before anything is stored. + * @return true when the set of entries, a port or a token changed. + */ + fun refresh(keepGoing: () -> Boolean = { true }): Boolean = + readEndpoints(keepGoing, tellEndpointListeners = true) + + /** + * [refresh] itself. + * + * @param tellEndpointListeners false for [install]'s first read; see there. + */ + private fun readEndpoints(keepGoing: () -> Boolean, tellEndpointListeners: Boolean): Boolean { + val (read, ticket) = synchronized(this) { + val current = source ?: return false + current to ++readsStarted + } + 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 detached = mutableListOf() + var healthForgotten = false + 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 + // Here, not after the lock: a read that restores the app has to come after this one, + // so the health and session taken out are this entry's, never its successor's. + // McpConnections takes its own lock inside this one and never calls in here under it. + for (id in old.keys - next.keys) { + McpConnections.detachRemoved(id, old.getValue(id).endpoint)?.let { detached += it } + if (McpServerHealth.detach(id)) healthForgotten = true + } + old.mapValues { it.value.endpoint } != next.mapValues { it.value.endpoint } + } + for (session in detached) session.close() + if (healthForgotten) McpServerHealth.notifyChanged() + for (id in moved) { + // A refused credential is not final for this entry: the new one has not been tried. + McpServerHealth.credentialChanged(id) + if (tellEndpointListeners) 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 + + /** + * The tools [serverId] last listed, as [recordTools] stored them; `McpToolCatalog.tools` + * answers an automatic entry from here. + * + * @return them, empty before its first listing or when it has no entry (any more). + */ + fun tools(serverId: String): List = states[serverId]?.tools.orEmpty() + + fun urlFor(endpoint: AutomaticEndpoint) = "http://127.0.0.1:${endpoint.port}/mcp" + + /** + * Remembers what the server listed. The only writer of an automatic entry's tools, which + * [tools] and [servers] both read. + * + * @param origin the endpoint the list was fetched from. A list from an endpoint that has since + * been replaced belongs to the old process and is dropped. The check and the write share one + * lock, so neither a refresh nor the replacement endpoint's own listing can slip between + * them: an old listing that passed its check before a relaunch stores its list beside the old + * endpoint, which the relaunch's read then carries over until the new process lists. + * @return false when the list was dropped (no entry any more, or [origin] is out of date). + */ + fun recordTools(serverId: String, origin: AutomaticEndpoint, tools: List): Boolean { + 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() + + /** + * Whether [server] is configured now: the check that keeps a call or a listing which outlived + * a server's removal from bringing back that server's session, health or tools. + * + * A server of the user's counts only at the URL [server] carries. A probe, a listing or a call + * handed the server before its URL was edited asks the old URL, which gets no credentials + * (`McpConnections.credentialsFor`): its 401 would otherwise mark the server refused after the + * edit had cleared that, so the probe skipped it until the next edit, and its session would + * replace the one for the new URL. A SQLite debugger entry counts by id: a call retried on its + * new endpoint (`EndpointRetry`) records its outcome under the entry it started with, and its + * session is keyed by URL and token anyway. + */ + fun isConfigured(server: McpServer): Boolean = + if (AutomaticServers.isAutomatic(server.id)) AutomaticServers.endpoint(server.id) != null + else McpServerStore.server(server.id)?.url == server.url +} diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/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..6741e97ac --- /dev/null +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReadOnlyTrust.kt @@ -0,0 +1,53 @@ +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: AI-Core overrides `requiresApproval` + * to true for every contributed tool (`ContributedToolHandler`). It does let AI-Core 3.6.0 or later + * offer "Always Allow" for that tool, for the rest of the chat (ADFA-7147). Each app's tool is its own + * grant, and the grant ignores the arguments. On an older AI-Core the Agent asks on each call. + * + * Only that entry may use this: the hint is the server's own claim, and the SQLite debugger endpoint + * is the one server whose code the IDE itself installed. A server the user adds by hand is never asked. + */ +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 + * "Always Allow" offered on a loose reading cannot be taken back for the rest of the chat. + * + * @param hint the value under `readOnlyHint`, or null when absent. + */ + fun isReadOnlyHint(hint: Any?): Boolean = hint == true +} diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpErrorFormatter.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpErrorFormatter.kt index 3a4072cfc..73fb04dfd 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpErrorFormatter.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpErrorFormatter.kt @@ -3,13 +3,16 @@ package com.itsaky.androidide.plugins.aiagentmcp.errors import android.content.Context import com.itsaky.androidide.plugins.aiagentmcp.R import com.itsaky.androidide.plugins.aiagentmcp.client.McpProtocolException +import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticServers import com.itsaky.androidide.plugins.aiagentmcp.security.UnavailableSecretException import com.itsaky.androidide.plugins.aiagentmcp.security.UnreadableSecretException +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServer import com.itsaky.androidide.plugins.aiagentmcp.transport.McpCleartextException import com.itsaky.androidide.plugins.aiagentmcp.transport.McpCredential import com.itsaky.androidide.plugins.aiagentmcp.transport.McpHttpException import com.itsaky.androidide.plugins.aiagentmcp.transport.McpRedirectException import java.io.InterruptedIOException +import java.net.ConnectException import java.net.SocketTimeoutException import java.net.UnknownHostException import javax.net.ssl.SSLException @@ -78,6 +81,18 @@ sealed interface McpFailure { /** Everything else, including failures that never reached the network. */ data class Failed(val reason: String?) : McpFailure + + /** + * The SQLite debugger of the app [applicationId] did not answer before a socket timeout. Android + * may have paused the app in the background, and a paused app answers nothing. + */ + data class AppNotAnswering(val applicationId: String) : McpFailure + + /** + * Nothing listens on the port stored for the app [applicationId]: its process ended, or it was + * rebuilt without the SQLite debugger. + */ + data class AppNotListening(val applicationId: String) : McpFailure } /** @@ -88,6 +103,9 @@ sealed interface McpFailure { */ object McpErrorFormatter { + /** How far down a cause chain [classify] looks, which also ends a chain that loops. */ + private const val MAX_CAUSES = 8 + /** * Reduces [error] to what the user needs to know. * @param error the failure, from any layer. @@ -109,19 +127,47 @@ object McpErrorFormatter { else -> McpFailure.Failed(error.message) } + /** + * Reduces [error] on [server] to what the user needs to know. As [classify], except on an + * entry built from an app's stored SQLite debugger endpoint, where a socket timeout or a + * refused connection says what to do with that app. + * + * Told apart by exception type, the cause chain included, never by message: Android's + * `HttpURLConnection` writes "failed to connect to ... after 15000ms" for both. + * + * @param error the failure, from any layer. + * @param server the server it came from. + * @return the classification. + */ + fun classify(error: Throwable, server: McpServer): McpFailure { + val failure = classify(error) + if (!server.automatic) return failure + // An HTTP status or a JSON-RPC error is an answer, so the app is running and listening. + if (failure != McpFailure.TimedOut && failure !is McpFailure.Failed) return failure + val applicationId = AutomaticServers.applicationIdOf(server.id) + val cause = generateSequence(error) { it.cause }.take(MAX_CAUSES) + .firstOrNull { it is SocketTimeoutException || it is ConnectException } + return when (cause) { + is SocketTimeoutException -> McpFailure.AppNotAnswering(applicationId) + is ConnectException -> McpFailure.AppNotListening(applicationId) + else -> failure + } + } + /** * The sentence to show for [error]. * @param context this plugin's context, for its own `strings.xml`; null falls back to the * untranslated shape, which beats showing the user nothing. - * @param serverName the server's label, so a user with several knows which one failed. + * @param server the server that failed. Its label names it, so a user with several knows + * which one; the two reasons that say what to do with an app name its application ID. * @param error the failure. * @return one sentence. */ - fun format(context: Context?, serverName: String, error: Throwable): String { - val failure = classify(error) + fun format(context: Context?, server: McpServer, error: Throwable): String { + val serverName = server.name if (context == null) return "$serverName: ${error.message ?: error.javaClass.simpleName}" - return when (failure) { + return when (val failure = classify(error, server)) { McpFailure.BadRequest -> context.getString(R.string.mcp_error_bad_request, serverName) is McpFailure.TokenRefused -> refused(context, serverName, failure.credential) is McpFailure.Forbidden -> forbidden(context, serverName, failure.credential) @@ -148,6 +194,10 @@ object McpErrorFormatter { is McpFailure.Failed -> failure.reason ?.let { context.getString(R.string.mcp_error_failed_reason, serverName, it) } ?: context.getString(R.string.mcp_error_failed, serverName) + is McpFailure.AppNotAnswering -> + context.getString(R.string.mcp_error_app_not_answering, failure.applicationId) + is McpFailure.AppNotListening -> + context.getString(R.string.mcp_error_app_not_listening, failure.applicationId) } } diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormat.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormat.kt index 35404318b..3076aaa88 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormat.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormat.kt @@ -1,5 +1,6 @@ package com.itsaky.androidide.plugins.aiagentmcp.errors +import com.itsaky.androidide.plugins.aiagentmcp.transport.JsonDepth import org.json.JSONArray import org.json.JSONObject @@ -52,15 +53,24 @@ object McpLogFormat { private fun code(status: String): Int? = STATUS_CODE.find(status)?.groupValues?.get(1)?.toInt() - private fun json(text: String): String? { - val indented = runCatching { - when { - text.startsWith("{") -> JSONObject(text).toString(JSON_INDENT) - text.startsWith("[") -> JSONArray(text).toString(JSON_INDENT) - else -> null - } - }.getOrNull() + /** + * [text] as indented JSON, or null when it is not JSON. An Exception or LinkageError from + * [indent] is a body that is not JSON; any other Error, an OutOfMemoryError above all, propagates. + * So would a StackOverflowError, which is why [text] never reaches [indent] when it nests + * deeper than [JsonDepth.MAX], or is not strict JSON and could hide such nesting: it is shown + * as it came. + * @param indent the parsing and indenting; injectable so a test can make it fail. + */ + internal fun json(text: String, indent: (String) -> String? = ::indentJson): String? { + if (JsonDepth.refusal(text) != null) return null + val indented = runCatchingRecoverable { indent(text) }.getOrNull() // org.json escapes every '/', which turns each URL in a reply into noise. return indented?.replace("\\/", "/") } + + private fun indentJson(text: String): String? = when { + text.startsWith("{") -> JSONObject(text).toString(JSON_INDENT) + text.startsWith("[") -> JSONArray(text).toString(JSON_INDENT) + else -> null + } } diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpTranscript.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpTranscript.kt index a65fb649e..fdd852435 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpTranscript.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpTranscript.kt @@ -21,6 +21,9 @@ object McpTranscript { /** The transcript of a failure that never reached the network. */ val nothingSent: String + + /** The note on a request given up before it was sent; see [McpExchange.cancelled]. */ + val cancelled: String } /** @@ -77,13 +80,19 @@ object McpTranscript { exchanges.lastOrNull()?.failure == null && error !is McpHttpException private fun render(exchange: McpExchange, labels: Labels): String = buildList { - add("> ${exchange.method} ${exchange.url}") - addAll(headers(">", exchange.requestHeaders, labels)) - addAll(body(">", exchange.requestBody, labels)) - exchange.status?.let { status -> - add("< $status") - addAll(headers("<", exchange.responseHeaders, labels)) - exchange.responseBody?.let { addAll(body("<", it, labels)) } + if (exchange.cancelled) { + // Nothing of it went over the wire, so no line of it is marked as sent. + add("* ${exchange.method} ${exchange.url}") + add("* ${labels.cancelled}") + } else { + add("> ${exchange.method} ${exchange.url}") + addAll(headers(">", exchange.requestHeaders, labels)) + addAll(body(">", exchange.requestBody, labels)) + exchange.status?.let { status -> + add("< $status") + addAll(headers("<", exchange.responseHeaders, labels)) + exchange.responseBody?.let { addAll(body("<", it, labels)) } + } } exchange.failure?.let { add("* $it") } }.joinToString("\n") diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/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..d9c698ba7 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/Recoverable.kt @@ -0,0 +1,29 @@ +package com.itsaky.androidide.plugins.aiagentmcp.errors + +import kotlin.coroutines.cancellation.CancellationException + +/** + * As [runCatching], but catching only what this plugin can recover from: an [Exception], or a + * [LinkageError], which is how a host whose plugin-api differs from this plugin's fails a call + * (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. + * + * So does a [CancellationException], although it is an Exception: it is how a coroutine learns it + * was cancelled, and a coroutine that kept it as one more failure would carry on with work nobody + * wants. No block passed here suspends today; this keeps the first one that does honest. + * + * @param block the work, usually one that reaches the host directly or through a listener. + * @return its value, or the recoverable failure it threw. + */ +internal inline fun runCatchingRecoverable(block: () -> T): Result = try { + Result.success(block()) +} catch (e: CancellationException) { + throw e +} catch (e: Exception) { + Result.failure(e) +} catch (e: LinkageError) { + 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..2434288e8 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt @@ -1,10 +1,16 @@ package com.itsaky.androidide.plugins.aiagentmcp.plugin +import android.util.Log +import androidx.annotation.VisibleForTesting import com.itsaky.androidide.plugins.IPlugin import com.itsaky.androidide.plugins.PluginContext import com.itsaky.androidide.plugins.PluginLifecycleListener 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 +21,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,30 +37,54 @@ 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 { private lateinit var context: PluginContext + + /** + * The tool source registered with AI Core: built by the first [activate], kept by a second, and + * closed and cleared by [teardown]. Read and written only under [lifecycleLock]. + */ private var toolSource: McpToolSource? = null /** True once [toolSource] is registered with AI Core, so re-registration is idempotent. */ @Volatile private var registered = false /** - * Serialises every swap of [scope]. + * Serialises the lifecycle transitions: [activate], [deactivate] and [dispose], [teardown] which + * they share, and the registration AI Core's activation triggers. Each runs whole before the next + * starts, since the host may drive one from one thread and the next from another. + * + * Without it, a teardown could fall inside an activation: between its read of [toolSource] and + * its write, putting back a source the teardown had just closed, or after the registration had + * started and before [registered] was set, so the teardown unregistered nothing and closed the + * source AI Core was being handed. AI Core then held a closed source, whose every call fails + * with a RejectedExecutionException. Every swap of [scope] takes it too: cancelling the old + * scope and installing a new one is one transition, not two. + * + * Nothing taken under it waits for this plugin's own work or for the network: the host's + * listener and service registries do not call back, the coroutines it cancels never take it, + * and [teardown] only takes the sessions out, into its caller's list. The lifecycle call that + * ran it ends them once it has let go ([endSessions]): a session's `close()` sends a DELETE + * and can first wait, up to about 70 s, for a handshake in flight to let go of the session, and a + * lifecycle call or AI Core's registration arriving meanwhile must not wait behind it. Each + * call ends only the sessions its own teardown took out, so one arriving meanwhile neither + * ends another's nor waits for them. * - * Cancelling the old scope and installing a new one is one transition, not two: without this, - * two lifecycle calls landing together can each cancel the scope the other has already replaced, - * leaving a live refresh behind after [deactivate] or orphaning an activation's scope uncancelled. - * `@Volatile` alone would publish each write but still let the pair interleave. + * Internal for the test that holds it while a lifecycle call runs. */ - private val lifecycleLock = Any() + @VisibleForTesting + internal val lifecycleLock = Any() /** * Background work: listing tools is network work and never belongs on the main thread. @@ -115,6 +147,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 @@ -128,7 +175,9 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { */ private val aiCoreLifecycle = object : PluginLifecycleListener { override fun onPluginActivated(pluginId: String) { - if (pluginId == AI_CORE_PLUGIN_ID) registerToolSource() + // Under the lifecycle lock, so a deactivation arriving meanwhile undoes this + // registration rather than closing the source while AI Core is handed it. + if (pluginId == AI_CORE_PLUGIN_ID) synchronized(lifecycleLock) { registerToolSource() } } override fun onPluginDeactivated(pluginId: String) { @@ -141,9 +190,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 +215,30 @@ 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. Registered by [activate] beside the + * change listeners, and removed with them. The activation's own install of the endpoints tells + * it nothing (see [AutomaticServers.install]): the `refreshAll` that follows lists those entries. + */ + private val relistAutomatic: (String) -> Unit = { id -> + scope.launch { + 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 @@ -166,16 +246,45 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension { return true } - override fun activate(): Boolean = try { + override fun activate(): Boolean { + val released = mutableListOf() + try { + return synchronized(lifecycleLock) { activateLocked(released) } + } finally { + // A failed activation tears down what it started, sessions included. + endSessions(released) + } + } + + /** + * [activate] itself, under [lifecycleLock]. + * @param released receives the sessions a failed one's teardown took out, to end. + * @return whether it worked. + */ + private fun activateLocked(released: MutableList): Boolean = try { // Cancelled and replaced as one step: a host that activates twice would otherwise orphan // the running scope, and the launch below has to use this activation's scope, not whatever // a concurrent lifecycle call has since installed. val active = swapScope(newScope()) activationJob = active.coroutineContext[Job] - toolSource = McpToolSource() + // Kept by a second activate: it is the one registered with AI Core, whose registry + // unregisters by identity, and [registered] is already true, so a replacement would never be + // registered while this one stayed registered and was never closed. [teardown] closes it and + // clears the field, so the activation after a deactivate builds a fresh one. + toolSource = toolSource ?: McpToolSource() + // Here, not on the coroutine below: a lifecycle call registers and removes every listener, + // so a late coroutine of an activation that has ended cannot add one, or remove the next + // activation's. The add methods ignore a listener already registered, so a host that + // activates twice still registers each once. McpServerStore.addChangeListener(settingsChanged) + AutomaticServers.addChangeListener(settingsChanged) + AutomaticServers.addEndpointListener(relistAutomatic) McpServerHealth.addChangeListener(healthChanged) - context.addPluginLifecycleListener(aiCoreLifecycle) + // Guarded like the removal in teardown: a host whose plugin-api differs answers with a + // LinkageError. That costs only the re-registration when AI Core activates later; with AI + // Core already active, the registration below still works. + runCatchingRecoverable { context.addPluginLifecycleListener(aiCoreLifecycle) } + .onFailure { e -> context.logger.warn("McpPlugin: could not add the lifecycle listener", e) } if (!registerToolSource()) { context.logger.info("McpPlugin: AI Core is not active yet; will register when it is") @@ -184,40 +293,104 @@ 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) { - context.logger.error("McpPlugin: activation failed", e) + activationFailed(e, released) + false + } catch (e: LinkageError) { + // A host call outside the guards above, from a host whose plugin-api differs. + activationFailed(e, released) false } - override fun deactivate(): Boolean = try { - context.removePluginLifecycleListener(aiCoreLifecycle) - McpServerStore.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() - releaseConnections() - true - } catch (e: Exception) { - context.logger.error("McpPlugin: deactivation failed", e) - false + /** + * Undoes a failed [activate] and logs why. + * + * The host need not call [deactivate] after an activation that failed, so nothing else would + * stop the scope it had started or remove the listeners it had registered by then. + * + * @param e what ended the activation. + * @param released receives the sessions the teardown took out, for [activate] to end. + */ + private fun activationFailed(e: Throwable, released: MutableList) { + teardown(released) + runCatchingRecoverable { context.logger.error("McpPlugin: activation failed", e) } + } + + override fun deactivate(): Boolean { + val released = mutableListOf() + try { + return synchronized(lifecycleLock) { + try { + teardown(released) + true + } catch (e: Exception) { + context.logger.error("McpPlugin: deactivation failed", e) + false + } + } + } finally { + // The sessions taken out before a step of the teardown failed, too. + endSessions(released) + } } override fun dispose() { - runCatching { context.removePluginLifecycleListener(aiCoreLifecycle) } + val released = mutableListOf() + try { + synchronized(lifecycleLock) { teardown(released) } + } finally { + // Before the context goes: a session's DELETE reads its credentials through it. Both + // whatever the teardown threw, the sessions it took out by then included. + try { + endSessions(released) + } finally { + pluginContext = null + } + } + context.logger.info("McpPlugin: disposed") + } + + /** + * Ends [released], each with a DELETE, best effort: the sessions the calling lifecycle call's + * own [teardown] took out, never another's. Called once that call has let go of + * [lifecycleLock], never under it; see there. + */ + private fun endSessions(released: List) = McpConnections.endAll(released) + + /** + * Stops what [activate] started: the lifecycle and change listeners, the tool source's + * registration, the scope with its work, and the connections. The one teardown path, shared by + * [deactivate], [dispose] and a failed [activate], so the three cannot drift apart. Safe to run + * on an activation that got only part of the way, and on none at all. Each caller holds + * [lifecycleLock]; taken here too, so a new caller cannot forget it. The sessions are only taken + * out here; the lifecycle call ends them after it has let go ([endSessions]). + * + * @param released receives the sessions taken out, each with the credentials read as it was + * taken out, for the caller alone to end. Filled as they are taken out, so the caller still + * has them when a later step throws. + */ + private fun teardown(released: MutableList) = synchronized(lifecycleLock) { + // Guarded: a host whose plugin-api differs answers with a LinkageError, and one escaping + // here would skip every step below, leaving the scope and its probe running. + runCatchingRecoverable { context.removePluginLifecycleListener(aiCoreLifecycle) } + .onFailure { e -> context.logger.warn("McpPlugin: could not remove the lifecycle listener", e) } McpServerStore.removeChangeListener(settingsChanged) + AutomaticServers.removeChangeListener(settingsChanged) + AutomaticServers.removeEndpointListener(relistAutomatic) McpServerHealth.removeChangeListener(healthChanged) unregisterToolSource() + // Before the connections are closed: an in-flight refresh would otherwise repopulate the + // catalogue and the session map straight after they were cleared. stopScope() - releaseConnections() - pluginContext = null - context.logger.info("McpPlugin: disposed") + releaseConnections(released) } /** @@ -230,14 +403,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 +427,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 +437,51 @@ 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, unless the activation ends first. + * + * The host's database read blocks and cancellation cannot interrupt it, so [keepGoing] is + * consulted before it and, inside [AutomaticServers.install], after it. No listener is added + * or removed here: [activate] registers [relistAutomatic] and [deactivate] removes it, so this + * call, which can outlive its activation, cannot touch the listener a later activation relies on. + * + * @param keepGoing false once this activation is over. + */ + internal fun startDebuggerEntry(keepGoing: () -> Boolean) { + if (!keepGoing()) return + installDebuggerEndpoints(keepGoing) + } + + /** + * 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 +532,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,44 +549,61 @@ 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 } - /** Closes every session and forgets the cached tool lists. */ - private fun releaseConnections() { + /** + * Closes the tool source, takes every session out, and forgets the cached tool lists. Under + * [lifecycleLock], with [teardown]. + * + * @param released receives the sessions taken out, for the lifecycle call to end + * ([endSessions]), before the steps after it run: one of those throwing must not lose them, + * or they would never get their DELETE. + */ + private fun releaseConnections(released: MutableList) { toolSource?.close() toolSource = null - McpConnections.closeAll() + // Before the entries are cleared below: each session's credentials are read as it is taken + // out, and a SQLite debugger entry's token leaves with its entry. + McpConnections.detachAll(released) 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 +644,14 @@ 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. For those four, you can choose + Always Allow, which lasts for the rest of the chat (needs AI Core 3.6.0 or + later). """.trimIndent(), buttons = listOf( PluginTooltipButton( diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpConnectionLogView.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpConnectionLogView.kt index 6a2461e65..35cf5a1e8 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpConnectionLogView.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpConnectionLogView.kt @@ -59,12 +59,17 @@ class McpConnectionLogView( val context = card.context card.findViewById(R.id.mcpLogMethod).text = exchange.method card.findViewById(R.id.mcpLogUrl).text = exchange.url - status(card.findViewById(R.id.mcpLogStatus), exchange.status) + status(card.findViewById(R.id.mcpLogStatus), exchange) val sections = card.findViewById(R.id.mcpLogSections) - sections.addView(text(context, context.getString(R.string.mcp_log_request), Role.SECTION)) - addHeaders(sections, exchange.requestHeaders) - addBody(sections, exchange.requestBody) + if (exchange.cancelled) { + // Never sent, so no request is shown as if it had been. + sections.addView(text(context, labels.cancelled, Role.NOTE)) + } else { + sections.addView(text(context, context.getString(R.string.mcp_log_request), Role.SECTION)) + addHeaders(sections, exchange.requestHeaders) + addBody(sections, exchange.requestBody) + } if (exchange.status != null) { sections.addView(text(context, context.getString(R.string.mcp_log_response), Role.SECTION)) addHeaders(sections, exchange.responseHeaders) @@ -74,15 +79,23 @@ class McpConnectionLogView( return card } - private fun status(badge: TextView, status: String?) { + private fun status(badge: TextView, exchange: McpExchange) { val context = badge.context - val (container, content) = when (McpLogFormat.tone(status)) { - McpLogFormat.Tone.SUCCESS -> R.color.plugin_success_container to R.color.plugin_success - McpLogFormat.Tone.REDIRECT -> - R.color.plugin_secondary_container to R.color.plugin_on_secondary_container - McpLogFormat.Tone.ERROR -> R.color.plugin_error_container to R.color.plugin_on_error_container + val status = exchange.status + val (container, content) = when { + // A cancel is the caller's doing, not the server failing. + exchange.cancelled -> R.color.plugin_secondary_container to R.color.plugin_on_secondary_container + else -> when (McpLogFormat.tone(status)) { + McpLogFormat.Tone.SUCCESS -> R.color.plugin_success_container to R.color.plugin_success + McpLogFormat.Tone.REDIRECT -> + R.color.plugin_secondary_container to R.color.plugin_on_secondary_container + McpLogFormat.Tone.ERROR -> R.color.plugin_error_container to R.color.plugin_on_error_container + } + } + badge.text = when { + exchange.cancelled -> context.getString(R.string.mcp_log_cancelled) + else -> status?.let(McpLogFormat::badge) ?: context.getString(R.string.mcp_log_no_response) } - badge.text = status?.let(McpLogFormat::badge) ?: context.getString(R.string.mcp_log_no_response) badge.backgroundTintList = ColorStateList.valueOf(color(context, container)) badge.setTextColor(color(context, content)) } diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/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..e648bebb7 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStore.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStore.kt @@ -11,6 +11,7 @@ import com.itsaky.androidide.plugins.aiagentmcp.transport.McpHeaders import com.itsaky.androidide.plugins.security.KeystoreSecretStore import java.util.UUID import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.atomic.AtomicReference import org.json.JSONArray import org.json.JSONObject @@ -40,6 +41,22 @@ object McpServerStore { private val listeners = CopyOnWriteArrayList<() -> Unit>() + /** + * The server list as last read or written, with the preferences it belongs to. + * + * The check that a server is still configured (`McpServers.isConfigured`) runs under the health, + * catalog and session locks, and a SQLite debugger entry's refresh waits on two of them while it + * holds its own. Read from the preferences, that check parsed every server's JSON under them; + * answered from here, it reads nothing and parses nothing. + * + * Every write puts the list it wrote here. A read puts what it read only by compare-and-set + * against what it saw first, so a read that raced a write never puts the older list back. Kept + * with the preferences it came from: a plugin initialized again reads its own afresh. + */ + private class Snapshot(val prefs: SharedPreferences, val servers: List) + + private val snapshot = AtomicReference(null) + /** * Serialises every read-modify-write of the server list. * @@ -49,9 +66,33 @@ object McpServerStore { */ private val lock = Any() - /** Registers [listener], called after any change to the servers or their toggles. */ + /** + * Held while a server's URL, token or headers are written, and while a request reads its + * credentials together with the URL they are for ([readTogether]). A reader then finds the URL + * with the credentials saved with it, never the new URL with the old token or the old URL with + * the new: a save writes the three one after another, and a request reading between two of + * those writes paired one server's URL with another's credentials. + * + * Its own lock, not [lock] and not `McpConnections`': it is held across Keystore work, which + * nothing waiting for the server list or the session map should sit behind. Taken before + * [lock], never inside it. Nothing runs under it but this store's own reads and writes, the + * Keystore's among them, never a listener. + */ + private val credentialsLock = Any() + + /** + * Runs [read] holding [credentialsLock]: what it reads of one server's URL, token and headers + * was saved together. For a request's credentials, read with the URL they go to. + */ + internal fun readTogether(read: () -> T): T = synchronized(credentialsLock, read) + + /** + * Registers [listener], called after any change to the servers or their toggles. Adding one + * already registered does nothing, so a host that activates the plugin twice still gets one + * call per change, and one [removeChangeListener] takes it out. + */ fun addChangeListener(listener: () -> Unit) { - listeners.add(listener) + listeners.addIfAbsent(listener) } /** Removes a listener added by [addChangeListener]. */ @@ -59,23 +100,36 @@ object McpServerStore { listeners.remove(listener) } + /** How many change listeners are registered; a test seam for a listener registered twice. */ + internal val changeListenerCount: Int get() = listeners.size + /** * Every configured server, in the order they were added. * @return the servers; empty before any is configured, or when the stored blob is unreadable. */ fun servers(): List { - val raw = prefs()?.getString(KEY_SERVERS, null) ?: return emptyList() + val prefs = prefs() ?: return emptyList() + val seen = snapshot.get() + if (seen != null && seen.prefs === prefs) return seen.servers + val read = parse(prefs.getString(KEY_SERVERS, null)) + snapshot.compareAndSet(seen, Snapshot(prefs, read)) + return read + } + + /** The stored list in [raw], empty when there is none or it is unreadable. */ + private fun parse(raw: String?): List { + if (raw == null) return emptyList() return try { - val array = JSONArray(raw) - (0 until array.length()).mapNotNull { index -> - array.optJSONObject(index)?.let(::toServer) - } + fromJson(JSONArray(raw)) } catch (e: Exception) { Log.e(TAG, "Stored server list is unreadable; treating it as empty", e) emptyList() } } + private fun fromJson(array: JSONArray): List = + (0 until array.length()).mapNotNull { index -> array.optJSONObject(index)?.let(::toServer) } + /** * Stores the two fields the add/edit dialog owns, leaving every other field as stored. * @@ -87,14 +141,107 @@ object McpServerStore { * @return the record as it now stands, for a caller holding a snapshot to refresh from. */ fun saveDetails(server: McpServer): McpServer { - val merged = synchronized(lock) { - mergeDetails(servers().firstOrNull { it.id == server.id }, server) - .also(::upsertLocked) - } + val merged = synchronized(credentialsLock) { saveDetailsLocked(server) } fireChanged() return merged } + /** [saveDetails] without telling the listeners. Call holding [credentialsLock]. */ + private fun saveDetailsLocked(server: McpServer): McpServer = synchronized(lock) { + mergeDetails(servers().firstOrNull { it.id == server.id }, server).also(::upsertLocked) + } + + /** + * What [saveConnection] stored. + * @property server the record as it now stands, for a caller holding a snapshot to refresh + * from. + * @property tokenStored false when a token was given and could not be stored. + * @property headersStored false when headers were given and could not be stored. + */ + data class SavedConnection( + val server: McpServer, + val tokenStored: Boolean, + val headersStored: Boolean, + ) + + /** + * Stores what the add/edit dialog owns: the name and URL, as [saveDetails] does, and when given + * the token and the headers. All in one step under [credentialsLock], so a request reading its + * credentials ([readTogether]) finds the old URL with the old ones or the new URL with the new, + * never one with the other. The listeners are told once, after. + * + * When the URL changes and a token or headers write fails, the old value is still stored, and + * the new URL must not get it: it is forgotten in the same step. If forgetting it fails too, + * the URL is put back instead, so the old credential stays with the URL it was entered for; + * the returned record then carries the old URL. Either way the failure is reported in the + * result, and the user enters the credential again. + * + * A null [token] or [headers] keeps the stored value, also when the URL changes: the new URL + * is then sent that stored credential, on purpose. Pass blank or empty to forget it. + * + * Keystore work, so call this off the main thread. + * + * @param server the candidate, carrying the id plus the edited name and URL. + * @param token the token to store, blank to forget it, or null to keep the stored one. + * @param headers the headers to store, replacing the stored ones, empty to forget them, or null + * to keep them. + * @return the record as it now stands, and which credentials could not be stored. + */ + fun saveConnection( + server: McpServer, + token: String?, + headers: Map?, + ): SavedConnection { + val saved = synchronized(credentialsLock) { + val before = server(server.id) + var merged = saveDetailsLocked(server) + val tokenStored = token?.let { writeToken(server.id, it) } ?: true + val headersStored = headers?.let { writeHeaders(server.id, it) } ?: true + if (before != null && before.url != merged.url && !(tokenStored && headersStored)) { + // A write that failed left the old value stored, and the URL has moved: the new + // URL must not get what was entered for the old one. Forget it, still under the + // lock, so no request reads the pair between the writes. + var forgotten = true + if (!tokenStored) forgotten = writeToken(server.id, "") && forgotten + if (!headersStored) forgotten = writeHeaders(server.id, emptyMap()) && forgotten + if (!forgotten) { + // Forgetting failed too, so the old credential is still stored: put the URL + // back, which is the one it belongs to. The user's other edits are kept. + // Re-read the record: a toggle made during the Keystore writes lives only + // there, and restoring the older snapshot would undo it. + merged = synchronized(lock) { + val current = servers().firstOrNull { it.id == server.id } + if (current == null) merged + else current.copy(url = before.url).also(::upsertLocked) + } + } + } + SavedConnection(merged, tokenStored, headersStored) + } + fireChanged() + return saved + } + + /** + * Forgets a server's token and every extra header, in one step under [credentialsLock]. + * + * Keystore work, so call this off the main thread. + * + * @param id the server. + * @return true when neither is stored any more. + */ + fun clearCredentials(id: String): Boolean { + val cleared = synchronized(credentialsLock) { + // Both, whatever the first returned: a token left behind is no reason to keep the + // headers. + val token = writeToken(id, "") + val headers = writeHeaders(id, emptyMap()) + token && headers + } + fireChanged() + return cleared + } + /** * Merges a dialog's edits onto the stored record. * @@ -149,33 +296,34 @@ object McpServerStore { * @param id the server to remove. */ fun remove(id: String) { - synchronized(lock) { - prefs()?.edit() - ?.remove(KEY_TOKEN_PREFIX + id) - ?.remove(KEY_HEADERS_PREFIX + id) - ?.apply() - writeLocked(servers().filterNot { it.id == id }) + // The credentials lock too, like every write of a URL or a credential. + synchronized(credentialsLock) { + synchronized(lock) { + prefs()?.edit() + ?.remove(KEY_TOKEN_PREFIX + id) + ?.remove(KEY_HEADERS_PREFIX + id) + ?.apply() + writeLocked(servers().filterNot { it.id == id }) + } } fireChanged() } /** - * Stores a server's bearer token, encrypted; blank forgets it. + * Stores a server's bearer token, encrypted; blank forgets it. Call holding [credentialsLock], + * through [saveConnection] or [clearCredentials], which tell the listeners: a new credential + * has to reach the agent, or it keeps calling with the old one until something else happens to + * touch the store. * - * Keystore work, so call this off the main thread. + * Internal for the tests, which have no Keystore to write to. * * @param id the server the token belongs to. * @param token the token, or blank to remove it. * @return true once it is on disk, or removed for a blank one; false when encrypting it or the * write itself failed, which is what the pane must not report as saved. */ - fun setToken(id: String, token: String): Boolean { - val stored = secureTokenStore.write(prefs(), KEY_TOKEN_PREFIX + id, token) - // Like every other mutator: a new credential has to reach the agent, or it keeps calling - // with the old one until something else happens to touch the store. - fireChanged() - return stored - } + internal fun writeToken(id: String, token: String): Boolean = + secureTokenStore.write(prefs(), KEY_TOKEN_PREFIX + id, token) /** * Reads a server's bearer token. @@ -228,9 +376,8 @@ object McpServerStore { } /** - * Stores a server's extra headers, encrypted; an empty map forgets them. - * - * Keystore work, so call this off the main thread. + * Stores a server's extra headers, encrypted; an empty map forgets them. Call holding + * [credentialsLock], as for [writeToken]. * * @param id the server the headers belong to. * @param headers the headers to store; unusable pairs are dropped. @@ -238,7 +385,7 @@ object McpServerStore { * or the write itself failed. Forgetting them on a store that was never opened is success: * there is nothing on disk to remove. */ - fun setHeaders(id: String, headers: Map): Boolean { + internal fun writeHeaders(id: String, headers: Map): Boolean { val clean = McpHeaders.sanitize(headers) val key = KEY_HEADERS_PREFIX + id // The empty map goes through write() as a blank, which removes the entry, rather than @@ -254,9 +401,7 @@ object McpServerStore { // A clear with no preferences behind it has nothing to remove, so it succeeded; only a // write with something to store has genuinely failed. val prefs = prefs() ?: return clean.isEmpty() - val stored = secureTokenStore.write(prefs, key, payload) - fireChanged() - return stored + return secureTokenStore.write(prefs, key, payload) } /** Whether any extra header is configured for [id], without decrypting them. */ @@ -264,12 +409,16 @@ object McpServerStore { /** * Records the tools a server advertised, dropping toggles for tools it no longer has. + * Does nothing when the server's URL is no longer the one the listing used: that list belongs + * to the old endpoint, and applying it would drop the toggles of tools the new one may have. * @param id the server. + * @param listedUrl the URL the tools were listed from. * @param toolNames the tools it just listed. */ - fun setKnownTools(id: String, toolNames: List) { + fun setKnownTools(id: String, listedUrl: String, toolNames: List) { synchronized(lock) { val server = servers().firstOrNull { it.id == id } ?: return + if (server.url != listedUrl) return val updated = server.copy( knownTools = toolNames, enabledTools = server.enabledTools.filterTo(mutableSetOf()) { it in toolNames }, @@ -306,7 +455,10 @@ object McpServerStore { private fun writeLocked(servers: List) { val array = JSONArray() servers.forEach { array.put(toJson(it)) } - prefs()?.edit()?.putString(KEY_SERVERS, array.toString())?.apply() + val prefs = prefs() ?: return + prefs.edit().putString(KEY_SERVERS, array.toString()).apply() + // As a read would give it back, a blank name already filled in from the URL. + snapshot.set(Snapshot(prefs, fromJson(array))) } private fun toJson(server: McpServer): JSONObject = JSONObject().apply { @@ -338,11 +490,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/settings/McpSettingsViewModel.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt index 45e8d164f..df01a9433 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsViewModel.kt @@ -95,37 +95,50 @@ class McpSettingsViewModel( */ fun loadForm(id: String, onLoaded: (FormState) -> Unit) { viewModelScope.launch { - val state = withContext(Dispatchers.IO) { - val token = McpServerStore.token(id) - var headersUnreadable = false - var headersUnavailable = false - val headers = try { - McpServerStore.headers(id) - } catch (e: UnreadableSecretException) { - headersUnreadable = true - null - } catch (e: UnavailableSecretException) { - headersUnavailable = true - null - } - // Reported per credential, never folded together: a token that decrypts beside - // headers that do not must not put "could not be read" on the token's own field, - // which is the mis-attribution this pane exists to avoid. - FormState( - hasToken = McpServerStore.hasToken(id), - hasHeaders = McpServerStore.hasHeaders(id), - tokenUnreadable = token is KeystoreSecretStore.Stored.Unreadable, - tokenUnavailable = token is KeystoreSecretStore.Stored.Unavailable, - headersKnown = headers != null, - headersUnreadable = headersUnreadable, - headersUnavailable = headersUnavailable, - headers = headers.orEmpty(), - ) - } + val state = withContext(Dispatchers.IO) { loadFormNow(id) } onLoaded(state) } } + /** + * [loadForm]'s blocking part, off the main thread. + * + * The token, the headers and whether each is stored are read in one [McpServerStore.readTogether], + * the lock a save writes them under: read one at a time, a save landing between them showed a + * token from after the save beside headers from before it. + * + * Accepted limit: that is the store's one global credentials lock, held across the Keystore + * decrypts of this load. A save of any server waits for a load, and a request's credential read + * waits for it too. Both are two decrypts long, the same window the saves already hold. + */ + internal fun loadFormNow(id: String): FormState = McpServerStore.readTogether { + val token = McpServerStore.token(id) + var headersUnreadable = false + var headersUnavailable = false + val headers = try { + McpServerStore.headers(id) + } catch (e: UnreadableSecretException) { + headersUnreadable = true + null + } catch (e: UnavailableSecretException) { + headersUnavailable = true + null + } + // Reported per credential, never folded together: a token that decrypts beside + // headers that do not must not put "could not be read" on the token's own field, + // which is the mis-attribution this pane exists to avoid. + FormState( + hasToken = McpServerStore.hasToken(id), + hasHeaders = McpServerStore.hasHeaders(id), + tokenUnreadable = token is KeystoreSecretStore.Stored.Unreadable, + tokenUnavailable = token is KeystoreSecretStore.Stored.Unavailable, + headersKnown = headers != null, + headersUnreadable = headersUnreadable, + headersUnavailable = headersUnavailable, + headers = headers.orEmpty(), + ) + } + /** * What an empty token field means when saving: leave whatever is stored alone. * @param typed the current contents of the token field. @@ -137,10 +150,10 @@ class McpSettingsViewModel( * What the header rows mean when saving, given whether the stored ones could be read. * * The token's rule, applied to headers: the rows replace what is stored only when the dialog - * drew what is stored. Otherwise they mean nothing about it — [setHeaders] replaces the whole - * map, so writing one typed row over a set nobody could read would delete headers the user was - * just told were intact. The dialog refuses such a save instead, and [clearCredential] is the - * way back to none. + * drew what is stored. Otherwise they mean nothing about it — [McpServerStore.saveConnection] + * replaces the whole map, so writing one typed row over a set nobody could read would delete + * headers the user was just told were intact. The dialog refuses such a save instead, and + * [clearCredential] is the way back to none. * * @param collected the header rows as they currently stand. * @param headersKnown whether those rows reflect what is stored. @@ -168,25 +181,57 @@ class McpSettingsViewModel( onDone: (McpServer, String?) -> Unit, ) { viewModelScope.launch { - val outcome = withContext(Dispatchers.IO) { - val merged = McpServerStore.saveDetails(server) - val tokenStored = token?.let { McpServerStore.setToken(server.id, it.trim()) } ?: true - val headersStored = headers?.let { McpServerStore.setHeaders(server.id, it) } ?: true - // A credential change has to invalidate the session, or the old one keeps working. - McpConnections.invalidate(server.id) - McpServerHealth.credentialChanged(server.id) - val failure = when { - !tokenStored -> string(R.string.mcp_token_save_failed) - !headersStored -> string(R.string.mcp_headers_save_failed) - else -> null - } - merged to failure - } + val outcome = withContext(Dispatchers.IO) { saveNow(server, token, headers) } reload() onDone(outcome.first, outcome.second) } } + /** + * [save]'s blocking part, off the main thread. + * + * A credential or URL change has to end the session, or the old one keeps working. It is taken + * out first, its credentials read while the store still holds the URL it was built for; then + * the URL, token and headers are written in one step that a request's credential read waits + * for; then it is ended, outside every lock. So its DELETE carries the old credentials, which a + * server that wants its token to end a session needs, and only to the old URL: the old token + * never reaches the new URL, nor the new token the old. A call that looks the session up in + * between stores one for the old URL, which the next lookup replaces; it ends with no + * credentials, since the server no longer points there. A token or headers write that fails + * while the URL changes forgets the old value in that step (or keeps the old URL, when + * forgetting fails too), so the new URL is never sent the old credential. + * + * One limit, on purpose: a null [token] means "keep the stored one", so a URL change with the + * token field left blank sends the stored token to the new URL. [clearCredentialNow] is the way + * to a URL with no token. + * + * The session is ended even when the save throws: it is out of the map by then, so nothing else + * would end it. The exception then propagates, and the health row is left as it was. + * + * @return the merged record and a status sentence, null when everything worked. + */ + internal fun saveNow( + server: McpServer, + token: String?, + headers: Map?, + ): Pair { + val released = McpConnections.detach(server.id) + val saved = try { + McpServerStore.saveConnection(server, token?.trim(), headers) + } finally { + // Also when the save throws: the session is out of the map, so nothing else would end + // it, and it would stay open on the server. + released?.close() + } + McpServerHealth.credentialChanged(server.id) + val failure = when { + !saved.tokenStored -> string(R.string.mcp_token_save_failed) + !saved.headersStored -> string(R.string.mcp_headers_save_failed) + else -> null + } + return saved.server to failure + } + /** * Forgets a server's stored credential: the token and every extra header. * @@ -199,34 +244,64 @@ class McpSettingsViewModel( */ fun clearCredential(id: String, onDone: (Boolean) -> Unit) { viewModelScope.launch { - val cleared = withContext(Dispatchers.IO) { - val tokenCleared = McpServerStore.setToken(id, "") - val headersCleared = McpServerStore.setHeaders(id, emptyMap()) - // The session was keyed by the credential it no longer has. - McpConnections.invalidate(id) - McpServerHealth.credentialChanged(id) - tokenCleared && headersCleared - } + val cleared = withContext(Dispatchers.IO) { clearCredentialNow(id) } onDone(cleared) } } + /** + * [clearCredential]'s blocking part, off the main thread. The session was keyed by the + * credential it no longer has, so it is ended, in [saveNow]'s order: taken out with the + * credentials it had, so its DELETE carries them, ended once they are cleared, or once clearing + * throws. + * + * @return true when nothing is stored any more. + */ + internal fun clearCredentialNow(id: String): Boolean { + val released = McpConnections.detach(id) + val cleared = try { + McpServerStore.clearCredentials(id) + } finally { + // Also when clearing throws, as in [saveNow]: the session is already out of the map. + released?.close() + } + McpServerHealth.credentialChanged(id) + return cleared + } + /** * Removes a server, its token, its session and its cached tools. * @param id the server to remove. */ fun delete(id: String) { viewModelScope.launch { - withContext(Dispatchers.IO) { - McpConnections.invalidate(id) - // Removed first, so a probe finishing in between sees it gone and records nothing. - McpServerStore.remove(id) - McpToolCatalog.forget(id) - } + withContext(Dispatchers.IO) { deleteNow(id) } reload() } } + /** + * [delete]'s blocking part, off the main thread. + * + * The session is ended before the server is removed, so its DELETE still has the credentials + * the removal deletes. A call or a listing that looked the session up between the two stored + * a new one, which would outlive the server; it is ended again once the server is gone, when + * no lookup stores one any more (McpConnections.withSession keeps none for a server no longer + * configured). That second DELETE carries the credentials read before the server was removed, + * whether or not there was a first session, best effort; only to a session built for the URL + * they were read for, so none to a session for a URL the server has left. + */ + internal fun deleteNow(id: String) { + // Read while the server is still stored: removing it deletes them. + val saved = McpConnections.saveCredentials(id) + McpConnections.detach(id)?.close() + // Removed before the tools are forgotten, so a probe finishing in between sees it gone and + // records nothing. + McpServerStore.remove(id) + McpConnections.detach(id)?.close(saved) + McpToolCatalog.forget(id) + } + /** * Switches a whole server on or off. * @param id the server. @@ -287,7 +362,7 @@ class McpSettingsViewModel( val context = getContext()?.androidContext // The cached tools: a failed reconnect must not blank out the switches. ConnectResult( - message = McpErrorFormatter.format(context, server.name, e), + message = McpErrorFormatter.format(context, server, e), log = McpTranscript.log( exchanges.snapshot(), e, McpTranscriptStrings(context), exchanges::redact, ), diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpTranscriptDialog.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpTranscriptDialog.kt index 7382a246a..7f0818c87 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpTranscriptDialog.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpTranscriptDialog.kt @@ -11,6 +11,7 @@ import androidx.core.content.ContextCompat import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.itsaky.androidide.plugins.aiagentmcp.R import com.itsaky.androidide.plugins.aiagentmcp.errors.McpTranscript +import com.itsaky.androidide.plugins.aiagentmcp.errors.runCatchingRecoverable import kotlin.time.Duration.Companion.seconds import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job @@ -67,7 +68,7 @@ object McpTranscriptDialog { val label = pluginContext.getString(R.string.mcp_transcript_title) val clipboard = context.getSystemService(ClipboardManager::class.java) ?: return // On the main thread: a short binder call, and the clipboard service is Looper-bound on old APIs. - if (runCatching { clipboard.setPrimaryClip(ClipData.newPlainText(label, text)) }.isFailure) return + if (runCatchingRecoverable { clipboard.setPrimaryClip(ClipData.newPlainText(label, text)) }.isFailure) return button.isEnabled = false button.text = pluginContext.getString(R.string.mcp_transcript_copied) // Not restored on cancellation: that only comes with the dialog or its view going. diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpTranscriptStrings.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpTranscriptStrings.kt index c8bb96cd9..eabbe63bc 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpTranscriptStrings.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpTranscriptStrings.kt @@ -16,6 +16,8 @@ class McpTranscriptStrings(private val context: Context?) : McpTranscript.Labels override val nothingSent: String get() = string(R.string.mcp_transcript_nothing_sent) + override val cancelled: String get() = string(R.string.mcp_transcript_cancelled) + private fun string(resId: Int, vararg args: Any): String = context?.getString(resId, *args).orEmpty() } diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpServerHealth.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpServerHealth.kt index 168722041..3ee4639b5 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpServerHealth.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpServerHealth.kt @@ -29,6 +29,19 @@ object McpServerHealth { private val byServer = ConcurrentHashMap() private val listeners = CopyOnWriteArrayList<() -> Unit>() + /** + * Taken by every removal ([detach], [forget], [clear]), and by a write made only while its + * server is configured, around the check and the write together. A removal landing between the + * two would otherwise be undone by the write, bringing back the row of a server that is gone. A + * removal takes its server out of the list first and forgets its row after, so under this lock + * either the write comes first and the removal takes its row, or the check sees the server gone. + * Nothing is called under it but that check, and never a listener. + */ + private val lock = Any() + + /** Writes a row whatever the list holds; the default of every `configured` below. */ + private val always: (String) -> Boolean = { true } + /** * @param serverId the server. * @return what is known of it, or null before it was ever asked. @@ -38,9 +51,15 @@ object McpServerHealth { /** * Records a first attempt under way. Only for a server with no answer yet: a re-probe of a * known server keeps its last answer until the new one lands, so the tag does not flicker. + * + * @param configured whether [serverId] is still configured; checked with the write, under the + * lock a removal takes, and false skips the write. */ - fun connectingIfUnknown(serverId: String) { - if (byServer.putIfAbsent(serverId, Health(State.CONNECTING)) == null) fireChanged() + fun connectingIfUnknown(serverId: String, configured: (String) -> Boolean = always) { + val added = synchronized(lock) { + configured(serverId) && byServer.putIfAbsent(serverId, Health(State.CONNECTING)) == null + } + if (added) fireChanged() } /** @@ -51,37 +70,65 @@ object McpServerHealth { if (byServer.remove(serverId, Health(State.CONNECTING))) fireChanged() } - /** Records that the server answered. */ - fun available(serverId: String) = set(serverId, Health(State.AVAILABLE)) + /** + * Records that the server answered. + * @param configured as for [connectingIfUnknown]. + */ + fun available(serverId: String, configured: (String) -> Boolean = always) = + set(serverId, Health(State.AVAILABLE), configured) /** * Records that the server could not be used. * @param message why, for the user, in the words the settings pane would use. * @param refused whether it refused the credential; see [Health.refused]. + * @param configured as for [connectingIfUnknown]. */ - fun degraded(serverId: String, message: String, refused: Boolean = false) = - set(serverId, Health(State.DEGRADED, message, refused)) + fun degraded( + serverId: String, + message: String, + refused: Boolean = false, + configured: (String) -> Boolean = always, + ) = set(serverId, Health(State.DEGRADED, message, refused), configured) /** Lets the probe ask a server that refused its credential again, once the user changed it. */ fun credentialChanged(serverId: String) { - byServer.computeIfPresent(serverId) { _, health -> health.copy(refused = false) } + // Under the lock a refused write takes, so it cannot land after this and leave the server + // refused until the next edit. No listener runs here. + synchronized(lock) { + byServer.computeIfPresent(serverId) { _, health -> health.copy(refused = false) } + } } /** Forgets a server that was removed. */ fun forget(serverId: String) { - if (byServer.remove(serverId) != null) fireChanged() + if (detach(serverId)) fireChanged() } + /** + * As [forget], without telling the listeners: for a caller that forgets a server under a lock + * of its own, which a listener calling the host must not run under. That caller calls + * [notifyChanged] once it has let go, when this returned true. + * + * @return whether anything was known of [serverId]. + */ + internal fun detach(serverId: String): Boolean = synchronized(lock) { byServer.remove(serverId) != null } + + /** Tells the listeners of a change [detach] made. */ + internal fun notifyChanged() = fireChanged() + /** Forgets everything, for the plugin shutting down. */ fun clear() { - if (byServer.isEmpty()) return - byServer.clear() - fireChanged() + val had = synchronized(lock) { byServer.isNotEmpty().also { byServer.clear() } } + if (had) fireChanged() } - /** Registers [listener], called after any server's health changes. */ + /** + * Registers [listener], called after any server's health changes. Adding one already + * registered does nothing, so a host that activates the plugin twice still gets one call per + * change, and one [removeChangeListener] takes it out. + */ fun addChangeListener(listener: () -> Unit) { - listeners.add(listener) + listeners.addIfAbsent(listener) } /** Removes a listener added by [addChangeListener]. */ @@ -89,16 +136,33 @@ object McpServerHealth { listeners.remove(listener) } - /** Stores [health], telling the listeners only when it differs from what was there. */ - private fun set(serverId: String, health: Health) { - if (byServer.put(serverId, health) != health) fireChanged() + /** How many change listeners are registered; a test seam for a listener registered twice. */ + internal val changeListenerCount: Int get() = listeners.size + + /** + * Stores [health] while [configured] holds, telling the listeners, after the lock is let go, + * only when it differs from what was there. + */ + private fun set(serverId: String, health: Health, configured: (String) -> Boolean) { + val changed = synchronized(lock) { + if (!configured(serverId)) return + byServer.put(serverId, health) != health + } + if (changed) fireChanged() } + /** + * 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..4c04fe342 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolCatalog.kt @@ -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" @@ -22,17 +26,40 @@ private const val TAG = "$LOG_PREFIX.McpToolCatalog" * The agent reads the tool list on a UI-adjacent path and the contract forbids blocking on the * network there, so the list has to be answered from memory. This is that memory: filled by an * explicit [connect] — on activation, on Connect, after an edit — and read by the source. + * + * A SQLite debugger entry's list is not held here but beside its endpoint in [AutomaticServers], + * which checks the endpoint and stores the list under one lock: a copy here, written after that + * lock was let go, could be overwritten by a listing of an endpoint that has since been replaced. */ object McpToolCatalog { + /** The tools of the user's own servers; an automatic entry's are in [AutomaticServers]. */ private val toolsByServer = ConcurrentHashMap>() + /** + * Taken by [forget] and [clear], and around the check and the write that store a listing of one + * of the user's servers. The deletion removes the server from the store before it forgets its + * tools, so under this lock either the listing is stored first and forgotten with the server, or + * the check sees the server gone; written with no check, a listing that outlived the deletion + * brought the tools of a server that no longer exists back. + */ + private val lock = Any() + + /** Re-reads an automatic entry's endpoint and tries once more when the stored one is stale. */ + val retry = EndpointRetry( + refresh = AutomaticServers::refresh, + current = { id -> AutomaticServers.servers().firstOrNull { it.id == id } }, + token = AutomaticServers::token, + ) + /** * The cached tools for a server. * @param serverId the server. * @return its tools, empty before the first successful connection. */ - fun tools(serverId: String): List = toolsByServer[serverId].orEmpty() + fun tools(serverId: String): List = + if (AutomaticServers.isAutomatic(serverId)) AutomaticServers.tools(serverId) + else toolsByServer[serverId].orEmpty() /** * What one handshake-and-list answered. @@ -59,15 +86,18 @@ object McpToolCatalog { server: McpServer, exchangeListener: McpExchangeListener = McpExchangeListener.NONE, ): Listing { - McpServerHealth.connectingIfUnknown(server.id) + // Each checked with its write, under the lock a removal takes: a server deleted while the + // handshake was in flight, even just after a check, gets no row back, nor one whose URL was + // edited since [server] was read. + val configured = { _: String -> McpServers.isConfigured(server) } + McpServerHealth.connectingIfUnknown(server.id, configured) val listing = try { - list(server, exchangeListener) + retry.call(server) { list(it, exchangeListener) } } catch (e: Throwable) { recordFailure(server, e) throw e } - // Deleted while the handshake was in flight: recording it would resurrect its entry. - if (isConfigured(server.id)) McpServerHealth.available(server.id) + McpServerHealth.available(server.id, configured) return listing } @@ -84,34 +114,58 @@ object McpToolCatalog { McpServerHealth.cancelConnecting(server.id) return } - if (!isConfigured(server.id)) return val context = McpPlugin.getContext()?.androidContext val refused = failure is McpFailure.TokenRefused || failure is McpFailure.Forbidden - McpServerHealth.degraded(server.id, McpErrorFormatter.format(context, server.name, error), refused) + // Not for a server removed meanwhile, or moved to another URL, checked with the write as in + // connect: a stale caller's 401 from the old URL must not mark the moved server refused. + McpServerHealth.degraded( + server.id, + McpErrorFormatter.format(context, server, error), + refused, + ) { McpServers.isConfigured(server) } } - private fun isConfigured(serverId: String): Boolean = - McpServerStore.servers().any { it.id == serverId } - /** The handshake-and-list itself; see [connect]. */ private fun list(server: McpServer, exchangeListener: McpExchangeListener): Listing { - // Kept, not just its tools: the name the handshake returned lands on the session. - val session = McpConnections.session(server) - val tools = session.recording(exchangeListener) { - // Explicit, so a catalogue refused below is told apart from a refused connection. - session.initialize() - try { - session.listTools() - } catch (e: McpProtocolException) { - // No tools capability: some servers expose only prompts or resources, and still work. - if (e.code != JsonRpc.METHOD_NOT_FOUND) throw e - emptyList() + // 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 + // The name too: the handshake returns it on the session, which is ended here for a server + // removed meanwhile. + val (serverName, tools) = McpConnections.withSession(server) { session -> + val listed = session.recording(exchangeListener) { + // Explicit, so a catalogue refused below is told apart from a refused connection. + session.initialize() + try { + session.listTools() + } catch (e: McpProtocolException) { + // No tools capability: some servers expose only prompts or resources, and still work. + if (e.code != JsonRpc.METHOD_NOT_FOUND) throw e + emptyList() + } } + session.serverName to listed + } + if (server.automatic) { + // Stored by recordTools alone, beside the endpoint it checks, under the same lock. + 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(serverName, tools) + } + } else { + val stored = synchronized(lock) { + McpServers.isConfigured(server).also { if (it) toolsByServer[server.id] = tools } + } + if (!stored) { + Log.i(TAG, "Dropping a tool list from '${server.name}', removed or moved while it listed") + return Listing(serverName, tools) + } + McpServerStore.setKnownTools(server.id, server.url, tools.map { it.name }) } - 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) + return Listing(serverName, tools) } /** @@ -123,12 +177,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,23 +193,36 @@ 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 } - /** Forgets a server's tools and health, for one that was removed. */ + /** + * Forgets a server's tools and health, for one of the user's own that was removed. A SQLite + * debugger entry that went away is cleaned up by `AutomaticServers.refresh` itself, under its + * lock, so the entry that replaces it under the same ID keeps its own. + */ fun forget(serverId: String) { - toolsByServer.remove(serverId) + synchronized(lock) { toolsByServer.remove(serverId) } McpServerHealth.forget(serverId) } /** Forgets everything, for the plugin shutting down. */ fun clear() { - toolsByServer.clear() + synchronized(lock) { toolsByServer.clear() } McpServerHealth.clear() } } diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt index f4e04bf39..610c2ee52 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolSource.kt @@ -1,21 +1,24 @@ package com.itsaky.androidide.plugins.aiagentmcp.tools import android.util.Log +import com.itsaky.androidide.plugins.aiagentmcp.client.McpCallHandle import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections -import com.itsaky.androidide.plugins.aiagentmcp.client.McpSession import com.itsaky.androidide.plugins.aiagentmcp.client.McpTool +import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticServers +import com.itsaky.androidide.plugins.aiagentmcp.debugger.McpServers import com.itsaky.androidide.plugins.aiagentmcp.errors.McpErrorFormatter import com.itsaky.androidide.plugins.aiagentmcp.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 import java.util.concurrent.Executors +import java.util.concurrent.atomic.AtomicBoolean private const val TAG = "$LOG_PREFIX.McpToolSource" @@ -25,29 +28,59 @@ private const val TAG = "$LOG_PREFIX.McpToolSource" * Only tools the user switched on are offered: one popular GitHub server advertises around ninety, * which would exhaust a phone-sized context window on its own, so the toggle defaults to off and * this class never widens it. + * + * @param executor where remote calls run; see [newExecutor]. A seam, so a test can wait for a + * call's worker to finish rather than poll for something it might still send. + * @param beforeWork runs on the worker thread with the call's id, before the worker does anything + * else. A seam, so a test can land a cancel at the one point after the worker has started. + * + * A call is owned from the moment [invoke] accepts it, not from the moment its worker starts, so a + * [cancel] always finds it. The ownership rule, for every entry: + * - [calls]: [invoke] adds the entry before it schedules the worker. Exactly one party then removes + * it, whichever wins [Call.claimed]: the worker, in [runTool]'s `finally`, or [invoke]'s + * completion callback when the call finished without the worker (cancelled before it ran), or + * [invoke] itself when scheduling threw. The loser does nothing, and a worker that loses sends + * nothing. + * - [inFlight]: [invoke] adds it once the future exists; the future's completion removes it. + * + * A cancel reaches a call through its [Call.handle] alone: the flag the worker reads, and the + * connection the call's current request is using. Not through its session, which every call to + * that server, the health probe's listing and a SQLite debugger entry's relisting share; see + * [McpCallHandle] for the handshake that keeps a cancelled call from sending anything. */ -class McpToolSource : - ToolSourceRegistry.StatusReportingToolSource, +class McpToolSource internal constructor( + private val executor: ExecutorService, + private val beforeWork: (String) -> Unit = {}, +) : ToolSourceRegistry.StatusReportingToolSource, ToolSourceRegistry.GroupedToolSource { - /** Calls in flight, so a stopped agent run can drop the socket instead of waiting it out. */ + constructor() : this(newExecutor()) + + /** Each accepted call's future, so a cancel completes it at once rather than when its worker ends. */ private val inFlight = ConcurrentHashMap>() /** - * The session each in-flight call is using. - * - * Per call rather than "every session there is": two tools can be in flight against different - * servers at once, and cancelling both would report the survivor to the model as a transport - * failure for a call nobody cancelled. + * Every accepted call that has not finished, so [cancel] knows a call exists whatever its worker + * has reached. See the class KDoc for who removes an entry. */ - private val liveSessions = ConcurrentHashMap() + private val calls = ConcurrentHashMap() /** - * 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. + * One accepted call. + * + * [handle] is what a cancel reaches: its flag, which the worker reads before it looks up a + * session (so a cancel between the two attempts of the endpoint retry, or before the worker's + * first line, sends nothing), and the connection of the call's current request, which each + * request publishes and then checks the flag against before it sends anything. It lives on the + * call, so it goes with the call and a late cancel cannot leave a stray flag behind, nor reach + * another call's or a listing's connection. + * + * [claimed] is the cleanup ownership: the first party to set it, the worker as it starts or the + * completion callback as it finds the call finished without one, is the only one to clean up. */ - private val executor: ExecutorService = Executors.newCachedThreadPool { runnable -> - Thread(runnable, "mcp-tool-call").apply { isDaemon = true } + private class Call { + val handle = McpCallHandle() + val claimed = AtomicBoolean(false) } override fun getProviderId(): String = McpPlugin.PLUGIN_ID @@ -57,8 +90,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 +102,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 +127,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, @@ -103,32 +137,59 @@ class McpToolSource : Outcome(false, "", string(R.string.mcp_error_tool_gone, invocation.toolName)) ) - val future = CompletableFuture.supplyAsync( - { runTool(invocation.callId, target.first, target.second, invocation.arguments) }, - executor, - ) - inFlight[invocation.callId] = future - return future.whenComplete { _, _ -> inFlight.remove(invocation.callId) } + val callId = invocation.callId + // Before the worker is scheduled, so a cancel landing at any point after this finds the call. + val call = Call() + calls[callId] = call + val future = try { + CompletableFuture.supplyAsync( + { + beforeWork(callId) + runTool(callId, call, target.first, target.second, invocation.arguments) + }, + executor, + ) + } catch (e: Throwable) { + // Scheduling failed (a rejected task, a shut-down executor): no worker will ever run. + calls.remove(callId, call) + throw e + } + inFlight[callId] = future + return future.whenComplete { _, _ -> + inFlight.remove(callId) + // Finished without the worker (cancelled before it ran): nobody else will clean up. + if (call.claimed.compareAndSet(false, true)) calls.remove(callId, call) + } } + /** How many accepted calls have not finished; for a test to prove nothing is left behind. */ + internal fun pendingCalls(): Int = calls.size + override fun cancel(callId: String) { + // Sets the flag and drops the call's connection: the worker is blocked on a socket read, + // where an interrupt does nothing, so dropping the connection is what actually ends it. + // Only this call's, so another call or a listing against the same server keeps its socket. + calls[callId]?.handle?.cancel() inFlight.remove(callId)?.cancel(true) - // The worker is blocked on a socket read, where an interrupt does nothing; dropping the - // connection is what actually ends it. Only this call's, so a concurrent call against - // another server keeps its socket. - liveSessions.remove(callId)?.let { runCatching { it.cancel() } } } - /** Ends the executor, for the plugin shutting down. */ + /** + * Ends the executor and every call it accepted, for the plugin shutting down: no new work is + * taken, each running call's connection is dropped so its blocked read ends, and each future, + * a queued call's included, completes (cancelled) so nobody waits on one that will never run. + */ fun close() { executor.shutdownNow() + for (call in calls.values) call.handle.cancel() + for (future in inFlight.values) future.cancel(true) inFlight.clear() - liveSessions.clear() + calls.clear() } /** * Runs one remote tool. - * @param callId the agent's id for this call, so [cancel] can reach the session it is using. + * @param callId the agent's id for this call, named in the failure a cancel leaves. + * @param call the call's entry, registered by [invoke] before this was scheduled. * @param server the server that owns it. * @param tool the tool, as the server described it. * @param arguments the agent's arguments. @@ -136,25 +197,49 @@ class McpToolSource : */ private fun runTool( callId: String, + call: Call, server: McpServer, tool: McpTool, arguments: Map, - ): ToolSourceRegistry.ToolOutcome = try { - val session = McpConnections.session(server) - liveSessions[callId] = session - val result = try { - session.callTool(tool.name, arguments) + ): ToolSourceRegistry.ToolOutcome { + // Lost: the call finished (cancelled) before this worker began, and the completion callback + // has cleaned up. The result is discarded, so send nothing. + if (!call.claimed.compareAndSet(false, true)) { + return Outcome(false, "", string(R.string.mcp_error_cancelled, server.name)) + } + return try { + val result = McpToolCatalog.retry.call(server) { target -> + // Cancelled between two attempts (or before the first): nothing is looked up or sent. + // Signalled as an interrupted read, which is how a dropped connection already + // reports a cancel. + if (call.handle.isCancelled) { + throw InterruptedIOException("Tool call $callId was cancelled") + } + // A cancel landing from here on, during the session lookup or while a request reads + // its credentials, is caught by the handle: each request publishes its connection + // there and reads the flag again before it sends anything. + // The session is ended after the call when it was not kept: a server removed + // meanwhile would otherwise keep the session this call's handshake opened. + McpConnections.withSession(target) { it.callTool(tool.name, arguments, call.handle) } + } + // A reply of any kind, a tool's own failure included, means the server is answering; + // unless it was removed while the call ran, when recording it would bring back its row, + // or moved to another URL. Checked with the write, under the lock the removal takes, so + // it cannot land between. + McpServerHealth.available(server.id) { McpServers.isConfigured(server) } + Outcome(result.success, result.text, result.errorMessage) + } catch (e: Throwable) { + // Throwable, unlike the other host-facing catches in this plugin: this runs inside + // CompletableFuture.supplyAsync, which catches every Throwable itself, so narrowing this + // would not bring an OutOfMemoryError to the IDE's handler. It would only hand AI Core an + // exceptionally completed future in place of the failure outcome it expects. + Log.w(TAG, "Tool '${tool.name}' on '${server.name}' failed", e) + McpToolCatalog.recordFailure(server, e) + val context = McpPlugin.getContext()?.androidContext + Outcome(false, "", McpErrorFormatter.format(context, server, e)) } finally { - liveSessions.remove(callId) + calls.remove(callId, call) } - // A reply of any kind, a tool's own failure included, means the server is answering. - McpServerHealth.available(server.id) - Outcome(result.success, result.text, result.errorMessage) - } catch (e: Throwable) { - 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)) } /** @@ -169,10 +254,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 +286,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 +316,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 +327,48 @@ 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. + * AI-Core overrides `requiresApproval` to true for every contributed tool + * (`ContributedToolHandler`), so the Agent still asks. For a read-only tool, AI-Core 3.6.0 or + * later offers "Always Allow" for the rest of the chat (ADFA-7147); an older AI-Core asks on each + * call. The contract is a Java interface, so its accessors are implemented as * functions: Kotlin synthesises properties for *reading* a Java getter, never for overriding one. */ private class Spec( 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 } /** @@ -283,5 +406,13 @@ class McpToolSource : private companion object { /** Shown wherever tool provenance is surfaced. */ const val DISPLAY_NAME = "MCP servers" + + /** + * Remote calls run here rather than on the common pool: an MCP call blocks on a socket for + * as long as the read timeout, and the common pool is sized for CPU work. + */ + fun newExecutor(): ExecutorService = Executors.newCachedThreadPool { runnable -> + Thread(runnable, "mcp-tool-call").apply { isDaemon = true } + } } } diff --git a/plugins/AI-Agent-MCP/src/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..0141dd6a2 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolText.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolText.kt @@ -26,13 +26,79 @@ 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. Each app takes the + * first of these forms that is its own: + * 1. `db_` and the first seven characters of the application ID's last segment (`db_notes`); + * 2. the first five characters of the segment and four hex digits of a digest of the full + * application ID (`notes_3fa1`), when another app would share form 1 (`com.a.notes` and + * `com.b.notes`); + * 3. the segment's first character and eight hex digits of that digest (`n_3fa1c2d4`); + * 4. `db_` and a number, counted in application-ID order (`db_1`). + * + * A form is an app's own when no other app still choosing would take the same prefix and no + * app has already settled on it; every app settles on form 1 before any takes form 2, and so + * on. So the prefixes are distinct, and no app's later form takes another's earlier one, as + * `com.a.db`'s form 2, `db_ec81`, would take the form 1 of `com.c.ec81`. Each depends only on + * the set of application IDs, never on the order they were read in, so two listings of the same + * apps give every app the same name. Each fits [MAX_PREFIX_LENGTH]. + * + * @param applicationIds the application ID of every entry. + * @return the prefix by application ID. + */ + fun appPrefixes(applicationIds: Collection): Map { + val prefixes = mutableMapOf() + // Sorted, so the numbering of form 4 follows the IDs rather than the order they came in. + var choosing = applicationIds.toSortedSet().toList() + for (form in appPrefixForms) { + val wanted = choosing.associateWith { form(it) } + val wanting = wanted.values.groupingBy { it }.eachCount() + val settled = prefixes.values.toSet() + for ((id, prefix) in wanted) { + if (wanting.getValue(prefix) == 1 && prefix !in settled) prefixes[id] = prefix + } + choosing = choosing.filter { it !in prefixes } + } + // Form 4: only apps whose digests agree in 32 bits get here. + var number = 1 + for (id in choosing) { + while ("db_$number" in prefixes.values) number++ + prefixes[id] = "db_$number" + } + return prefixes + } + + /** Forms 1 to 3 of [appPrefixes], each a function of one application ID alone. */ + private val appPrefixForms: List<(String) -> String> = listOf( + { id -> "db_" + segment(id).take(MAX_PREFIX_LENGTH - 3).trim('_') }, + { id -> segment(id).take(5).trim('_') + "_" + digest(id, 2) }, + { id -> segment(id).take(1) + "_" + digest(id, 4) }, + ) + + private fun segment(applicationId: String): String = + identifier(applicationId.substringAfterLast('.')).ifEmpty { "app" } + + /** The first [bytes] bytes of the SHA-256 of [text], in hex. */ + private fun digest(text: String, bytes: Int): String = + java.security.MessageDigest.getInstance("SHA-256").digest(text.toByteArray()) + .take(bytes).joinToString("") { "%02x".format(it) } + /** * A free variant of [name], numbered when two tools ended up sharing one exposed name. * diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepth.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepth.kt new file mode 100644 index 000000000..4c97c79ec --- /dev/null +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepth.kt @@ -0,0 +1,96 @@ +package com.itsaky.androidide.plugins.aiagentmcp.transport + +/** + * How deeply a server's JSON may nest arrays and objects before anything here parses it. + * + * org.json parses recursively, once per array or object, and Android's has no limit of its own: + * a body of nothing but `[` runs the thread out of stack, and the StackOverflowError ends Code on + * the Go, whose process this plugin runs in. So a server's text is scanned first, in one pass with + * no recursion, and text nested deeper than [MAX], or not strict JSON, is never handed to a parser: + * a reply is refused with the rule it broke ([JsonRpc.parseReply]), and a body in the connection + * log is shown as it came. + */ +internal object JsonDepth { + + /** The deepest nesting read; no MCP reply comes near it. */ + const val MAX = 100 + + /** + * Why [refusal] refused a text, kept apart so a server's author is told the rule their reply + * broke: a reply refused for a comment but reported as nested too deep sends them looking for + * nesting that is not there. + * @property reason what is wrong with the text, to follow "The server's reply to 'm' ". + */ + sealed interface Refusal { + val reason: String + + /** More than [limit] arrays or objects one inside another. */ + data class TooDeep(val limit: Int) : Refusal { + override val reason: String get() = "nests arrays and objects more than $limit levels deep" + } + + /** + * [found] outside a string, where strict JSON never has it. A single quote is named in + * words, since three in a row read as noise; every other character is shown in quotes. + */ + data class NotStrict(val found: Char) : Refusal { + override val reason: String + get() = "is not strict JSON: a comment, single quote, ';', '=' or stray '\"' outside " + + "a string (found ${describe(found)})" + } + } + + /** [c] as a reason shows it: in single quotes, or in words for a single quote itself. */ + private fun describe(c: Char): String = if (c == '\'') "a single quote" else "'$c'" + + /** + * Why [text] may not be parsed: it opens more than [limit] arrays or objects one inside + * another, or it is not strict JSON where that could hide brackets; null when it may. One + * pass, no recursion; the first rule broken is the one reported. A bracket inside a string + * does not count. + * + * The scan reads strict JSON, because Android's org.json is lenient: it also reads `;` as a + * separator, `=` and `=>` between a name and its value, `//`, `/* */` and `#` comments, single + * quoted strings, and unquoted text that runs up to the next delimiter, a `"` included. Each is + * a way for a parser to take a bracket as structure where a scan of strict JSON takes it as + * text, and so to recurse past [limit] through text this scan passed. So, outside a string: + * - `'`, `;`, `=`, `/` and `#` refuse the text: valid JSON has none of them there; + * - a `"` opens a string where a value or a name starts, at the start or after `[`, `{`, `,` or + * `:`, whitespace aside, and refuses the text anywhere else, where Android's parser reads it + * as part of unquoted text: `[a",[[[` is one array nested in another for it, however many + * brackets follow the quote. + * + * Valid JSON is never refused for these rules, so no MCP reply is. + */ + fun refusal(text: String, limit: Int = MAX): Refusal? { + var depth = 0 + var inString = false + var escaped = false + // The last character outside a string and whitespace, or null at the start of the text. + var last: Char? = null + for (c in text) { + if (inString) { + when { + escaped -> escaped = false + c == '\\' -> escaped = true + c == '"' -> inString = false + } + continue + } + when (c) { + ' ', '\t', '\n', '\r' -> continue + '\'', ';', '=', '/', '#' -> return Refusal.NotStrict(c) + '"' -> { + if (last != null && last != '[' && last != '{' && last != ',' && last != ':') { + return Refusal.NotStrict(c) + } + inString = true + } + '[', '{' -> if (++depth > limit) return Refusal.TooDeep(limit) + ']', '}' -> if (depth > 0) depth-- + } + last = c + } + return null + } +} diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonRpc.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonRpc.kt index 7500c3dbf..d4dad5fbd 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonRpc.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonRpc.kt @@ -12,6 +12,8 @@ object JsonRpc { private const val VERSION = "2.0" + private const val BYTE_ORDER_MARK = "\uFEFF" + /** JSON-RPC's own code for a method the server does not implement. */ const val METHOD_NOT_FOUND = -32601 @@ -64,13 +66,24 @@ object JsonRpc { * * A batch — which the spec allows and some servers send even for a single request — is reduced * to its first non-notification member, since this client only ever has one call in flight. + * A leading byte order mark is ignored. + * + * A document nested deeper than [JsonDepth.MAX], or not strict JSON, is refused before any + * parser sees it: parsing recurses once per level, and on Android a server's reply nested + * thousands deep would end in a StackOverflowError that nothing here may catch. Text that is + * not strict JSON could hide such nesting from the scan, so it is refused too. * * @param payload one JSON-RPC document, object or array. * @return the reply, or null when the payload is not a reply at all (a server-initiated * request or notification, which this client does not answer). + * @throws UnparsedReplyException when [payload] nests deeper than [JsonDepth.MAX] or is not + * strict JSON, its message naming which. */ fun parseReply(payload: String): Reply? { - val trimmed = payload.trim() + // A byte order mark is dropped: a parser may ignore one (RFC 8259, 8.1), Android's org.json + // does, and the checks below took a reply that starts with one for no JSON at all. + val trimmed = payload.trim().removePrefix(BYTE_ORDER_MARK).trim() + JsonDepth.refusal(trimmed)?.let { throw UnparsedReplyException(it.reason) } val json = when { trimmed.startsWith("{") -> JSONObject(trimmed) trimmed.startsWith("[") -> org.json.JSONArray(trimmed).let { array -> @@ -115,4 +128,10 @@ object JsonRpc { return Reply(id = id, result = json.optJSONObject("result") ?: JSONObject()) } + + /** + * A reply [parseReply] refused unparsed: nested deeper than [JsonDepth.MAX], or not strict JSON. + * @param reason the rule it broke, to follow "The server's reply to 'm' ". + */ + class UnparsedReplyException internal constructor(reason: String) : IllegalArgumentException(reason) } diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpExchange.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpExchange.kt index e9afd518e..e70ea0a27 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpExchange.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpExchange.kt @@ -12,6 +12,9 @@ package com.itsaky.androidide.plugins.aiagentmcp.transport * @property responseHeaders the server's headers, in the order it sent them. * @property responseBody what the server sent back, or null when none was read. * @property failure what interrupted the exchange, or null when it ran to the end. + * @property cancelled the request was given up before it went out, as a cancelled tool call's is: + * nothing of it reached the server, and [requestHeaders] and [requestBody] are only what it + * would have carried. */ data class McpExchange( val method: String, @@ -22,6 +25,7 @@ data class McpExchange( val responseHeaders: List
    , val responseBody: Body?, val failure: String?, + val cancelled: Boolean = false, ) { /** One header line. */ diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpExchangeTrace.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpExchangeTrace.kt index 6b2719ea6..2dc218e7f 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpExchangeTrace.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpExchangeTrace.kt @@ -8,6 +8,7 @@ import java.net.HttpURLConnection * * @param headers the headers as set on the connection, credentials included. * @param contentLength the body's size in bytes, as the stack sends it. + * @param redactor the request's own, built from the credentials it carries. */ internal class McpExchangeTrace( private val method: String, @@ -15,9 +16,17 @@ internal class McpExchangeTrace( private val headers: List>, private val payload: String, private val contentLength: Int, - private val redactor: McpRedactor, + redactor: McpRedactor, ) { + /** + * What everything passes through: the request's redactor until [answered], and from there one + * that also masks the session id the answer assigned. A reply to `initialize` assigns one the + * request could not carry, and its body may repeat it. + */ + var redactor: McpRedactor = redactor + private set + private var status: String? = null private var responseHeaders: List = emptyList() private var responseBody: McpExchange.Body? = null @@ -25,9 +34,16 @@ internal class McpExchangeTrace( /** Records the status line and headers, which is where the server is first heard from. */ fun answered(conn: HttpURLConnection) { val code = conn.responseCode + // Before anything of the answer is kept: its other headers and its body may echo the id. + conn.getHeaderField(McpHttpClient.HEADER_SESSION_ID)?.takeIf { it.isNotBlank() } + ?.let { redactor = redactor.with(it) } val fields = conn.headerFields.orEmpty().entries - status = fields.firstOrNull { it.key == null }?.value?.firstOrNull() - ?: "HTTP $code ${conn.responseMessage.orEmpty()}".trim() + // Scrubbed like the headers and the body: a status line's reason phrase is the server's + // free text, and may repeat the session id it assigned or a credential it was sent. + status = redactor.scrub( + fields.firstOrNull { it.key == null }?.value?.firstOrNull() + ?: "HTTP $code ${conn.responseMessage.orEmpty()}".trim() + ) responseHeaders = fields // `X-Android-*` is the platform's own bookkeeping, not something the server sent. .filter { (name, _) -> name != null && !name.startsWith("X-Android-", ignoreCase = true) } @@ -39,11 +55,25 @@ internal class McpExchangeTrace( responseBody = McpExchange.Body.capped(redactor.scrub(body)) } + /** + * As [received], for a body kept only in part: [dropped] more characters came after [body] + * and were read and thrown away; the record counts them with what its own cap leaves out. + * + * When anything was dropped, [body] was cut at a fixed length and may end partway through a + * credential, which [McpRedactor.scrub] would leave showing; [McpRedactor.scrubCut] masks it. + */ + fun received(body: String, dropped: Long) { + val scrubbed = if (dropped > 0) redactor.scrubCut(body) else redactor.scrub(body) + val kept = McpExchange.Body.capped(scrubbed) + responseBody = kept.copy(omitted = (kept.omitted + dropped).coerceAtMost(Int.MAX_VALUE.toLong()).toInt()) + } + /** * The finished record. * @param failure what ended the request early, or null when it ran to the end. + * @param cancelled whether the request was given up before it went out; see [McpExchange.cancelled]. */ - fun toExchange(failure: Throwable?): McpExchange = McpExchange( + fun toExchange(failure: Throwable?, cancelled: Boolean = false): McpExchange = McpExchange( method = method, url = redactor.url(url), requestHeaders = headers.map { (name, value) -> redactor.requestHeader(name, value) } + @@ -54,5 +84,6 @@ internal class McpExchangeTrace( responseBody = responseBody, // The status line and body already say what an HTTP error was. failure = failure?.takeUnless { it is McpHttpException }?.let { redactor.message(it.describe()) }, + cancelled = cancelled, ) } diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt index 67c67f8f3..1e77acc36 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClient.kt @@ -1,9 +1,11 @@ package com.itsaky.androidide.plugins.aiagentmcp.transport import android.util.Log +import com.itsaky.androidide.plugins.aiagentmcp.errors.runCatchingRecoverable import com.itsaky.androidide.plugins.aiagentmcp.logging.LOG_PREFIX import java.io.BufferedReader import java.io.IOException +import java.io.InputStream import java.net.HttpURLConnection import java.net.URL import org.json.JSONObject @@ -24,10 +26,12 @@ private const val TAG = "$LOG_PREFIX.McpHttpClient" * * @param connectTimeoutMs how long to wait for the connection itself. * @param readTimeoutMs how long a call may take to answer. + * @param drainDeadlineMs how long reading a 202 body may take in all; see [drain]. */ open class McpHttpClient( private val connectTimeoutMs: Int = CONNECT_TIMEOUT_MS, private val readTimeoutMs: Int = READ_TIMEOUT_MS, + private val drainDeadlineMs: Long = DRAIN_DEADLINE_MS, ) { companion object { @@ -46,8 +50,108 @@ open class McpHttpClient( /** Same-origin redirects followed before giving up, so a redirect loop cannot spin. */ private const val MAX_REDIRECTS = 5 + + /** + * Characters of a drained body kept for the connection log: twice what the log shows, so + * a credential the redactor has to find is whole even where the log's own cut falls. The + * drain's own cut, at this length, can fall inside one; the trace masks what was kept of + * it with [McpRedactor.scrubCut], so the log never shows the start of a credential. + */ + internal const val DRAINED_CHARS_KEPT = 2 * McpExchange.Body.MAX_CHARS + + /** + * Characters of a 202 body read and thrown away, past the ones kept, before the drain gives + * up on it: about 1 MiB of ASCII. Far more than any server sends by mistake, and little + * enough that a body which never ends costs a moment rather than the call. + */ + internal const val DRAIN_BUDGET_CHARS = 1L shl 20 + + /** + * How long the drain of a 202 body may take in all, whatever the read timeout: far longer + * than a server needs to send a body it should not have sent, short enough that one which + * dribbles it cannot hold `initialize` for long. + */ + internal const val DRAIN_DEADLINE_MS = 10_000L + + /** + * Reads a body to its end through a fixed buffer, keeping only its first [keep] characters. + * + * For a 202, which should carry no body: one left unread keeps the socket out of the pool, + * and a server that sends a huge one must not cost Code on the Go, whose process this + * plugin runs in, its memory. Nor its time: a body that runs on past [budget] dropped + * characters is abandoned as a failure. A server streaming one forever would otherwise hold + * the read, and with it `initialize`, which is synchronized, and every health check behind + * it. A read that fails with an Exception or a LinkageError is returned as a failure too. + * The caller survives either by not reusing the socket; any other Error, an OutOfMemoryError + * above all, propagates. + * + * The budget bounds how much is read; [deadlineMs] bounds how long it takes. The clock is + * checked between reads, so a server that sends a byte just under every read timeout, which + * never trips that timeout, is abandoned at the deadline like one past the budget. The worst + * case is [deadlineMs] plus one read timeout: a read already blocked when the deadline + * passes ends only at its own timeout. + * + * Only a 202 is bounded this way. A JSON reply and an error body are read whole, with + * `readText()`: each is the document the caller needs. + * + * What is kept is cut at [keep] characters wherever that falls, inside a credential the + * server echoed too; [McpExchangeTrace.received] masks the end of a cut body for that. + * + * @param keep how many characters to keep. + * @param budget how many characters past [keep] may be read and dropped before the body is + * abandoned. + * @param deadlineMs how long the whole drain may take before the body is abandoned. + * @param nowMs the clock, in milliseconds from any fixed point; injectable so a test needs + * no real waiting. + * @param open opens the body; called inside the guard, since opening it can fail too. + * @return what was kept and how much was dropped, or the failure: a recoverable read + * failure, or a [DrainBudgetException] for a body that ran past [budget] or [deadlineMs]. + */ + internal fun drain( + keep: Int = DRAINED_CHARS_KEPT, + budget: Long = DRAIN_BUDGET_CHARS, + deadlineMs: Long = DRAIN_DEADLINE_MS, + nowMs: () -> Long = { System.nanoTime() / 1_000_000 }, + open: () -> InputStream, + ): Result = + runCatchingRecoverable { + val started = nowMs() + open().reader(Charsets.UTF_8).use { reader -> + val kept = StringBuilder() + val buffer = CharArray(8 * 1024) + var dropped = 0L + while (true) { + val read = reader.read(buffer) + if (read < 0) break + val room = (keep - kept.length).coerceIn(0, read) + kept.append(buffer, 0, room) + dropped += read - room + if (dropped > budget) { + throw DrainBudgetException( + "A 202 body ran past ${kept.length + budget} characters; abandoned it" + ) + } + if (nowMs() - started > deadlineMs) { + throw DrainBudgetException( + "A 202 body took more than $deadlineMs ms to read; abandoned it" + ) + } + } + Drained(kept.toString(), dropped) + } + } } + /** + * What [drain] read. + * @property text the body's first characters. + * @property dropped how many characters came after [text] and were read and thrown away. + */ + internal class Drained(val text: String, val dropped: Long) + + /** A 202 body that ran past [DRAIN_BUDGET_CHARS] or [DRAIN_DEADLINE_MS]; its socket is disconnected, not reused. */ + internal class DrainBudgetException(message: String) : IOException(message) + /** * One answer to a POST. * @property document the JSON-RPC document the server replied with, or null for `202 Accepted`, @@ -64,8 +168,19 @@ open class McpHttpClient( * @param body the JSON-RPC envelope to send. * @param sessionId the session to continue, or null before one exists. * @param protocolVersion the negotiated revision, or null before `initialize` has answered. - * @param onConnected receives the live connection, so a caller can disconnect it to cancel. + * @param onConnected receives each request's connection, redirect hops included, before it is + * connected, so a caller can disconnect it to cancel. What it throws ends the request unsent, + * and is recorded as [beforeSend]'s is: a cancel it catches, as cancelled. + * @param beforeSend runs once that connection is connected, before anything is written to it, + * and again once the body is written, before the answer is asked for; what it throws ends + * the request unsent. A `disconnect()` before the connection exists does nothing, so a cancel + * landing just after [onConnected] is caught here or not at all. Without a streaming mode the + * write only fills a buffer and the request goes out when the answer is first read, so the + * second run catches a cancel that landed during the write. A request it ends with an + * Exception is recorded as cancelled, never as sent ([McpExchange.cancelled]); an Error + * propagates and is recorded as the failure it is. * @param exchangeListener receives each request made and what came back, redirects included. + * An Exception or a LinkageError it throws is dropped; any other Error propagates. * @return the reply document and any session id the server sent. * @throws McpHttpException on a non-2xx answer, carrying the server's error body. */ @@ -77,6 +192,7 @@ open class McpHttpClient( protocolVersion: String? = null, extraHeaders: Map = emptyMap(), onConnected: (HttpURLConnection) -> Unit = {}, + beforeSend: () -> Unit = {}, exchangeListener: McpExchangeListener = McpExchangeListener.NONE, ): Response { val payload = body.toString() @@ -96,14 +212,38 @@ open class McpHttpClient( doOutput = true } val trace = McpExchangeTrace("POST", target, headers, payload, bytes.size, redactor) - onConnected(conn) // Only a socket that cannot be reused is disconnected: `disconnect()` evicts it from // the pool, so doing it on the success path made every call — initialize, each // tools/list page, each tools/call — pay a fresh TCP and TLS handshake. var reusable = false var failure: Throwable? = null + // Set when onConnected or beforeSend ends the request: nothing went out, and its record + // must not say so. + var cancelled = false + fun unsentIfThrows(step: () -> Unit) { + try { + step() + } catch (e: Exception) { + // A cancel, which both throw as an InterruptedIOException. An Error is not one: + // the process is failing, and its record must not read "cancelled". + cancelled = true + throw e + } + } val redirect = try { + // Inside the try, so a cancel caught here, as the call's handle publishes the + // connection, leaves its record in the connection log like one caught below. + unsentIfThrows { onConnected(conn) } + // Connected here rather than by the first write, so beforeSend runs in between: a + // cancel whose disconnect came before the connection existed dropped nothing, and the + // write would connect and send the request regardless. + conn.connect() + unsentIfThrows(beforeSend) conn.outputStream.use { it.write(bytes) } + // Again: the write only filled a buffer, and the request goes out at the first read + // of the answer, just below. A cancel that landed meanwhile disconnected a connection + // the JDK connects again at that read, sending the request after all. + unsentIfThrows(beforeSend) trace.answered(conn) val next = conn.redirectTargetFrom(target) if (next == null) { @@ -115,8 +255,11 @@ open class McpHttpClient( // than ignored, since a body left unread keeps the socket out of the pool. if (conn.responseCode == HttpURLConnection.HTTP_ACCEPTED) { // A half-read body is neither pooled nor closed, so only a whole drain counts. - val drained = runCatching { conn.inputStream.use { it.readBytes() } } - drained.getOrNull()?.let { trace.received(String(it, Charsets.UTF_8)) } + val drained = drain(deadlineMs = drainDeadlineMs) { conn.inputStream } + drained.getOrNull()?.let { trace.received(it.text, it.dropped) } + drained.exceptionOrNull()?.let { e -> + Log.w(TAG, "Not reusing the connection after its 202 body: ${e.message}") + } reusable = drained.isSuccess return Response(null, assignedSession) } @@ -141,7 +284,13 @@ open class McpHttpClient( throw e } finally { if (!reusable) conn.disconnect() - runCatching { exchangeListener.onExchange(trace.toExchange(failure), redactor) } + // The connection log is a convenience: a listener failing with an Exception or a + // LinkageError costs only its record. Any other Error, an OutOfMemoryError above + // all, is the process failing and propagates. + // The trace's redactor, which masks a session id this answer assigned as well. + runCatchingRecoverable { + exchangeListener.onExchange(trace.toExchange(failure, cancelled), trace.redactor) + } } if (++hops > MAX_REDIRECTS) { diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpRedactor.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpRedactor.kt index 89d9d352a..a3e29358e 100644 --- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpRedactor.kt +++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpRedactor.kt @@ -1,5 +1,6 @@ package com.itsaky.androidide.plugins.aiagentmcp.transport +import com.itsaky.androidide.plugins.aiagentmcp.errors.runCatchingRecoverable import java.net.URLDecoder /** @@ -10,7 +11,7 @@ import java.net.URLDecoder * @param userHeaderNames the headers the user configured; their values are stored encrypted. */ class McpRedactor( - credentials: Collection, + private val credentials: Collection, private val userHeaderNames: Collection, ) { @@ -38,6 +39,9 @@ class McpRedactor( /** Characters JSON may escape with a backslash alone. */ private const val JSON_BACKSLASHED = "\"\\/" + /** The longest form [encodedForms] matches one character in: `\uXXXX`. */ + private const val LONGEST_CHAR_FORM = 6 + /** * A redactor for one request to [url], which also masks what the URL itself carries. * @param credentials the token, session and the user's header values, as sent. @@ -46,26 +50,48 @@ class McpRedactor( fun forRequest(url: String, credentials: Collection, userHeaderNames: Collection) = McpRedactor(credentials + urlSecrets(url), userHeaderNames) - /** The userinfo and query values of [url], long enough to be masked wherever echoed. */ - private fun urlSecrets(url: String): List { + /** + * The userinfo and query values of [url], long enough to be masked wherever echoed. + * A value that cannot be decoded is kept as it is; an Error other than a LinkageError, an + * OutOfMemoryError above all, propagates. + * @param decode the URL decoding; injectable so a test can make it fail. + */ + internal fun urlSecrets( + url: String, + decode: (String) -> String = { URLDecoder.decode(it, "UTF-8") }, + ): List { val userInfo = USERINFO.find(url)?.groupValues?.get(2) val values = url.substringAfter('?', "").substringBefore('#') .split('&') .map { it.substringAfter('=', "") } return (listOfNotNull(userInfo, userInfo?.substringAfter(':', "")) + values) - .flatMap { listOf(it, runCatching { URLDecoder.decode(it, "UTF-8") }.getOrDefault(it)) } + .flatMap { listOf(it, runCatchingRecoverable { decode(it) }.getOrDefault(it)) } .filter { it.length >= MIN_SUBSTRING_LENGTH } } } - /** Longest first, so no secret is left half-masked by a shorter one inside it. */ - private val secrets: List = credentials + /** The secrets as given, longest first, so none is left half-masked by a shorter one inside it. */ + private val plainSecrets: List = credentials .flatMap { listOfNotNull(it, SCHEMED.matchEntire(it)?.groupValues?.get(2)) } .filter { it.isNotEmpty() } .distinct() .sortedByDescending { it.length } + + private val secrets: List = plainSecrets .map { if (it.length >= MIN_SUBSTRING_LENGTH) Regex(encodedForms(it)) else wholeToken(it) } + /** How many characters one secret can take up in a text at most, in its longest escaped form. */ + private val longestForm: Int = (plainSecrets.firstOrNull()?.length ?: 0) * LONGEST_CHAR_FORM + + /** + * This redactor, masking [credential] as well: for a secret the server hands out in its answer, + * which the request this redactor was built for could not carry. + * @param credential the secret, such as the session id a reply to `initialize` assigns. + * @return a redactor masking it and everything this one masks; this one when it already does. + */ + fun with(credential: String): McpRedactor = + if (credential in credentials) this else McpRedactor(credentials + credential, userHeaderNames) + /** * A header this client sent, its value hidden when it is a credential. * @return the header as it may be shown. @@ -89,6 +115,52 @@ class McpRedactor( */ fun scrub(text: String): String = secrets.fold(text) { acc, secret -> acc.replace(secret, MASK) } + /** + * As [scrub], for a text that is the start of something longer, cut at a fixed length without + * regard to what it cut through. [scrub] masks whole credentials only, so one the cut fell + * inside would show its start. Here the end is masked from where such a credential starts, + * in any form [scrub] matches, escaped or not, so the text ends in [MASK] rather than in part + * of one. That start is the first character from which a credential reads on to the cut + * unfinished, moved back over any whole credential that runs past it, so no part of one is + * left before the mask either. + * + * Only the last characters, as many as a credential can take up, are examined, and nothing is + * copied but the result, so the cost is bounded whatever the length of [text]. + * + * @param text the first characters of a body, the rest of which was not kept. + * @return the text, safe to show. + */ + fun scrubCut(text: String): String { + val start = credentialAtEnd(text) + return if (start == text.length) scrub(text) else scrub(text.substring(0, start)) + MASK + } + + /** + * Where the credential that [text] may end partway through starts; see [scrubCut]. + * @return its index, or the length of [text] when its end is not part of one. + */ + private fun credentialAtEnd(text: String): Int { + // Transparent bounds, so a short secret's "not inside a word" check sees what precedes. + val matchers = secrets.map { it.toPattern().matcher(text).useTransparentBounds(true) } + var start = text.length + while (true) { + val from = (start - longestForm).coerceAtLeast(0) + val earlier = (from until start).firstOrNull { index -> + matchers.any { it.reachesPast(index, start, text.length) } + } ?: return start + start = earlier + } + } + + /** + * Whether a credential read from [index] runs past [mark]: a whole match that ends after it, or + * one the end of the text cut short, which is what `hitEnd` reports when nothing matched. + */ + private fun java.util.regex.Matcher.reachesPast(index: Int, mark: Int, length: Int): Boolean { + region(index, length) + return if (lookingAt()) end() > mark else hitEnd() + } + /** * A URL as it may be shown: its userinfo and every query value masked, then scrubbed. * A secret carried in a path segment cannot be told apart from the path, so it stays. diff --git a/plugins/AI-Agent-MCP/src/main/res/values/strings.xml b/plugins/AI-Agent-MCP/src/main/res/values/strings.xml index b28ff7f18..4f40b1b19 100644 --- a/plugins/AI-Agent-MCP/src/main/res/values/strings.xml +++ b/plugins/AI-Agent-MCP/src/main/res/values/strings.xml @@ -84,6 +84,10 @@ %1$s\'s saved credentials could not be read just now. They are still stored — try again in a moment. Could not reach %1$s. Could not reach %1$s: %2$s + + The app %1$s did not answer. If the app is in the background, Android may have paused it. Bring the app to the front and try again. + + The app %1$s is not running with the SQLite debugger. Open the app again from Code on the Go. \'%1$s\' is no longer offered by any configured MCP server. @@ -99,7 +103,9 @@ Headers Body No response + Cancelled Nothing was sent: the request failed before it reached the server. + Cancelled before it was sent: nothing of it reached the server. Extra headers diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/AssignedSessionRedactionTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/AssignedSessionRedactionTest.kt new file mode 100644 index 000000000..1905a479c --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/AssignedSessionRedactionTest.kt @@ -0,0 +1,105 @@ +package com.itsaky.androidide.plugins.aiagentmcp.client + +import com.itsaky.androidide.plugins.aiagentmcp.transport.McpExchangeLog +import com.itsaky.androidide.plugins.aiagentmcp.transport.McpExchangeTrace +import com.itsaky.androidide.plugins.aiagentmcp.transport.McpRedactor +import com.sun.net.httpserver.HttpServer +import io.mockk.every +import io.mockk.mockk +import java.net.HttpURLConnection +import java.net.InetSocketAddress +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * A session id the server assigns in its reply to `initialize` is masked in the connection log + * wherever that same reply's body echoes it. + * + * The log's redactor is built from what the request carried, and `initialize` carries no session + * id: the server assigns one in its answer. The `Mcp-Session-Id` header itself was hidden by name, + * but a body repeating the id showed it. The redactor for that answer now masks it too. + */ +class AssignedSessionRedactionTest { + + private val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply { + createContext("/mcp") { exchange -> + val request = JSONObject(exchange.requestBody.use { String(it.readBytes()) }) + if (!request.has("id")) { + exchange.sendResponseHeaders(202, -1) + } else { + val result = JSONObject() + .put("protocolVersion", "2025-06-18") + .put("serverInfo", JSONObject().put("name", "echoing")) + .put("instructions", "Your session is $SESSION_ID.") + val bytes = JSONObject().put("jsonrpc", "2.0").put("id", request.get("id")) + .put("result", result).toString().toByteArray() + exchange.responseHeaders.add("Content-Type", "application/json") + exchange.responseHeaders.add("Mcp-Session-Id", SESSION_ID) + exchange.sendResponseHeaders(200, bytes.size.toLong()) + exchange.responseBody.use { it.write(bytes) } + } + exchange.close() + } + start() + } + + @After + fun tearDown() { + server.stop(0) + } + + @Test + fun `a session id the server assigns is masked where the same reply's body echoes it`() { + val session = McpSession( + "http://127.0.0.1:${server.address.port}/mcp", + { McpCredentials("", emptyMap()) }, + ) + val log = McpExchangeLog() + + session.recording(log) { session.initialize() } + + val reply = requireNotNull(log.snapshot().first().responseBody).text + assertFalse("the connection log shows the assigned session id: $reply", reply.contains(SESSION_ID)) + assertTrue("the echo was not masked: $reply", reply.contains("Your session is ${McpRedactor.MASK}.")) + } + + @Test + fun `a session id the server assigns is masked in the status line that repeats it`() { + val trace = trace(McpRedactor(emptyList(), emptyList())) + + trace.answered(connection("HTTP/1.1 200 Session $SESSION_ID ready", sessionId = SESSION_ID)) + + val status = requireNotNull(trace.toExchange(null).status) + assertFalse("the status line shows the assigned session id: $status", status.contains(SESSION_ID)) + assertTrue("the status line was not masked: $status", status.contains(McpRedactor.MASK)) + } + + @Test + fun `the request's bearer token is masked in a status line that repeats it`() { + val trace = trace(McpRedactor(listOf(BEARER), emptyList())) + + trace.answered(connection("HTTP/1.1 401 Bad token $BEARER", sessionId = null)) + + val status = requireNotNull(trace.toExchange(null).status) + assertFalse("the status line shows the bearer token: $status", status.contains(BEARER)) + } + + private fun trace(redactor: McpRedactor) = + McpExchangeTrace("POST", "http://127.0.0.1/mcp", emptyList(), "{}", 2, redactor) + + private fun connection(statusLine: String, sessionId: String?): HttpURLConnection = + mockk().also { + every { it.responseCode } returns 200 + every { it.responseMessage } returns "" + every { it.getHeaderField("Mcp-Session-Id") } returns sessionId + every { it.headerFields } returns mapOf(null to listOf(statusLine)) + } + + private companion object { + const val SESSION_ID = "sess-7d41c9e2a8b3f650" + const val BEARER = "bearer-9f3a71c2d8e45b60" + } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/CancelAfterAttachTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/CancelAfterAttachTest.kt new file mode 100644 index 000000000..9cf4003f1 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/CancelAfterAttachTest.kt @@ -0,0 +1,101 @@ +package com.itsaky.androidide.plugins.aiagentmcp.client + +import com.itsaky.androidide.plugins.aiagentmcp.transport.McpExchangeListener +import com.itsaky.androidide.plugins.aiagentmcp.transport.McpHttpClient +import com.sun.net.httpserver.HttpServer +import java.io.InterruptedIOException +import java.net.HttpURLConnection +import java.net.InetSocketAddress +import java.util.concurrent.CopyOnWriteArrayList +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * A cancel that lands just after a request published its connection, after [McpCallHandle.attach] + * read the flag and before the connection is connected, sends nothing. + * + * Such a cancel finds the connection and disconnects it, but a connection that is not connected + * yet has nothing to drop, on Android and on the JDK alike; the request's first write then + * connected and sent it. The request now reads the flag again once its connection is up. + */ +class CancelAfterAttachTest { + + /** The JSON-RPC method of every request body the server received, in order. */ + private val received = CopyOnWriteArrayList() + + private val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply { + createContext("/mcp") { exchange -> + val request = JSONObject(exchange.requestBody.use { String(it.readBytes()) }) + received += request.optString("method") + if (!request.has("id")) { + exchange.sendResponseHeaders(202, -1) + } else { + val result = when (request.optString("method")) { + "initialize" -> JSONObject().put("protocolVersion", "2025-06-18") + else -> JSONObject().put("content", org.json.JSONArray()) + } + val bytes = JSONObject().put("jsonrpc", "2.0").put("id", request.get("id")) + .put("result", result).toString().toByteArray() + exchange.responseHeaders.add("Content-Type", "application/json") + exchange.sendResponseHeaders(200, bytes.size.toLong()) + exchange.responseBody.use { it.write(bytes) } + } + exchange.close() + } + start() + } + + @After + fun tearDown() { + server.stop(0) + } + + @Test + fun `a cancel that lands just after the request attached sends nothing`() { + val handle = McpCallHandle() + val http = object : McpHttpClient() { + override fun post( + url: String, + token: String, + body: JSONObject, + sessionId: String?, + protocolVersion: String?, + extraHeaders: Map, + onConnected: (HttpURLConnection) -> Unit, + beforeSend: () -> Unit, + exchangeListener: McpExchangeListener, + ): Response = super.post( + url, + token, + body, + sessionId, + protocolVersion, + extraHeaders, + onConnected = { conn -> + onConnected(conn) + // Here: attach has read the flag, and the connection is not connected yet. + if (body.optString("method") == "tools/call") handle.cancel() + }, + beforeSend = beforeSend, + exchangeListener = exchangeListener, + ) + } + val session = McpSession( + "http://127.0.0.1:${server.address.port}/mcp", + { McpCredentials("", emptyMap()) }, + http, + ) + + val failure = runCatching { session.callTool("echo", emptyMap(), handle) }.exceptionOrNull() + + assertEquals( + "the cancelled call's request reached the server", + listOf("initialize", "notifications/initialized"), + received.toList(), + ) + assertTrue("the call did not end cancelled: $failure", failure is InterruptedIOException) + } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/CancelAfterCheckTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/CancelAfterCheckTest.kt new file mode 100644 index 000000000..c20ecc266 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/CancelAfterCheckTest.kt @@ -0,0 +1,108 @@ +package com.itsaky.androidide.plugins.aiagentmcp.client + +import com.itsaky.androidide.plugins.aiagentmcp.transport.McpExchangeListener +import com.itsaky.androidide.plugins.aiagentmcp.transport.McpHttpClient +import com.sun.net.httpserver.HttpServer +import java.io.InterruptedIOException +import java.net.HttpURLConnection +import java.net.InetSocketAddress +import java.util.concurrent.CopyOnWriteArrayList +import org.json.JSONArray +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * A cancel that lands once the request has read its flag before the write sends nothing. + * + * Without a streaming mode the write only fills a buffer: the request goes out when the answer is + * first asked for. A cancel landing between the flag's read and that point disconnected the + * connection, and the JDK connected again at the write and sent the request when it was answered. + * The request now reads the flag once more after the write, before it asks for the answer. + * + * The cancel is made from inside that first read, just after it passed: the write, and the point + * where the request would go out, both come after it. The server counts the request bodies it gets. + */ +class CancelAfterCheckTest { + + /** The JSON-RPC method of every request body the server received, in order. */ + private val received = CopyOnWriteArrayList() + + private val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply { + createContext("/mcp") { exchange -> + val request = JSONObject(exchange.requestBody.use { String(it.readBytes()) }) + received += request.optString("method") + if (!request.has("id")) { + exchange.sendResponseHeaders(202, -1) + } else { + val result = when (request.optString("method")) { + "initialize" -> JSONObject().put("protocolVersion", "2025-06-18") + else -> JSONObject().put("content", JSONArray()) + } + val bytes = JSONObject().put("jsonrpc", "2.0").put("id", request.get("id")) + .put("result", result).toString().toByteArray() + exchange.responseHeaders.add("Content-Type", "application/json") + exchange.sendResponseHeaders(200, bytes.size.toLong()) + exchange.responseBody.use { it.write(bytes) } + } + exchange.close() + } + start() + } + + @After + fun tearDown() { + server.stop(0) + } + + @Test + fun `a cancel that lands after the check before the write sends nothing`() { + val handle = McpCallHandle() + val http = object : McpHttpClient() { + override fun post( + url: String, + token: String, + body: JSONObject, + sessionId: String?, + protocolVersion: String?, + extraHeaders: Map, + onConnected: (HttpURLConnection) -> Unit, + beforeSend: () -> Unit, + exchangeListener: McpExchangeListener, + ): Response { + var checks = 0 + return super.post( + url, + token, + body, + sessionId, + protocolVersion, + extraHeaders, + onConnected, + beforeSend = { + beforeSend() + // Here: the connection is up and the flag was read; the write comes next. + if (body.optString("method") == "tools/call" && checks++ == 0) handle.cancel() + }, + exchangeListener = exchangeListener, + ) + } + } + val session = McpSession( + "http://127.0.0.1:${server.address.port}/mcp", + { McpCredentials("", emptyMap()) }, + http, + ) + + val failure = runCatching { session.callTool("echo", emptyMap(), handle) }.exceptionOrNull() + + assertEquals( + "the cancelled call's request reached the server", + listOf("initialize", "notifications/initialized"), + received.toList(), + ) + assertTrue("the call did not end cancelled: $failure", failure is InterruptedIOException) + } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/DeepReplyTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/DeepReplyTest.kt new file mode 100644 index 000000000..ed1f7d940 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/DeepReplyTest.kt @@ -0,0 +1,92 @@ +package com.itsaky.androidide.plugins.aiagentmcp.client + +import com.itsaky.androidide.plugins.aiagentmcp.transport.JsonDepth +import com.itsaky.androidide.plugins.aiagentmcp.transport.McpExchangeListener +import com.itsaky.androidide.plugins.aiagentmcp.transport.McpHttpClient +import java.io.IOException +import java.net.HttpURLConnection +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertThrows +import org.junit.Test + +/** + * A server whose reply nests arrays thousands deep fails the listing with a reason, rather than + * running the thread out of stack. + * + * Android's org.json recurses once per level with no limit, and the StackOverflowError it throws + * is not caught on the way: during Connect, the activation's first listing or the health probe it + * would end Code on the Go. The reply is now refused before it is parsed. The org.json these tests + * run on fails such a parse with a JSONException of its own, so the message is what tells the + * guard's refusal apart. + * + * The reason is the rule the reply broke. A reply with a comment, refused because it is not strict + * JSON, was reported as nested more than 100 levels deep, and its server's author would look for + * nesting that is not there. + */ +class DeepReplyTest { + + private fun session(listReply: String) = McpSession( + "http://127.0.0.1:1/mcp", + { McpCredentials("", emptyMap()) }, + object : McpHttpClient() { + override fun post( + url: String, + token: String, + body: JSONObject, + sessionId: String?, + protocolVersion: String?, + extraHeaders: Map, + onConnected: (HttpURLConnection) -> Unit, + beforeSend: () -> Unit, + exchangeListener: McpExchangeListener, + ): Response = when (body.optString("method")) { + "initialize" -> Response( + """{"jsonrpc":"2.0","id":${body.get("id")},"result":{"protocolVersion":"2026-07-28"}}""", + null, + ) + "tools/list" -> Response(listReply, null) + else -> Response(null, null) + } + }, + ) + + @Test + fun `a reply nested ten thousand deep fails the listing with the depth as its reason`() { + val failure = assertThrows(IOException::class.java) { session("[".repeat(10_000)).listTools() } + + assertEquals( + "The server's reply to 'tools/list' nests arrays and objects more than ${JsonDepth.MAX} " + + "levels deep; it was not read.", + failure.message, + ) + } + + @Test + fun `a reply one level past the limit fails the listing with the depth as its reason`() { + val depth = JsonDepth.MAX + 1 + val failure = assertThrows(IOException::class.java) { + session("[".repeat(depth) + "]".repeat(depth)).listTools() + } + + assertEquals( + "The server's reply to 'tools/list' nests arrays and objects more than ${JsonDepth.MAX} " + + "levels deep; it was not read.", + failure.message, + ) + } + + @Test + fun `a reply with a comment fails the listing as not strict JSON, not as nested too deep`() { + val reply = """{"jsonrpc":"2.0","id":2, // the listing + |"result":{"tools":[]}}""".trimMargin() + + val failure = assertThrows(IOException::class.java) { session(reply).listTools() } + + assertEquals( + "The server's reply to 'tools/list' is not strict JSON: a comment, single quote, ';', '=' " + + "or stray '\"' outside a string (found '/'); it was not read.", + failure.message, + ) + } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/DetachAllErrorTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/DetachAllErrorTest.kt new file mode 100644 index 000000000..9d20198e0 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/DetachAllErrorTest.kt @@ -0,0 +1,87 @@ +package com.itsaky.androidide.plugins.aiagentmcp.client + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpToolCatalog +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame +import org.junit.Assert.assertThrows +import org.junit.Before +import org.junit.Test + +/** + * Taking every session out loses none of them when reading one session's credentials throws an + * Error. + * + * `detachAll` emptied the map, then read each session's credentials as it built the list it + * returned. An Error from one read, which a recoverable read lets through, escaped with the list + * unbuilt: the sessions were out of the map and nobody held them, so none got its DELETE. Each + * session now reaches the caller's list as it leaves the map, the one whose read failed with no + * credentials, and the Error is thrown after the others are safe. + */ +class DetachAllErrorTest { + + private val servers = List(3) { FakeMcpServer("", listOf(tool("search", true)), sessionId = "session-$it") } + private val failure = OutOfMemoryError("reading the second token") + @Volatile private var failing = false + + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + mockkObject(McpServerStore) + every { McpServerStore.headers(any()) } returns emptyMap() + } + + @After + fun tearDown() { + failing = false + McpConnections.closeAll() + McpToolCatalog.clear() + servers.forEach { it.stop() } + plugin.dispose() + unmockkObject(McpServerStore) + } + + @Test + fun `an Error reading one session's credentials does not lose the others, and reaches the caller`() { + val saved = servers.mapIndexed { i, server -> + McpServerStore.saveDetails(McpServerStore.newServer("S$i", "http://127.0.0.1:${server.port}/mcp")) + } + every { McpServerStore.token(any()) } answers { + val id = firstArg() + if (failing && id == saved[1].id) throw failure + KeystoreSecretStore.Stored.Value("token-of-$id") + } + saved.forEach { McpConnections.withSession(it) { session -> session.initialize() } } + // After the sessions exist, so only the take-out's read throws. + failing = true + + val thrown = assertThrows(OutOfMemoryError::class.java) { McpConnections.closeAll() } + + assertSame("not the Error from the read", failure, thrown) + servers.forEachIndexed { i, server -> + val delete = server.requests.singleOrNull { it.httpMethod == "DELETE" } + assertEquals("session $i was never ended", true, delete != null) + if (i == 1) { + assertNull("the session whose read failed was sent a token", delete!!.authorization) + } else { + assertEquals("Bearer token-of-${saved[i].id}", delete!!.authorization) + } + } + } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/EndAllSessionsTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/EndAllSessionsTest.kt new file mode 100644 index 000000000..bfcc1f19f --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/EndAllSessionsTest.kt @@ -0,0 +1,74 @@ +package com.itsaky.androidide.plugins.aiagentmcp.client + +import com.itsaky.androidide.plugins.aiagentmcp.transport.McpExchangeListener +import com.itsaky.androidide.plugins.aiagentmcp.transport.McpHttpClient +import java.net.HttpURLConnection +import java.util.concurrent.CopyOnWriteArrayList +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertSame +import org.junit.Assert.assertThrows +import org.junit.Test + +/** + * Ending the sessions a lifecycle call took out ends every one of them, even when ending one + * throws an Error, and then throws that Error. + * + * A session's close survives an Exception or a LinkageError and lets any other Error through. The + * loop over the sessions stopped at the first, and every session after it was never ended, so its + * server kept it open. Each is now ended, and the first Error is thrown after the last. + */ +class EndAllSessionsTest { + + private val ended = CopyOnWriteArrayList() + + /** A session with a server-side id, whose DELETE throws [failure], or is recorded when null. */ + private fun session(url: String, failure: Error? = null) = McpSession( + url, + { McpCredentials("", emptyMap()) }, + object : McpHttpClient() { + override fun post( + url: String, + token: String, + body: JSONObject, + sessionId: String?, + protocolVersion: String?, + extraHeaders: Map, + onConnected: (HttpURLConnection) -> Unit, + beforeSend: () -> Unit, + exchangeListener: McpExchangeListener, + ): Response = when (body.optString("method")) { + "initialize" -> Response( + """{"jsonrpc":"2.0","id":${body.get("id")},"result":{"protocolVersion":"2025-03-26"}}""", + "session-of-$url", + ) + else -> Response(null, null) + } + + override fun deleteSession(url: String, token: String, sessionId: String, extraHeaders: Map) { + failure?.let { throw it } + ended += url + } + }, + ).also { it.initialize() } + + @Test + fun `an Error ending one session does not stop the others, and the first is thrown after them`() { + val first = OutOfMemoryError("ending a") + val second = OutOfMemoryError("ending c") + val released = listOf( + session(url("a"), first), + session(url("b")), + session(url("c"), second), + session(url("d")), + ).map { McpConnections.Released(it, "", null) } + + val thrown = assertThrows(OutOfMemoryError::class.java) { McpConnections.endAll(released) } + + assertEquals("the sessions after a failing one were not ended", listOf(url("b"), url("d")), ended) + assertSame("not the first Error", first, thrown) + assertSame("the second Error was lost", second, thrown.suppressed.single()) + } + + private fun url(name: String) = "http://127.0.0.1:1/$name" +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpCallHandleTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpCallHandleTest.kt new file mode 100644 index 000000000..e89990609 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpCallHandleTest.kt @@ -0,0 +1,103 @@ +package com.itsaky.androidide.plugins.aiagentmcp.client + +import java.io.InterruptedIOException +import java.net.HttpURLConnection +import java.net.URL +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The handshake between a request and a cancel, either way round: a request that publishes its + * connection after the cancel sends nothing, and a cancel after the request published drops that + * connection and no other. + */ +class McpCallHandleTest { + + /** A connection that never connects; counts its disconnects, or fails them with [failure]. */ + private class FakeConnection(private val failure: Throwable? = null) : + HttpURLConnection(URL("http://127.0.0.1/mcp")) { + var disconnects = 0 + + override fun disconnect() { + failure?.let { throw it } + disconnects++ + } + + override fun usingProxy() = false + + override fun connect() = Unit + } + + @Test + fun `a request attached after the cancel is refused before it sends anything`() { + val handle = McpCallHandle() + handle.cancel() + + assertThrows(InterruptedIOException::class.java) { handle.attach(FakeConnection()) } + } + + @Test + fun `a cancel after the request attached drops its connection`() { + val handle = McpCallHandle() + val conn = FakeConnection() + handle.attach(conn) + + handle.cancel() + + assertEquals(1, conn.disconnects) + assertTrue(handle.isCancelled) + } + + @Test + fun `a cancel after the request attached is caught before it sends anything`() { + val handle = McpCallHandle() + handle.attach(FakeConnection()) + + handle.cancel() + + assertThrows(InterruptedIOException::class.java) { handle.throwIfCancelled() } + } + + @Test + fun `a request not cancelled goes ahead`() { + val handle = McpCallHandle() + handle.attach(FakeConnection()) + + handle.throwIfCancelled() + + assertFalse(handle.isCancelled) + } + + @Test + fun `a cancel after the request ended drops nothing`() { + val handle = McpCallHandle() + val conn = FakeConnection() + handle.attach(conn) + handle.detach() + + handle.cancel() + + assertEquals("a finished request's connection may be back in the pool", 0, conn.disconnects) + } + + @Test + fun `a disconnect that fails with an Exception is survived`() { + val handle = McpCallHandle() + handle.attach(FakeConnection(IllegalStateException("already closed"))) + + handle.cancel() + + assertTrue(handle.isCancelled) + } + + @Test + fun `an OutOfMemoryError from the disconnect reaches the caller`() { + val handle = McpCallHandle() + handle.attach(FakeConnection(OutOfMemoryError("disconnecting"))) + + assertThrows(OutOfMemoryError::class.java) { handle.cancel() } + } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSessionLifecycleTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSessionLifecycleTest.kt index 085a6f274..ef0bf7df5 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSessionLifecycleTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/McpSessionLifecycleTest.kt @@ -79,6 +79,7 @@ class McpSessionLifecycleTest { protocolVersion: String?, extraHeaders: Map, onConnected: (HttpURLConnection) -> Unit, + beforeSend: () -> Unit, exchangeListener: McpExchangeListener, ): Response { val method = body.optString("method") diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/MovedServerCredentialTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/MovedServerCredentialTest.kt new file mode 100644 index 000000000..1083e336e --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/client/MovedServerCredentialTest.kt @@ -0,0 +1,105 @@ +package com.itsaky.androidide.plugins.aiagentmcp.client + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServer +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpToolCatalog +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Before +import org.junit.Test + +/** + * A server of the user's moved to another URL never hands the credentials entered for the new URL + * to the old one. + * + * The settings pane stored the new URL, token and headers, and only then ended the old session. Its + * DELETE read the server's credentials without asking which URL they were for, so it went to the + * old URL with the new token and headers; so did any request of the old session still running. + * The credentials are now released only to a session built for the URL the server has, the rule a + * SQLite debugger entry already followed. + * + * The save now takes the old session out before it writes, so that session's DELETE carries the + * old credentials (SaveServerSessionTest). The rule still holds for any session of the old URL + * ended once the server has moved: one a call stored between that take-out and the write, which the + * next lookup replaces, and every request still running on the old session. + */ +class MovedServerCredentialTest { + + private val old = FakeMcpServer("", listOf(tool("search", true)), sessionId = "old-session") + private val moved = FakeMcpServer("new-token", listOf(tool("search", true))) + + @Volatile private var token = "old-token" + @Volatile private var headers = mapOf("X-Team" to "old") + + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + // The Keystore is not there on the JVM: the store answers what the user last entered. + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } answers { KeystoreSecretStore.Stored.Value(token) } + every { McpServerStore.headers(any()) } answers { headers } + } + + @After + fun tearDown() { + McpConnections.closeAll() + McpToolCatalog.clear() + old.stop() + moved.stop() + plugin.dispose() + unmockkObject(McpServerStore) + } + + @Test + fun `the old session's DELETE carries none of the credentials entered for the new URL`() { + val saved = McpServerStore.saveDetails(McpServerStore.newServer("Docs", url(old))) + McpConnections.withSession(saved) { it.initialize() } + assertEquals("the old session did not carry the old token", "Bearer old-token", old.requests.first().authorization) + + moveToTheNewUrl(saved) + McpConnections.invalidate(saved.id) + + val delete = old.requests.single { it.httpMethod == "DELETE" } + assertNull("the old URL was sent a token", delete.authorization) + assertFalse("the old URL was sent the user's headers", "x-team" in delete.headerNames) + } + + @Test + fun `a request of the old session after the move carries none of the new credentials`() { + val saved = McpServerStore.saveDetails(McpServerStore.newServer("Docs", url(old))) + val session = McpConnections.withSession(saved) { it.also { kept -> kept.initialize() } } + + moveToTheNewUrl(saved) + session.listTools() + + val listing = old.requests.last() + assertEquals("POST", listing.httpMethod) + assertNull("the old URL was sent a token", listing.authorization) + assertFalse("the old URL was sent the user's headers", "x-team" in listing.headerNames) + } + + /** What the settings pane's save stores; a session of the old URL is ended after it. */ + private fun moveToTheNewUrl(saved: McpServer) { + McpServerStore.saveDetails(saved.copy(url = url(moved))) + token = "new-token" + headers = mapOf("X-Team" to "new") + } + + private fun url(server: FakeMcpServer) = "http://127.0.0.1:${server.port}/mcp" +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/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..633e3732b --- /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.withSession(AutomaticServers.servers().single()) { it } + session.listTools() + assertTrue("the session opened against the old endpoint", old.requests.any { it.httpMethod == "POST" }) + + stored = listOf(AutomaticEndpoint(app, replacement.port, "new-token")) + assertTrue(AutomaticServers.refresh()) + McpConnections.withSession(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..82e3b051b --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AppToolNamesTest.kt @@ -0,0 +1,181 @@ +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()) + } + + /** + * `com.a.db` and `com.d.db` share `db_db`, and `com.a.db`'s digest form is `db_ec81`, the plain + * prefix of `com.c.ec81`. Were both to take it, the numbering that keeps tool names apart would + * give `_2` to whichever app was read second, and a reordered read would hand `db_ec81_query` + * to the other app's database. + */ + @Test + fun `an app whose digest prefix is another app's plain prefix keeps its names whatever the row order`() { + val apps = listOf("com.a.db", "com.d.db", "com.c.ec81") + connectAll(*apps.map { it to fake(it, tool("query", true)) }.toTypedArray()) + val forward = byApp() + assertEquals(apps.toSet(), forward.keys) + assertEquals("db_ec81_query", forward.getValue("com.c.ec81").first) + assertEquals(3, forward.values.map { it.first }.toSet().size) + + AutomaticServers.install(null) + McpToolCatalog.clear() + servers.forEach { it.stop() } + servers.clear() + connectAll(*apps.map { it to fake(it, tool("query", true)) }.toTypedArray(), reversed = true) + + assertEquals(forward, byApp()) + } + + @Test + fun `an app listed between two reads of the server list cannot break the listing`() { + connectAll( + "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..0807382cd --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServersTest.kt @@ -0,0 +1,358 @@ +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) + } + + /** + * The plugin registers its endpoint listener on activation, before it installs the source, and + * lists every entry itself straight after the install. A listener told of each entry by the + * install's read would list each one a second time. + */ + @Test + fun `the install's first read tells no endpoint listener and a later change does`() { + var current = listOf(endpoint(), endpoint(app = "com.example.other", port = 4001)) + val asked = mutableListOf() + val listener: (String) -> Unit = { asked += it } + AutomaticServers.addEndpointListener(listener) + try { + AutomaticServers.install { current } + assertEquals(2, AutomaticServers.servers().size) + assertEquals("the install's read told the listener", emptyList(), asked) + + current = listOf(endpoint(port = 4002, token = "t2"), endpoint(app = "com.example.other", port = 4001)) + AutomaticServers.refresh() + assertEquals(listOf(AutomaticServers.idFor("com.example.app")), asked) + } finally { + AutomaticServers.removeEndpointListener(listener) + } + } + + @Test + fun `a relaunch lets the probe ask an entry that had refused its credential`() { + var current = listOf(endpoint()) + 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..2773fc34c --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/CancelBetweenAttemptsTest.kt @@ -0,0 +1,109 @@ +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.CountDownLatch +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + + +/** A 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 executor = Executors.newSingleThreadExecutor() + private val source = McpToolSource(executor) + 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 + // invoke stores the call's future only after its worker has started, and a cancel that + // landed first would find no future to cancel: the outcome would come back as an ordinary + // failure, which is not what this test is about. So the cancel waits for invoke to return. + val invoked = CountDownLatch(1) + AutomaticServers.install { + if (cancelOnRead) { + check(invoked.await(10, TimeUnit.SECONDS)) { "invoke never returned" } + 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) + invoked.countDown() + + // The agent's future is cancelled with the call; the worker behind it is what must stop. + // Waits for the worker itself, so whatever it was going to send has been sent. + executor.shutdown() + assertTrue("the call never finished", executor.awaitTermination(10, TimeUnit.SECONDS)) + assertTrue(future.isCompletedExceptionally) + assertTrue("the retry was sent anyway: ${second.requests}", second.requests.isEmpty()) + } +} 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..6301ddfc4 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReadOnlyHintParsingTest.kt @@ -0,0 +1,82 @@ +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, + beforeSend: () -> 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/RemovedEntryCleanupTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/RemovedEntryCleanupTest.kt new file mode 100644 index 000000000..7444bee6c --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/RemovedEntryCleanupTest.kt @@ -0,0 +1,132 @@ +package com.itsaky.androidide.plugins.aiagentmcp.debugger + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpServerHealth +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpToolCatalog +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicReference +import kotlin.concurrent.thread +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * A read that finds an app gone forgets that entry's health and ends its session. A later read can + * restore the app, at a new endpoint, before the first read has finished; what the first read + * forgets is the entry it removed, never the one that replaced it under the same id. + */ +class RemovedEntryCleanupTest { + + private val servers = mutableListOf() + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + // The Keystore is not there on the JVM; nothing here reads a hand-added server's secrets. + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } returns KeystoreSecretStore.Stored.Absent + every { McpServerStore.headers(any()) } returns emptyMap() + } + + @After + fun tearDown() { + AutomaticServers.install(null) + McpConnections.closeAll() + McpToolCatalog.clear() + servers.forEach { it.stop() } + plugin.dispose() + unmockkObject(McpServerStore) + } + + private fun fake(token: String, toolName: String) = + FakeMcpServer(token, listOf(tool(toolName, true))).also { servers += it } + + /** + * Two apps go away in one read. That read is held by the health listener its first forgotten + * entry tells, so the second app's cleanup is still to come, while a newer read restores the + * second app at a new endpoint and the relisting connects to it. + */ + @Test + fun `a removal that finishes after the app came back leaves the new endpoint's health and session`() { + val appA = "com.example.a" + val appB = "com.example.b" + val a = fake("ta", "a_tool") + val b1 = fake("tb1", "b_tool") + val b2 = fake("tb2", "b_tool") + val stored = AtomicReference( + listOf(AutomaticEndpoint(appA, a.port, "ta"), AutomaticEndpoint(appB, b1.port, "tb1")) + ) + AutomaticServers.install { stored.get() } + AutomaticServers.servers().forEach { McpToolCatalog.connect(it) } + val idB = AutomaticServers.idFor(appB) + assertEquals(McpServerHealth.State.AVAILABLE, McpServerHealth.of(idB)?.state) + + val removingThread = AtomicReference() + val removalHeld = CountDownLatch(1) + val releaseRemoval = CountDownLatch(1) + val holdRemoval: () -> Unit = { + if (Thread.currentThread() === removingThread.get() && removalHeld.count > 0) { + removalHeld.countDown() + releaseRemoval.await(10, TimeUnit.SECONDS) + } + } + McpServerHealth.addChangeListener(holdRemoval) + try { + stored.set(emptyList()) + val removal = thread(start = false) { AutomaticServers.refresh() } + removingThread.set(removal) + removal.start() + assertTrue("the removal never forgot anything", removalHeld.await(10, TimeUnit.SECONDS)) + assertNull("the removal stored nothing", AutomaticServers.endpoint(idB)) + + stored.set(listOf(AutomaticEndpoint(appB, b2.port, "tb2"))) + assertTrue(AutomaticServers.refresh()) + val restored = AutomaticServers.servers().single() + McpToolCatalog.connect(restored) + val session = McpConnections.withSession(restored) { it } + + releaseRemoval.countDown() + removal.join(10_000) + assertFalse("the removal never finished", removal.isAlive) + + assertEquals( + "the removal forgot the new endpoint's tools", + listOf("b_tool"), + McpToolCatalog.tools(idB).map { it.name }, + ) + assertEquals( + "the removal forgot the new endpoint's health", + McpServerHealth.State.AVAILABLE, + McpServerHealth.of(idB)?.state, + ) + assertSame( + "the removal ended the new endpoint's session", + session, + McpConnections.withSession(restored) { it }, + ) + } finally { + releaseRemoval.countDown() + McpServerHealth.removeChangeListener(holdRemoval) + } + } +} 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/debugger/ReplacedEndpointListingTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReplacedEndpointListingTest.kt new file mode 100644 index 000000000..78195a7a9 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReplacedEndpointListingTest.kt @@ -0,0 +1,110 @@ +package com.itsaky.androidide.plugins.aiagentmcp.debugger + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpToolCatalog +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicReference +import kotlin.concurrent.thread +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * Two listings of one SQLite debugger entry can overlap: the probe's, of the endpoint it read, and + * the relisting a relaunch starts, of the endpoint that replaced it. Whichever records last, the + * tools the agent is offered are the ones the current endpoint listed. + */ +class ReplacedEndpointListingTest { + + private val app = "com.example.app" + private val servers = mutableListOf() + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + // The Keystore is not there on the JVM; nothing here reads a hand-added server's secrets. + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } returns KeystoreSecretStore.Stored.Absent + every { McpServerStore.headers(any()) } returns emptyMap() + } + + @After + fun tearDown() { + AutomaticServers.install(null) + McpConnections.closeAll() + McpToolCatalog.clear() + servers.forEach { it.stop() } + plugin.dispose() + unmockkObject(McpServerStore) + } + + private fun fake(token: String, toolName: String) = + FakeMcpServer(token, listOf(tool(toolName, true))).also { servers += it } + + /** + * The old endpoint's listing passes its endpoint check and is held there, by the change + * listener its own record calls, until the new endpoint has listed and recorded. + */ + @Test + fun `a replaced endpoint's listing that finishes last leaves the new endpoint's tools`() { + val first = fake("t1", "old_tool") + val second = fake("t2", "new_tool") + val stored = AtomicReference(listOf(AutomaticEndpoint(app, first.port, "t1"))) + AutomaticServers.install { stored.get() } + val id = AutomaticServers.idFor(app) + val oldEntry = AutomaticServers.servers().single() + + val olderThread = AtomicReference() + val olderRecorded = CountDownLatch(1) + val releaseOlder = CountDownLatch(1) + val holdOlder: () -> Unit = { + if (Thread.currentThread() === olderThread.get() && olderRecorded.count > 0) { + olderRecorded.countDown() + releaseOlder.await(10, TimeUnit.SECONDS) + } + } + AutomaticServers.addChangeListener(holdOlder) + try { + val older = thread(start = false) { McpToolCatalog.connect(oldEntry) } + olderThread.set(older) + older.start() + assertTrue("the old endpoint's listing never recorded", olderRecorded.await(10, TimeUnit.SECONDS)) + + stored.set(listOf(AutomaticEndpoint(app, second.port, "t2"))) + assertTrue(AutomaticServers.refresh()) + McpToolCatalog.connect(AutomaticServers.servers().single()) + + releaseOlder.countDown() + older.join(10_000) + assertFalse("the old endpoint's listing never finished", older.isAlive) + + assertEquals( + "the replaced endpoint's listing overwrote the new endpoint's tools", + listOf("new_tool"), + McpToolCatalog.tools(id).map { it.name }, + ) + assertEquals(listOf("new_tool"), AutomaticServers.servers().single().knownTools) + } finally { + releaseOlder.countDown() + AutomaticServers.removeChangeListener(holdOlder) + } + } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpErrorFormatterTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpErrorFormatterTest.kt index 76a8cccf0..bd31476f0 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpErrorFormatterTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpErrorFormatterTest.kt @@ -3,6 +3,7 @@ package com.itsaky.androidide.plugins.aiagentmcp.errors import com.itsaky.androidide.plugins.aiagentmcp.client.McpProtocolException import com.itsaky.androidide.plugins.aiagentmcp.security.UnavailableSecretException import com.itsaky.androidide.plugins.aiagentmcp.security.UnreadableSecretException +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServer import com.itsaky.androidide.plugins.aiagentmcp.transport.McpCleartextException import com.itsaky.androidide.plugins.aiagentmcp.transport.McpCredential import com.itsaky.androidide.plugins.aiagentmcp.transport.McpHttpException @@ -123,7 +124,8 @@ class McpErrorFormatterTest { @Test fun givenNoPluginContext_whenFormatted_thenTheUserStillGetsASentence() { - val message = McpErrorFormatter.format(null, "Docs", IOException("socket closed")) + val server = McpServer(id = "docs", name = "Docs", url = "https://docs.example/mcp") + val message = McpErrorFormatter.format(null, server, IOException("socket closed")) assertTrue(message.contains("Docs")) assertTrue(message.contains("socket closed")) diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormatTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormatTest.kt index 83eae0ba0..b1902b744 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormatTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpLogFormatTest.kt @@ -1,7 +1,11 @@ package com.itsaky.androidide.plugins.aiagentmcp.errors +import com.itsaky.androidide.plugins.aiagentmcp.transport.JsonDepth import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows import org.junit.Assert.assertTrue import org.junit.Test @@ -58,4 +62,92 @@ class McpLogFormatTest { assertEquals(capped, McpLogFormat.pretty(capped)) } + + @Test + fun givenAnExceptionWhileIndenting_whenFormatted_thenTheBodyIsNotJson() { + assertNull(McpLogFormat.json("{\"a\":1}") { throw IllegalStateException("bad") }) + } + + @Test + fun givenAnOutOfMemoryErrorWhileIndenting_whenFormatted_thenItPropagates() { + assertThrows(OutOfMemoryError::class.java) { + McpLogFormat.json("{\"a\":1}") { throw OutOfMemoryError("indenting") } + } + } + + @Test + fun givenTenThousandNestedBrackets_whenFormatted_thenItIsNotJsonAndNothingThrows() { + assertNull(McpLogFormat.json("[".repeat(10_000))) + } + + /** + * Android's org.json recurses once per level with no limit of its own and catches nothing, so + * such a body overflows the stack there, and the StackOverflowError propagates. The org.json + * these tests run on turns an overflow while parsing into a JSONException, so the real parser + * cannot show it here; a parser that recurses the same way, on a thread with a small stack, + * stands in for Android's. + */ + @Test + fun givenTenThousandNestedBrackets_whenFormatted_thenNoParserRecursesThroughThem() { + val deep = "[".repeat(10_000) + var result: String? = "never ran" + var thrown: Throwable? = null + val parsing = Thread(null, { + try { + result = McpLogFormat.json(deep, ::recursiveIndent) + } catch (t: Throwable) { + thrown = t + } + }, "small-stack", SMALL_STACK_BYTES) + parsing.start() + parsing.join(10_000) + + assertNull("formatting the body threw $thrown", thrown) + assertNull(result) + } + + @Test + fun givenNestingAtTheLimit_whenFormatted_thenItIsIndented() { + val depth = JsonDepth.MAX + assertNotNull(McpLogFormat.json("[".repeat(depth) + "]".repeat(depth))) + } + + @Test + fun givenNestingOneLevelPastTheLimit_whenFormatted_thenItIsShownAsItCame() { + val depth = JsonDepth.MAX + 1 + val body = "{\"a\":" + "[".repeat(depth - 1) + "]".repeat(depth - 1) + "}" + + assertNull(McpLogFormat.json(body)) + assertEquals(body, McpLogFormat.pretty(body)) + } + + @Test + fun givenBracketsInsideStrings_whenFormatted_thenTheyDoNotCount() { + val brackets = "[".repeat(500) + // An escaped quote at the start of "b" and an escaped backslash at its end: neither ends it. + val body = """{"a":"$brackets","b":"\"$brackets\\","c":["$brackets"]}""" + + assertNotNull("brackets inside strings were counted", McpLogFormat.json(body)) + } + + @Test + fun givenABodyThatIsNotStrictJson_whenFormatted_thenItIsShownAsItCame() { + val body = """{"jsonrpc":"2.0","id":2,"result":{}} // done""" + + assertNull(McpLogFormat.json(body)) + assertEquals(body, McpLogFormat.pretty(body)) + } + + /** Descends once per opening bracket at the start of [text], as a recursive-descent parser does. */ + private fun recursiveIndent(text: String): String? { + fun descend(index: Int): Int = + if (index < text.length && (text[index] == '[' || text[index] == '{')) descend(index + 1) + 1 else 0 + descend(0) + return text + } + + private companion object { + /** Far less than 10,000 frames need, whatever the JIT makes of them. */ + const val SMALL_STACK_BYTES = 128L * 1024 + } } diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpTranscriptTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpTranscriptTest.kt index 08de3e998..837f3fb79 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpTranscriptTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/McpTranscriptTest.kt @@ -16,6 +16,7 @@ class McpTranscriptTest { override fun hidden(length: Int) = "<$length hidden>" override fun omitted(count: Int) = "<$count more>" override val nothingSent = "" + override val cancelled = "" } private fun exchange( diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/RecoverableTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/RecoverableTest.kt new file mode 100644 index 000000000..ecb910426 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/errors/RecoverableTest.kt @@ -0,0 +1,33 @@ +package com.itsaky.androidide.plugins.aiagentmcp.errors + +import kotlin.coroutines.cancellation.CancellationException +import org.junit.Assert.assertEquals +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Test + +/** What [runCatchingRecoverable] keeps as a failure and what it lets through. */ +class RecoverableTest { + + @Test + fun `a cancellation is rethrown, not kept as a failure`() { + val thrown = assertThrows(CancellationException::class.java) { + runCatchingRecoverable { throw CancellationException("the coroutine was cancelled") } + } + + assertEquals("the coroutine was cancelled", thrown.message) + } + + @Test + fun `an exception and a linkage error are kept as failures`() { + assertTrue(runCatchingRecoverable { throw IllegalStateException("a host call") }.isFailure) + assertTrue(runCatchingRecoverable { throw AbstractMethodError("a host call") }.isFailure) + } + + @Test + fun `an OutOfMemoryError is let through`() { + assertThrows(OutOfMemoryError::class.java) { + runCatchingRecoverable { throw OutOfMemoryError("the process") } + } + } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/AutomaticSessionCloseTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/AutomaticSessionCloseTest.kt new file mode 100644 index 000000000..83b3e0a49 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/AutomaticSessionCloseTest.kt @@ -0,0 +1,101 @@ +package com.itsaky.androidide.plugins.aiagentmcp.plugin + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticEndpoint +import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticServers +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpToolCatalog +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import com.itsaky.androidide.plugins.services.DebuggerEndpointService +import com.itsaky.androidide.plugins.services.ToolSourceRegistry +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import java.util.concurrent.atomic.AtomicReference +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Before +import org.junit.Test + +/** + * The DELETE that ends a SQLite debugger entry's session carries the entry's token, whether the + * plugin is deactivated or the entry's app goes away, as when its project is closed. + * + * The app's MCP server refuses a DELETE without the token, and the session stays open. Both + * DELETEs read the token when they were sent, and by then it had gone: a deactivation clears the + * entries before it ends the sessions, outside its lock, and a removed entry has left the list + * before its session is ended. The token is now read as each session is taken out, from the entry + * as it is removed. + */ +class AutomaticSessionCloseTest { + + /** Asks for the token on every request but a DELETE, and records each with its Authorization. */ + private val server = FakeMcpServer(TOKEN, listOf(tool("query", true)), sessionId = "session-1") + + private val stored = AtomicReference(listOf(AutomaticEndpoint(APP, server.port, TOKEN))) + + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + // The entry is installed by the test, not read from the host. + every { context.services.get(DebuggerEndpointService::class.java) } returns null + every { context.getPluginService(any(), ToolSourceRegistry::class.java) } returns null + plugin = McpPlugin().also { it.initialize(context) } + // The Keystore is not there on the JVM; nothing here reads a hand-added server's secrets. + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } returns KeystoreSecretStore.Stored.Absent + every { McpServerStore.headers(any()) } returns emptyMap() + } + + @After + fun tearDown() { + AutomaticServers.install(null) + McpConnections.closeAll() + McpToolCatalog.clear() + plugin.dispose() + server.stop() + unmockkObject(McpServerStore) + } + + /** Installs the entry and lists it, which leaves it a session with a server-side id. */ + private fun connectEntry() { + AutomaticServers.install { stored.get() } + McpToolCatalog.connect(AutomaticServers.servers().single()) + } + + private fun deleteAuthorizations() = + server.requests.filter { it.httpMethod == "DELETE" }.map { it.authorization } + + @Test + fun `a deactivation's DELETE for a SQLite debugger entry carries the entry's token`() { + plugin.activate() + connectEntry() + + plugin.deactivate() + + assertEquals("the DELETE ending the entry's session", listOf("Bearer $TOKEN"), deleteAuthorizations()) + } + + @Test + fun `the DELETE when an entry's app goes away carries the entry's token`() { + connectEntry() + + stored.set(emptyList()) + AutomaticServers.refresh() + + assertEquals("the DELETE ending the entry's session", listOf("Bearer $TOKEN"), deleteAuthorizations()) + } + + private companion object { + const val APP = "com.example.notes" + const val TOKEN = "t1" + } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/ConcurrentLifecycleTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/ConcurrentLifecycleTest.kt new file mode 100644 index 000000000..19ef53130 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/ConcurrentLifecycleTest.kt @@ -0,0 +1,152 @@ +package com.itsaky.androidide.plugins.aiagentmcp.plugin + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.PluginLifecycleListener +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.aiagentmcp.testing.awaitFinishedOrBlockedBy +import com.itsaky.androidide.plugins.services.SharedServices +import com.itsaky.androidide.plugins.services.ToolSourceRegistry +import io.mockk.every +import io.mockk.mockk +import io.mockk.slot +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import kotlin.concurrent.thread +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * A deactivation that arrives while the tool source is being registered waits for the registration + * and then undoes it, rather than running alongside it. + * + * The registration used to run unguarded against [McpPlugin.deactivate]: the deactivation found + * nothing registered yet, closed the tool source and cleared it, and the registration then + * finished. AI Core was left holding a closed source, whose every call fails with a + * RejectedExecutionException. The same held for `toolSource = toolSource ?: McpToolSource()`, + * a read and a write a teardown could fall between. The lifecycle calls, and the registration AI + * Core's activation triggers, now share one lock. + * + * The registry holds each registration on a latch. The deactivation runs on another thread, and the + * test waits until it has either finished or is blocked on a lock the registering thread holds: + * no sleeps, and no outcome that depends on timing. + */ +class ConcurrentLifecycleTest { + + /** What the registry holds now. */ + private val registered = CopyOnWriteArrayList() + + /** Every source ever registered and every one unregistered, in order, so a test can tell + * that the registration happened and that the deactivation undid that very source. */ + private val registrations = CopyOnWriteArrayList() + private val unregistrations = CopyOnWriteArrayList() + + /** What the worker threads threw, which a thread would otherwise only print. */ + private val failures = CopyOnWriteArrayList() + + private val registering = CountDownLatch(1) + private val releaseRegistration = CountDownLatch(1) + + /** Matches by identity, as AI Core's does; a registration waits on [releaseRegistration]. */ + private val registry = object : ToolSourceRegistry { + override fun getToolSources(): List = registered.toList() + + override fun notifyToolsChanged(providerId: String) = Unit + + override fun registerToolSource(source: ToolSourceRegistry.ToolSource) { + registering.countDown() + assertTrue("the test never released the registration", releaseRegistration.await(10, TimeUnit.SECONDS)) + registrations += source + registered += source + } + + override fun unregisterToolSource(source: ToolSourceRegistry.ToolSource) { + unregistrations += source + registered.removeAll { it === source } + } + } + + private val lifecycleListener = slot() + private lateinit var context: PluginContext + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + every { context.addPluginLifecycleListener(capture(lifecycleListener)) } returns Unit + every { context.getPluginService(any(), ToolSourceRegistry::class.java) } returns null + plugin = McpPlugin().also { it.initialize(context) } + } + + @After + fun tearDown() { + releaseRegistration.countDown() + plugin.dispose() + SharedServices.unregister(ToolSourceRegistry::class.java) + } + + @Test + fun `a deactivate that arrives while activate registers the tool source leaves none registered`() { + SharedServices.register(ToolSourceRegistry::class.java, registry) + + val activating = worker("activating") { plugin.activate() } + assertTrue("activate never registered the tool source", registering.await(10, TimeUnit.SECONDS)) + val deactivating = worker("deactivating") { plugin.deactivate() } + awaitFinishedOrBlockedBy(deactivating, activating) + releaseRegistration.countDown() + activating.join(10_000) + deactivating.join(10_000) + + assertFalse("activate never finished", activating.isAlive) + assertFalse("deactivate never finished", deactivating.isAlive) + assertEquals("a tool source is still registered after the deactivate", 0, registered.size) + assertEquals("a worker failed: $failures", emptyList(), failures.toList()) + assertEquals("the tool source was not registered exactly once", 1, registrations.size) + assertEquals("the deactivation did not unregister the registered source", 1, unregistrations.size) + assertTrue("the unregistered source is not the registered one", unregistrations.single() === registrations.single()) + } + + @Test + fun `a deactivate that arrives while AI Core's activation registers the tool source leaves none registered`() { + // AI Core is not active yet: activate registers nothing and leaves it to the listener. + plugin.activate() + assertEquals(0, registered.size) + SharedServices.register(ToolSourceRegistry::class.java, registry) + + val registeringThread = worker("ai-core-activated") { + lifecycleListener.captured.onPluginActivated(AI_CORE_PLUGIN_ID) + } + assertTrue("the listener never registered the tool source", registering.await(10, TimeUnit.SECONDS)) + val deactivating = worker("deactivating") { plugin.deactivate() } + awaitFinishedOrBlockedBy(deactivating, registeringThread) + releaseRegistration.countDown() + registeringThread.join(10_000) + deactivating.join(10_000) + + assertFalse("the registration never finished", registeringThread.isAlive) + assertFalse("deactivate never finished", deactivating.isAlive) + assertEquals("a tool source is still registered after the deactivate", 0, registered.size) + assertEquals("a worker failed: $failures", emptyList(), failures.toList()) + assertEquals("the tool source was not registered exactly once", 1, registrations.size) + assertEquals("the deactivation did not unregister the registered source", 1, unregistrations.size) + assertTrue("the unregistered source is not the registered one", unregistrations.single() === registrations.single()) + } + + /** A thread running [block] that records what it throws in [failures]. */ + private fun worker(name: String, block: () -> Unit): Thread = thread(name = name) { + try { + block() + } catch (e: Throwable) { + failures += e + } + } + + private companion object { + const val AI_CORE_PLUGIN_ID = "com.itsaky.androidide.plugins.aicore" + } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/DoubleActivateToolSourceTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/DoubleActivateToolSourceTest.kt new file mode 100644 index 000000000..a2c31fe21 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/DoubleActivateToolSourceTest.kt @@ -0,0 +1,64 @@ +package com.itsaky.androidide.plugins.aiagentmcp.plugin + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.services.SharedServices +import com.itsaky.androidide.plugins.services.ToolSourceRegistry +import io.mockk.every +import io.mockk.mockk +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Test + +/** + * A host that activates the plugin twice and then deactivates it leaves no tool source registered. + * + * The second activation used to build a new tool source. The first was already registered, so the + * new one never was, and deactivation unregistered the new one: AI Core's registry matches by + * identity, so the first stayed registered, and it was never closed. The registry here matches the + * same way. + */ +class DoubleActivateToolSourceTest { + + /** What the registry holds now. */ + private val registered = mutableListOf() + + /** Every source ever registered, in order. */ + private val everRegistered = mutableListOf() + + private val registry = mockk(relaxed = true) { + every { registerToolSource(any()) } answers { + val source = firstArg() + registered.removeAll { it.providerId == source.providerId } + registered += source + everRegistered += source + } + every { unregisterToolSource(any()) } answers { + val source = firstArg() + registered.removeAll { it === source } + } + } + + @After + fun tearDown() { + SharedServices.unregister(ToolSourceRegistry::class.java) + } + + @Test + fun `activate, activate, deactivate leaves no tool source registered`() { + SharedServices.register(ToolSourceRegistry::class.java, registry) + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + val plugin = McpPlugin().also { it.initialize(context) } + try { + plugin.activate() + plugin.activate() + plugin.deactivate() + + assertEquals("tool sources still registered after deactivate", 0, registered.size) + assertEquals("the second activation registered another source", 1, everRegistered.size) + } finally { + plugin.dispose() + } + } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/LifecycleSessionCloseTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/LifecycleSessionCloseTest.kt new file mode 100644 index 000000000..cd20ae9ae --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/LifecycleSessionCloseTest.kt @@ -0,0 +1,204 @@ +package com.itsaky.androidide.plugins.aiagentmcp.plugin + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.aiagentmcp.testing.awaitFinishedOrBlockedBy +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpServerHealth +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpToolCatalog +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import com.itsaky.androidide.plugins.services.ToolSourceRegistry +import com.sun.net.httpserver.HttpServer +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import java.net.InetSocketAddress +import java.util.concurrent.CountDownLatch +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import kotlin.concurrent.thread +import org.json.JSONArray +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * A deactivation ends its sessions after it has let go of the lifecycle lock, so an activation + * arriving meanwhile does not wait for them. + * + * Each session's close sends a DELETE, and can first wait, up to about 70 s, for a handshake in + * flight to let go of the session. The teardown used to close the sessions under the lock that + * serialises the lifecycle calls, so an activate, or AI Core's registration of the tool source, + * waited behind every DELETE. The teardown now only takes the sessions out under it. + * + * The server holds the DELETE on a latch; the activation runs on another thread, and the test + * waits until it has finished or is blocked on a lock the deactivating thread holds. Nothing + * sleeps. + */ +class LifecycleSessionCloseTest { + + private val deleteArrived = CountDownLatch(1) + private val releaseDelete = CountDownLatch(1) + + /** Kept so [tearDown] can end it; an idle pool thread otherwise lives on for up to 60 s. */ + private val handlers = Executors.newCachedThreadPool() + + private val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply { + // Its own threads, so the held DELETE does not hold the next activation's listing. + executor = handlers + createContext("/mcp") { exchange -> + if (exchange.requestMethod == "DELETE") { + deleteArrived.countDown() + releaseDelete.await(10, TimeUnit.SECONDS) + exchange.sendResponseHeaders(200, -1) + exchange.close() + return@createContext + } + val request = JSONObject(exchange.requestBody.use { String(it.readBytes()) }) + if (!request.has("id")) { + exchange.sendResponseHeaders(202, -1) + } else { + val result = when (request.optString("method")) { + "initialize" -> JSONObject().put("protocolVersion", "2025-06-18") + else -> JSONObject().put("tools", JSONArray()) + } + val bytes = JSONObject().put("jsonrpc", "2.0").put("id", request.get("id")) + .put("result", result).toString().toByteArray() + exchange.responseHeaders.add("Content-Type", "application/json") + exchange.responseHeaders.add("Mcp-Session-Id", "session-1") + exchange.sendResponseHeaders(200, bytes.size.toLong()) + exchange.responseBody.use { it.write(bytes) } + } + exchange.close() + } + start() + } + + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + every { context.getPluginService(any(), ToolSourceRegistry::class.java) } returns null + plugin = McpPlugin().also { it.initialize(context) } + // The Keystore is not there on the JVM. + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } returns KeystoreSecretStore.Stored.Absent + every { McpServerStore.headers(any()) } returns emptyMap() + } + + @After + fun tearDown() { + releaseDelete.countDown() + plugin.dispose() + McpConnections.closeAll() + McpToolCatalog.clear() + server.stop(0) + handlers.shutdownNow() + unmockkObject(McpServerStore) + assertTrue("the HTTP handler threads outlived the test", handlers.awaitTermination(10, TimeUnit.SECONDS)) + } + + @Test + fun `an activate arriving while a deactivation ends its sessions does not wait for them`() { + val saved = McpServerStore.saveDetails( + McpServerStore.newServer("Docs", "http://127.0.0.1:${server.address.port}/mcp") + ) + plugin.activate() + // A session with a server-side id, so ending it sends the DELETE the server holds. + McpConnections.withSession(saved) { it.initialize() } + + val deactivating = thread(name = "deactivating") { plugin.deactivate() } + assertTrue("the deactivation never sent its DELETE", deleteArrived.await(10, TimeUnit.SECONDS)) + val activating = thread(name = "activating") { plugin.activate() } + val state = awaitFinishedOrBlockedBy(activating, deactivating) + releaseDelete.countDown() + activating.join(10_000) + deactivating.join(10_000) + + assertEquals("activate waited for the deactivation's DELETE", Thread.State.TERMINATED, state) + assertFalse("deactivate never finished", deactivating.isAlive) + } + + /** + * An activate that runs after a deactivation has taken its sessions out, and before that + * deactivation has ended them, leaves them to it: it neither ends them nor waits for them. + * + * The sessions taken out were kept in one list that every lifecycle call emptied once it had + * let go of the lock. An activate taking the lock in that window emptied it, ended the + * deactivation's sessions itself, and waited for their DELETEs, up to about 70 s each. Each + * lifecycle call now ends only the sessions its own teardown took out. + * + * A health listener holds the deactivation at its teardown's last steps, after the sessions are + * taken out, in a wait on the lifecycle lock, which lets that lock go: the window, opened for as + * long as the test needs. The lock is internal for this test. Nothing sleeps. + */ + @Test + @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") // wait and notifyAll on the lock's own monitor + fun `an activate between a deactivation's teardown and its DELETEs leaves the sessions to it`() { + val saved = McpServerStore.saveDetails( + McpServerStore.newServer("Docs", "http://127.0.0.1:${server.address.port}/mcp") + ) + plugin.activate() + McpConnections.withSession(saved) { it.initialize() } + // A health row, so the teardown's clearing of the cache tells the health listeners. + McpServerHealth.available(saved.id) + val lock = plugin.lifecycleLock as java.lang.Object + val held = CountDownLatch(1) + var resume = false + val hold = { + if (Thread.currentThread().name == "deactivating" && held.count > 0) { + synchronized(lock) { + held.countDown() + while (!resume) lock.wait() + } + } + } + McpServerHealth.addChangeListener(hold) + // Outside the try, so the finally can reach them when an assertion fails part way. + var deactivating: Thread? = null + var activating: Thread? = null + try { + deactivating = thread(name = "deactivating") { plugin.deactivate() } + assertTrue("the deactivation's teardown never took its sessions out", held.await(10, TimeUnit.SECONDS)) + activating = thread(name = "activating") { plugin.activate() } + // Whichever comes first: the activate ending, or a DELETE sent while the deactivation is held. + val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10) + while (activating.isAlive && deleteArrived.count > 0 && System.nanoTime() < deadline) activating.join(10) + val endedByActivate = deleteArrived.count == 0L + val activateEnded = !activating.isAlive + synchronized(lock) { + resume = true + lock.notifyAll() + } + val endedByDeactivate = deleteArrived.await(10, TimeUnit.SECONDS) + releaseDelete.countDown() + activating.join(10_000) + deactivating.join(10_000) + + assertFalse("activate ended the sessions the deactivation took out", endedByActivate) + assertTrue("activate did not end", activateEnded) + assertTrue("the deactivation never ended its own session", endedByDeactivate) + assertFalse("deactivate never finished", deactivating.isAlive) + } finally { + McpServerHealth.removeChangeListener(hold) + // Whatever failed above, the deactivating thread may still be waiting on the lock for + // `resume`, and it is not a daemon: left there, the failed assertion would hang the run + // instead of reporting it. + synchronized(lock) { + resume = true + lock.notifyAll() + } + releaseDelete.countDown() + deactivating?.join(10_000) + activating?.join(10_000) + } + } +} 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..6179ef778 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginDebuggerStartTest.kt @@ -0,0 +1,83 @@ +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 behind: nothing removes it after [McpPlugin.deactivate]. Nor does the read add + * or remove a listener: [McpPlugin.activate] owns that, so a late read cannot take away the + * listener of the activation that replaced its own. + */ +class McpPluginDebuggerStartTest { + + 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 touches 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 leaves the listener to activate`() { + val listeners = AutomaticServers.endpointListenerCount + release.countDown() + plugin.startDebuggerEntry { true } + + assertEquals(1, AutomaticServers.servers().size) + assertEquals(listeners, 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..620025764 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginHostErrorTest.kt @@ -0,0 +1,254 @@ +package com.itsaky.androidide.plugins.aiagentmcp.plugin + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.PluginLogger +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticEndpoint +import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticServers +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 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.assertFalse +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) + } + + /** Every listener registry the plugin registers with, so a test can see one left behind. */ + private fun listenerCounts() = mapOf( + "AutomaticServers change" to AutomaticServers.changeListenerCount, + "AutomaticServers endpoint" to AutomaticServers.endpointListenerCount, + "McpServerStore change" to McpServerStore.changeListenerCount, + "McpServerHealth change" to McpServerHealth.changeListenerCount, + ) + + /** + * The lifecycle listener is added after the scope has started and the change listeners are in. + * The Error used to escape activate, which caught only an Exception, and the host need not call + * deactivate after a failed activate: the scope and the listeners were left behind. Now the + * failure costs only the listener, as its removal's does in deactivate. + */ + @Test + fun `a lifecycle listener the host cannot add costs only that listener`() { + every { context.addPluginLifecycleListener(any()) } throws + AbstractMethodError("PluginContext.addPluginLifecycleListener") + val before = listenerCounts() + + val activated = survives("activate") { plugin.activate() } + + assertTrue("the activation must carry on", activated) + assertTrue("the activation's scope must be live", requireNotNull(plugin.scopeJob).isActive) + assertEquals(before.mapValues { it.value + 1 }, listenerCounts()) + plugin.deactivate() + assertEquals(before, listenerCounts()) + } + + @Test + fun `an activation that fails with a linkage error leaves no scope and no listener behind`() { + assertFailedActivationLeavesNothing(AbstractMethodError("PluginLogger.info")) + } + + @Test + fun `an activation that fails with an exception leaves no scope and no listener behind`() { + assertFailedActivationLeavesNothing(IllegalStateException("PluginLogger.info")) + } + + /** + * Fails an activation after it has started its scope and registered its listeners, at the one + * host call left unguarded by then: the note that AI Core is not active yet. + * @param failure what that call throws. + */ + private fun assertFailedActivationLeavesNothing(failure: Throwable) { + val logger = mockk(relaxed = true) + every { context.logger } returns logger + every { context.getPluginService(any(), ToolSourceRegistry::class.java) } returns null + every { logger.info(match { it.contains("AI Core is not active") }) } throws failure + val before = listenerCounts() + + val activated = survives("activate") { plugin.activate() } + + assertFalse("a failed activation must say so", activated) + assertTrue("the failed activation's scope must be stopped", requireNotNull(plugin.activationJob).isCancelled) + assertEquals("listeners left behind", before, listenerCounts()) + } + + @Test + fun `an error that escapes a coroutine stops at the backstop, not at the IDE's handler`() { + val reached = CopyOnWriteArrayList() + 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/McpPluginListenerTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginListenerTest.kt new file mode 100644 index 000000000..e38801add --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPluginListenerTest.kt @@ -0,0 +1,71 @@ +package com.itsaky.androidide.plugins.aiagentmcp.plugin + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticServers +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpServerHealth +import io.mockk.every +import io.mockk.mockk +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Before +import org.junit.Test + +/** + * The plugin's four listeners, registered once however often the host activates it. + * + * The host can activate twice without a deactivation in between. A listener added twice and + * removed once stays registered after [McpPlugin.deactivate]: a change to the servers then tells + * the agent the tools changed although the plugin is off, and while it is on each endpoint change + * starts two tool listings. That the first endpoint read, which can outlive its activation, adds + * or removes no listener is [McpPluginDebuggerStartTest]'s. + */ +class McpPluginListenerTest { + + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + } + + @After + fun tearDown() { + plugin.dispose() + } + + /** Each registry's listener count, in a fixed order, so the assertions can name the registry. */ + private fun counts() = listOf( + AutomaticServers.changeListenerCount, + AutomaticServers.endpointListenerCount, + McpServerStore.changeListenerCount, + McpServerHealth.changeListenerCount, + ) + + private fun assertCounts(message: String, expected: List) { + val names = listOf( + "AutomaticServers change listeners", + "AutomaticServers endpoint listeners", + "McpServerStore change listeners", + "McpServerHealth change listeners", + ) + val actual = counts() + for (i in names.indices) assertEquals("${names[i]} $message", expected[i], actual[i]) + } + + @Test + fun `two activations register each listener once and one deactivation removes them all`() { + val before = counts() + + plugin.activate() + plugin.activate() + // Counted as soon as activate returns: it registers every listener before it launches anything. + assertCounts("after two activations", before.map { it + 1 }) + + plugin.deactivate() + assertCounts("after the deactivation", before) + } +} 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/plugin/TeardownFailureSessionTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/TeardownFailureSessionTest.kt new file mode 100644 index 000000000..bde31bd08 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/TeardownFailureSessionTest.kt @@ -0,0 +1,89 @@ +package com.itsaky.androidide.plugins.aiagentmcp.plugin + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticServers +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpToolCatalog +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Before +import org.junit.Test + +/** + * A lifecycle call whose teardown fails after it has taken the sessions out still ends them, and a + * disposal still lets go of the plugin context. + * + * The teardown returned the sessions it took out only once its last step had run. A step after + * the take-out that threw, clearing the SQLite debugger entries here, lost them: nothing ended + * them, so their servers kept them open. A disposal also skipped clearing the context. The + * sessions now go into the caller's list as they are taken out, and the caller ends them whatever + * the teardown threw. + */ +class TeardownFailureSessionTest { + + private val server = FakeMcpServer("", listOf(tool("search", true)), sessionId = "session-1") + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + // The Keystore is not there on the JVM. + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } returns KeystoreSecretStore.Stored.Absent + every { McpServerStore.headers(any()) } returns emptyMap() + val saved = McpServerStore.saveDetails( + McpServerStore.newServer("Docs", "http://127.0.0.1:${server.port}/mcp") + ) + McpConnections.withSession(saved) { it.initialize() } + // The teardown's last step, after the sessions are taken out. + mockkObject(AutomaticServers) + every { AutomaticServers.install(null) } throws IllegalStateException("clearing the entries failed") + } + + @After + fun tearDown() { + unmockkObject(AutomaticServers) + McpConnections.closeAll() + McpToolCatalog.clear() + server.stop() + plugin.dispose() + unmockkObject(McpServerStore) + } + + @Test + fun `a deactivation whose teardown fails after taking the sessions out still ends them`() { + assertFalse(plugin.deactivate()) + + assertEquals( + "the session taken out before the failing step was never ended", + 1, + server.requests.count { it.httpMethod == "DELETE" }, + ) + } + + @Test + fun `a disposal whose teardown fails still ends the sessions and lets go of the context`() { + assertThrows(IllegalStateException::class.java) { plugin.dispose() } + + assertEquals( + "the session taken out before the failing step was never ended", + 1, + server.requests.count { it.httpMethod == "DELETE" }, + ) + assertNull("the disposal kept the plugin context", McpPlugin.getContext()) + } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/ConfiguredCheckReadTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/ConfiguredCheckReadTest.kt new file mode 100644 index 000000000..78240ce4a --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/ConfiguredCheckReadTest.kt @@ -0,0 +1,67 @@ +package com.itsaky.androidide.plugins.aiagentmcp.settings + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.debugger.McpServers +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import io.mockk.clearMocks +import io.mockk.every +import io.mockk.mockk +import io.mockk.spyk +import io.mockk.verify +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * The check that a server is still configured, made under the health, catalog and session locks, + * reads no preferences, and so parses no stored JSON there. + * + * It read the stored server list and parsed every server's JSON on each call, under those locks; a + * SQLite debugger entry's refresh, which waits on two of them while holding its own, waited behind + * that read. The store now answers from the list it last read or wrote. + */ +class ConfiguredCheckReadTest { + + private val prefs = spyk(FakeSharedPreferences()) + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns prefs + plugin = McpPlugin().also { it.initialize(context) } + } + + @After + fun tearDown() { + plugin.dispose() + } + + @Test + fun `the configured check reads no preferences`() { + val saved = McpServerStore.saveDetails(McpServerStore.newServer("Docs", "http://127.0.0.1:1/mcp")) + clearMocks(prefs, answers = false, recordedCalls = true, childMocks = false) + + assertTrue(McpServers.isConfigured(saved)) + assertFalse(McpServers.isConfigured(saved.copy(url = "http://127.0.0.1:2/mcp"))) + + verify(exactly = 0) { prefs.getString(any(), any()) } + } + + @Test + fun `the list it answers from is the one last written`() { + val saved = McpServerStore.saveDetails(McpServerStore.newServer("", "http://127.0.0.1:1/mcp")) + val moved = McpServerStore.saveDetails(saved.copy(url = "http://127.0.0.1:2/mcp")) + + assertTrue(McpServers.isConfigured(moved)) + assertFalse(McpServers.isConfigured(saved)) + // As read back from the preferences: a blank name is the URL. + assertEquals("http://127.0.0.1:2/mcp", McpServerStore.server(saved.id)?.name) + McpServerStore.remove(saved.id) + assertFalse(McpServers.isConfigured(moved)) + } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/DeleteServerSessionTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/DeleteServerSessionTest.kt new file mode 100644 index 000000000..107ed5fec --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/DeleteServerSessionTest.kt @@ -0,0 +1,147 @@ +package com.itsaky.androidide.plugins.aiagentmcp.settings + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpToolCatalog +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * Deleting one of the user's servers leaves no session behind, even one a call stored while the + * deletion ran. + * + * The deletion ends the server's session first, so the DELETE still has the credentials that + * removing the server deletes. A call or a listing that looked the session up between the two + * stored a new one, for a server that was then gone, and nothing would ever end it. The session + * is now ended again once the server is gone. + * + * The lookup is made from inside the store's removal, just before it runs: the one point between + * the two steps. Nothing sleeps. + */ +class DeleteServerSessionTest { + + private lateinit var server: FakeMcpServer + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + // The Keystore is not there on the JVM. + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } returns KeystoreSecretStore.Stored.Absent + every { McpServerStore.headers(any()) } returns emptyMap() + server = FakeMcpServer("", listOf(tool("search", true)), sessionId = "session-1") + } + + @After + fun tearDown() { + McpConnections.closeAll() + McpToolCatalog.clear() + server.stop() + plugin.dispose() + unmockkObject(McpServerStore) + } + + @Test + fun `a session stored while the server was being deleted is ended with it`() { + val saved = McpServerStore.saveDetails( + McpServerStore.newServer("Docs", "http://127.0.0.1:${server.port}/mcp") + ) + McpConnections.withSession(saved) { it.initialize() } + var lookedUp = false + every { McpServerStore.remove(saved.id) } answers { + // A call landing between the two steps: its lookup stores a session for the server. + McpConnections.withSession(saved) { } + lookedUp = true + callOriginal() + } + + McpSettingsViewModel { null }.deleteNow(saved.id) + + assertTrue("the removal never ran", lookedUp) + assertNull("a session stored during the deletion outlived the server", McpConnections.detach(saved.id)) + } + + /** + * The second DELETE, for the session a call stored meanwhile, goes out after the server's token + * was deleted with it; it carries the token read for the first one instead. + */ + @Test + fun `the second DELETE of a deleted server carries the credentials read for the first`() { + val guarded = FakeMcpServer("ut", listOf(tool("search", true)), sessionId = "session-2") + try { + var removed = false + every { McpServerStore.token(any()) } answers { + if (removed) KeystoreSecretStore.Stored.Absent else KeystoreSecretStore.Stored.Value("ut") + } + val saved = McpServerStore.saveDetails( + McpServerStore.newServer("Guarded", "http://127.0.0.1:${guarded.port}/mcp") + ) + McpConnections.withSession(saved) { it.initialize() } + every { McpServerStore.remove(saved.id) } answers { + // A call landing between the two steps: its session has a server-side id too. + McpConnections.withSession(saved) { it.initialize() } + callOriginal().also { removed = true } + } + + McpSettingsViewModel { null }.deleteNow(saved.id) + + assertEquals( + "the DELETEs ending the deleted server's two sessions", + listOf("Bearer ut", "Bearer ut"), + guarded.requests.filter { it.httpMethod == "DELETE" }.map { it.authorization }, + ) + } finally { + guarded.stop() + } + } + + /** + * The same when the deletion found no session to end first, so no credentials were read for + * one: the DELETE for the session a call stored meanwhile carries the token read before the + * server was removed, not none. + */ + @Test + fun `the second DELETE of a deleted server with no first session carries its token`() { + val guarded = FakeMcpServer("ut", listOf(tool("search", true)), sessionId = "session-3") + try { + var removed = false + every { McpServerStore.token(any()) } answers { + if (removed) KeystoreSecretStore.Stored.Absent else KeystoreSecretStore.Stored.Value("ut") + } + val saved = McpServerStore.saveDetails( + McpServerStore.newServer("Guarded", "http://127.0.0.1:${guarded.port}/mcp") + ) + every { McpServerStore.remove(saved.id) } answers { + // A call landing between the two steps, the server's first session. + McpConnections.withSession(saved) { it.initialize() } + callOriginal().also { removed = true } + } + + McpSettingsViewModel { null }.deleteNow(saved.id) + + assertEquals( + "the DELETE ending the session stored during the deletion", + listOf("Bearer ut"), + guarded.requests.filter { it.httpMethod == "DELETE" }.map { it.authorization }, + ) + } finally { + guarded.stop() + } + } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/FailedCredentialWriteTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/FailedCredentialWriteTest.kt new file mode 100644 index 000000000..c897e9660 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/FailedCredentialWriteTest.kt @@ -0,0 +1,148 @@ +package com.itsaky.androidide.plugins.aiagentmcp.settings + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpToolCatalog +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Before +import org.junit.Test + +/** + * A failed credential write while a server's URL changes never sends the old credential to the + * new URL. + * + * The save wrote the URL, then the token and the headers, and reported "token save failed" when + * the Keystore refused one. The refused write left the old value stored, so the new URL's first + * request carried the old token or the old headers. The old value is now forgotten in the same + * step as the URL change; when forgetting fails too, the URL is put back. + * + * The secret store here is a fake that refuses every write of a value, and refuses the forgetting + * as well when [forgetFails] is set. + */ +class FailedCredentialWriteTest { + + private val old = FakeMcpServer("old-token", listOf(tool("search", true)), sessionId = "old-session") + private val moved = FakeMcpServer("", listOf(tool("search", true))) + + @Volatile private var token = "old-token" + @Volatile private var headers = mapOf("X-Old" to "1") + @Volatile private var forgetFails = false + @Volatile private var duringTokenWrite: (() -> Unit)? = null + + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } answers { + token.takeIf { it.isNotEmpty() }?.let { KeystoreSecretStore.Stored.Value(it) } + ?: KeystoreSecretStore.Stored.Absent + } + every { McpServerStore.headers(any()) } answers { headers } + // The Keystore refuses to store a value; a blank, which removes, lands unless told not to. + every { McpServerStore.writeToken(any(), any()) } answers { + val value = secondArg() + if (value.isNotEmpty()) duringTokenWrite?.invoke() + if (value.isNotEmpty() || forgetFails) false else { token = ""; true } + } + every { McpServerStore.writeHeaders(any(), any()) } answers { + val value = secondArg>() + if (value.isNotEmpty() || forgetFails) false else { headers = emptyMap(); true } + } + } + + @After + fun tearDown() { + McpConnections.closeAll() + McpToolCatalog.clear() + old.stop() + moved.stop() + plugin.dispose() + unmockkObject(McpServerStore) + } + + @Test + fun `a refused token write during a URL change leaves the new URL with no token`() { + val saved = McpServerStore.saveDetails(McpServerStore.newServer("Docs", url(old))) + + val (record, failure) = McpSettingsViewModel { null } + .saveNow(saved.copy(url = url(moved)), "new-token", null) + + assertNotNull("the pane was not told the token was not saved", failure) + assertEquals(url(moved), record.url) + // The headers were not part of this save: the user kept them, as for any URL change. + assertNull("the new URL was sent the old token", firstRequestToTheNewUrl(saved.id).authorization) + } + + @Test + fun `a refused headers write during a URL change leaves the new URL with no headers`() { + val saved = McpServerStore.saveDetails(McpServerStore.newServer("Docs", url(old))) + + val (record, failure) = McpSettingsViewModel { null } + .saveNow(saved.copy(url = url(moved)), null, mapOf("X-New" to "1")) + + assertNotNull("the pane was not told the headers were not saved", failure) + assertEquals(url(moved), record.url) + assertFalse( + "the new URL was sent the old headers", + "x-old" in firstRequestToTheNewUrl(saved.id).headerNames, + ) + } + + @Test + fun `when forgetting the old credential fails too, the URL stays where the credential belongs`() { + val saved = McpServerStore.saveDetails(McpServerStore.newServer("Docs", url(old))) + forgetFails = true + + val (record, failure) = McpSettingsViewModel { null } + .saveNow(saved.copy(url = url(moved)), "new-token", mapOf("X-New" to "1")) + + assertNotNull("the pane was not told the save failed", failure) + assertEquals("the URL moved with the old credential still stored", url(old), record.url) + McpConnections.withSession(McpServerStore.server(saved.id)!!) { it.initialize() } + assertEquals("the new URL was contacted", emptyList(), moved.requests.toList()) + } + + @Test + fun `restoring the URL keeps a tool switched off while the Keystore was writing`() { + val saved = McpServerStore.saveDetails(McpServerStore.newServer("Docs", url(old))) + McpServerStore.setToolEnabled(saved.id, "search", true) + duringTokenWrite = { McpServerStore.setToolEnabled(saved.id, "search", false) } + forgetFails = true + + val (record, failure) = McpSettingsViewModel { null } + .saveNow(McpServerStore.server(saved.id)!!.copy(url = url(moved)), "new-token", null) + + assertNotNull("the pane was not told the save failed", failure) + assertEquals("the URL was not put back", url(old), record.url) + assertEquals(url(old), McpServerStore.server(saved.id)!!.url) + assertFalse( + "the rollback undid the toggle made meanwhile", + "search" in McpServerStore.server(saved.id)!!.enabledTools, + ) + assertFalse("search" in record.enabledTools) + } + + private fun firstRequestToTheNewUrl(id: String): FakeMcpServer.Seen { + McpConnections.withSession(McpServerStore.server(id)!!) { it.initialize() } + return moved.requests.first() + } + + private fun url(server: FakeMcpServer) = "http://127.0.0.1:${server.port}/mcp" +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/LoadFormTogetherTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/LoadFormTogetherTest.kt new file mode 100644 index 000000000..385a5d96f --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/LoadFormTogetherTest.kt @@ -0,0 +1,118 @@ +package com.itsaky.androidide.plugins.aiagentmcp.settings + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.aiagentmcp.testing.awaitFinishedOrBlockedBy +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import kotlin.concurrent.thread +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Before +import org.junit.Test + +/** + * The settings dialog's load shows the token and the headers as stored together, never a token + * from after a save beside headers from before it. + * + * The load read the token, then the headers, outside the lock a save writes them under. A save + * landing between the two reads showed "no token" with the old headers. The load is made from + * inside the headers write of a clear, which has already forgotten the token, on another thread; + * the test waits until it has finished or is blocked on a lock the clearing thread holds. The + * other direction is covered too: a save made from inside the load's token read, which must wait + * for the load to finish. + */ +class LoadFormTogetherTest { + + @Volatile private var token = "old-token" + @Volatile private var headers = mapOf("X-Old" to "1") + + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } answers { + token.takeIf { it.isNotEmpty() }?.let { KeystoreSecretStore.Stored.Value(it) } + ?: KeystoreSecretStore.Stored.Absent + } + every { McpServerStore.headers(any()) } answers { headers } + every { McpServerStore.hasToken(any()) } answers { token.isNotEmpty() } + every { McpServerStore.hasHeaders(any()) } answers { headers.isNotEmpty() } + every { McpServerStore.writeToken(any(), any()) } answers { token = secondArg(); true } + every { McpServerStore.writeHeaders(any(), any()) } answers { headers = secondArg(); true } + } + + @After + fun tearDown() { + plugin.dispose() + unmockkObject(McpServerStore) + } + + @Test + fun `a load between the token write and the headers write shows both before or both after`() { + val clearer = Thread.currentThread() + var load: Thread? = null + var state: McpSettingsViewModel.FormState? = null + every { McpServerStore.writeHeaders(any(), any()) } answers { + // The token is forgotten, the headers not yet. + load = thread(name = "load") { state = McpSettingsViewModel { null }.loadFormNow("s") } + awaitFinishedOrBlockedBy(load!!, clearer) + headers = secondArg() + true + } + + McpServerStore.clearCredentials("s") + load!!.join(10_000) + + val shown = assertNotNull_(state) + assertEquals( + "the load showed a token and headers from different saves", + shown.hasToken, + shown.headers.isNotEmpty(), + ) + } + + @Test + fun `a save between the token read and the headers read does not mix the two`() { + val saved = McpServerStore.saveDetails(McpServerStore.newServer("Docs", "https://example.invalid/mcp")) + val reader = Thread.currentThread() + var saver: Thread? = null + var found: Thread.State? = null + every { McpServerStore.token(saved.id) } answers { + val read = token.takeIf { it.isNotEmpty() }?.let { KeystoreSecretStore.Stored.Value(it) } + ?: KeystoreSecretStore.Stored.Absent + if (saver == null) { + // The token is read, the headers not yet: a save that forgets the token and + // replaces the headers. + saver = thread(name = "saver") { + McpServerStore.saveConnection(saved, "", mapOf("X-New" to "1")) + } + found = awaitFinishedOrBlockedBy(saver!!, reader) + } + read + } + + val shown = McpSettingsViewModel { null }.loadFormNow(saved.id) + saver!!.join(10_000) + + assertEquals( + "the form mixed one save's token with another's headers (saver found $found)", + true to mapOf("X-Old" to "1"), + shown.hasToken to shown.headers, + ) + } + + private fun assertNotNull_(value: McpSettingsViewModel.FormState?): McpSettingsViewModel.FormState { + assertNotNull("the load never finished", value) + return value!! + } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStoreLockTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStoreLockTest.kt index 8e7532f2e..067d8e06a 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStoreLockTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpServerStoreLockTest.kt @@ -32,6 +32,8 @@ class McpServerStoreLockTest { const val READ_DELAY_MS = 2L const val JOIN_TIMEOUT_SECONDS = 30L + + const val URL = "https://example.test/mcp" } private val prefs = FakeSharedPreferences() @@ -48,7 +50,7 @@ class McpServerStoreLockTest { plugin = McpPlugin() plugin.initialize(context) serverId = McpServerStore.saveDetails( - McpServerStore.newServer("Docs", "https://example.test/mcp") + McpServerStore.newServer("Docs", URL) ).id } @@ -60,7 +62,7 @@ class McpServerStoreLockTest { @Test fun givenConcurrentToolToggles_whenTheyInterleave_thenNoWriteIsLost() { val tools = (1..WRITERS).map { "tool_$it" } - McpServerStore.setKnownTools(serverId, tools) + McpServerStore.setKnownTools(serverId, URL, tools) prefs.readDelayMillis = READ_DELAY_MS runTogether(tools) { McpServerStore.setToolEnabled(serverId, it, true) } @@ -71,7 +73,7 @@ class McpServerStoreLockTest { @Test fun givenAToggleAndAWholeServerSwitchAtOnce_whenTheyInterleave_thenNeitherIsLost() { val tools = (1..WRITERS).map { "tool_$it" } - McpServerStore.setKnownTools(serverId, tools) + McpServerStore.setKnownTools(serverId, URL, tools) prefs.readDelayMillis = READ_DELAY_MS runTogether(tools + "disable") { work -> @@ -87,6 +89,26 @@ class McpServerStoreLockTest { assertFalse("the whole-server switch must survive the toggles", stored?.enabled ?: true) } + @Test + fun givenAListingFromTheOldUrl_whenTheUrlChangedMeanwhile_thenItChangesNothing() { + McpServerStore.setKnownTools(serverId, URL, listOf("x")) + McpServerStore.setToolEnabled(serverId, "x", true) + val moved = "https://moved.example.test/mcp" + McpServerStore.saveDetails(McpServerStore.server(serverId)!!.copy(url = moved)) + + McpServerStore.setKnownTools(serverId, URL, listOf("y")) + + val stale = McpServerStore.server(serverId)!! + assertEquals("the old endpoint's list was applied", listOf("x"), stale.knownTools) + assertEquals("the enabled tool was dropped", setOf("x"), stale.enabledTools) + + McpServerStore.setKnownTools(serverId, moved, listOf("y")) + + val applied = McpServerStore.server(serverId)!! + assertEquals(listOf("y"), applied.knownTools) + assertEquals(emptySet(), applied.enabledTools) + } + /** * Runs [work] on one thread per item, all released at once. * diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsHeadersToStoreTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsHeadersToStoreTest.kt index 7e3ddb306..b1359d0aa 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsHeadersToStoreTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsHeadersToStoreTest.kt @@ -7,9 +7,10 @@ import org.junit.Test /** * What the header rows mean when the dialog saves them. * - * `setHeaders` replaces the whole stored map, so this predicate is the only thing standing between - * a keystore that would not answer and a user losing headers they were just told were intact: the - * rows on screen may replace what is stored only when the dialog drew what is stored. + * `McpServerStore.saveConnection` replaces the whole stored map, so this predicate is the only + * thing standing between a keystore that would not answer and a user losing headers they were just + * told were intact: the rows on screen may replace what is stored only when the dialog drew what is + * stored. */ class McpSettingsHeadersToStoreTest { diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/SaveServerSessionTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/SaveServerSessionTest.kt new file mode 100644 index 000000000..19fa319cf --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/SaveServerSessionTest.kt @@ -0,0 +1,200 @@ +package com.itsaky.androidide.plugins.aiagentmcp.settings + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.aiagentmcp.testing.awaitFinishedOrBlockedBy +import com.itsaky.androidide.plugins.aiagentmcp.tools.McpToolCatalog +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import kotlin.concurrent.thread +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * Saving a server's new URL and token ends the old session with the old credentials, and a request + * reading the credentials meanwhile gets the old URL's or the new URL's, never one with the other. + * + * The save stored the URL, then the token, then the headers, and only then ended the old session. + * Its DELETE read the credentials for the old URL once the server had left it, so it carried none, + * and a server that wants its token to end a session refused it and kept the session open. A + * request reading the credentials between the URL write and the token write passed the URL check + * for the new URL and sent it the old token and headers. The session is now taken out first, with + * the credentials it had, the three are written in one step a request's read waits for, and the + * session is ended last. + * + * The request between the two writes is made from inside the token write, on another thread, and + * the test waits until it has finished or is blocked on a lock the saving thread holds. Nothing + * sleeps. + */ +class SaveServerSessionTest { + + private val old = FakeMcpServer("old-token", listOf(tool("search", true)), sessionId = "old-session") + private val moved = FakeMcpServer("new-token", listOf(tool("search", true))) + + // The Keystore is not there on the JVM: the store answers what was last written. + @Volatile private var token = "old-token" + @Volatile private var headers = mapOf("X-Old" to "1") + + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } answers { + token.takeIf { it.isNotEmpty() }?.let { KeystoreSecretStore.Stored.Value(it) } + ?: KeystoreSecretStore.Stored.Absent + } + every { McpServerStore.headers(any()) } answers { headers } + every { McpServerStore.writeToken(any(), any()) } answers { token = secondArg(); true } + every { McpServerStore.writeHeaders(any(), any()) } answers { headers = secondArg(); true } + } + + @After + fun tearDown() { + McpConnections.closeAll() + McpToolCatalog.clear() + old.stop() + moved.stop() + plugin.dispose() + unmockkObject(McpServerStore) + } + + @Test + fun `editing the URL and the token ends the old session with the old token, and the new URL gets the new one`() { + val saved = McpServerStore.saveDetails(McpServerStore.newServer("Docs", url(old))) + McpConnections.withSession(saved) { it.initialize() } + + McpSettingsViewModel { null }.saveNow(saved.copy(url = url(moved)), "new-token", mapOf("X-New" to "1")) + + val delete = old.requests.single { it.httpMethod == "DELETE" } + assertEquals("the old session's DELETE did not carry the old token", "Bearer old-token", delete.authorization) + assertEquals("the old session's DELETE did not carry the old header's value", "1", delete.customHeaders["x-old"]) + assertFalse("the old URL was sent the new headers", "x-new" in delete.headerNames) + + McpConnections.withSession(McpServerStore.server(saved.id)!!) { it.initialize() } + val first = moved.requests.first() + assertEquals("the new URL's first request did not carry the new token", "Bearer new-token", first.authorization) + assertEquals("the new URL's first request did not carry the new header's value", "1", first.customHeaders["x-new"]) + assertFalse("the new URL was sent the old headers", "x-old" in first.headerNames) + } + + @Test + fun `a request between the URL write and the token write gets the old pair or the new, never a mix`() { + val saved = McpServerStore.saveDetails(McpServerStore.newServer("Docs", url(old))) + val saver = Thread.currentThread() + var lookup: Thread? = null + var found: Thread.State? = null + every { McpServerStore.writeToken(saved.id, any()) } answers { + // The URL is written, the token not yet: a request for the server as it now stands. + val current = McpServerStore.server(saved.id)!! + lookup = thread(name = "lookup") { + runCatching { McpConnections.withSession(current) { it.initialize() } } + } + found = awaitFinishedOrBlockedBy(lookup!!, saver) + token = secondArg() + true + } + + McpSettingsViewModel { null }.saveNow(saved.copy(url = url(moved)), "new-token", mapOf("X-New" to "1")) + lookup!!.join(10_000) + + assertTrue("the request never reached the new URL", moved.requests.isNotEmpty()) + moved.requests.forEach { request -> + assertEquals( + "a request read between the URL write and the token write (found $found) sent the new URL", + "Bearer new-token" to mapOf("x-new" to "1"), + request.authorization to request.customHeaders, + ) + } + } + + @Test + fun `a request between the token write and the headers write gets the old pair or the new, never a mix`() { + val saved = McpServerStore.saveDetails(McpServerStore.newServer("Docs", url(old))) + val saver = Thread.currentThread() + var lookup: Thread? = null + var found: Thread.State? = null + every { McpServerStore.writeHeaders(saved.id, any()) } answers { + // The URL and the token are written, the headers not yet: a request for the server as + // it now stands. + val current = McpServerStore.server(saved.id)!! + lookup = thread(name = "lookup") { + runCatching { McpConnections.withSession(current) { it.initialize() } } + } + found = awaitFinishedOrBlockedBy(lookup!!, saver) + headers = secondArg() + true + } + + McpSettingsViewModel { null }.saveNow(saved.copy(url = url(moved)), "new-token", mapOf("X-New" to "1")) + lookup!!.join(10_000) + + assertTrue("the request never reached the new URL", moved.requests.isNotEmpty()) + moved.requests.forEach { request -> + assertEquals( + "a request read between the token write and the headers write (found $found) sent the new URL", + "Bearer new-token" to mapOf("x-new" to "1"), + request.authorization to request.customHeaders, + ) + } + } + + @Test + fun `clearing the credentials ends the session with the ones it had`() { + val saved = McpServerStore.saveDetails(McpServerStore.newServer("Docs", url(old))) + McpConnections.withSession(saved) { it.initialize() } + + val cleared = McpSettingsViewModel { null }.clearCredentialNow(saved.id) + + assertTrue(cleared) + val delete = old.requests.single { it.httpMethod == "DELETE" } + assertEquals("the session's DELETE did not carry its token", "Bearer old-token", delete.authorization) + assertEquals("the session's DELETE did not carry its header's value", "1", delete.customHeaders["x-old"]) + } + + @Test + fun `a save that throws still ends the detached session with the old credentials`() { + val saved = McpServerStore.saveDetails(McpServerStore.newServer("Docs", url(old))) + McpConnections.withSession(saved) { it.initialize() } + every { McpServerStore.saveConnection(any(), any(), any()) } throws IllegalStateException("disk full") + + val thrown = runCatching { + McpSettingsViewModel { null }.saveNow(saved.copy(url = url(moved)), "new-token", mapOf("X-New" to "1")) + }.exceptionOrNull() + + assertTrue("the save's failure was swallowed", thrown is IllegalStateException) + val delete = old.requests.singleOrNull { it.httpMethod == "DELETE" } + assertTrue("the detached session was left open on the server", delete != null) + assertEquals("the DELETE did not carry the old token", "Bearer old-token", delete!!.authorization) + } + + @Test + fun `clearing that throws still ends the detached session with the old credentials`() { + val saved = McpServerStore.saveDetails(McpServerStore.newServer("Docs", url(old))) + McpConnections.withSession(saved) { it.initialize() } + every { McpServerStore.clearCredentials(any()) } throws IllegalStateException("disk full") + + val thrown = runCatching { McpSettingsViewModel { null }.clearCredentialNow(saved.id) }.exceptionOrNull() + + assertTrue("the clear's failure was swallowed", thrown is IllegalStateException) + val delete = old.requests.singleOrNull { it.httpMethod == "DELETE" } + assertTrue("the detached session was left open on the server", delete != null) + assertEquals("the DELETE did not carry the old token", "Bearer old-token", delete!!.authorization) + } + + private fun url(server: FakeMcpServer) = "http://127.0.0.1:${server.port}/mcp" +} 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..1ff532fcb --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/testing/FakeMcpServer.kt @@ -0,0 +1,98 @@ +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. + * @property headerNames the names of every header it carried, in lower case. + * @property customHeaders the first value of each `X-*` header it carried, by lower-case name, + * so a test can tell the value a header was sent with, not only that it was sent. + */ + data class Seen( + val httpMethod: String, + val authorization: String?, + val headerNames: Set = emptySet(), + val customHeaders: Map = emptyMap(), + ) + + 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"), + exchange.requestHeaders.keys.mapTo(mutableSetOf()) { it.lowercase() }, + exchange.requestHeaders.entries + .filter { (name, _) -> name.startsWith("x-", ignoreCase = true) } + .associate { (name, values) -> name.lowercase() to values.first() }, + ) + if (exchange.requestMethod == "DELETE") { + exchange.sendResponseHeaders(200, -1) + 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/testing/ThreadStates.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/testing/ThreadStates.kt new file mode 100644 index 000000000..6ded4486a --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/testing/ThreadStates.kt @@ -0,0 +1,26 @@ +package com.itsaky.androidide.plugins.aiagentmcp.testing + +import java.lang.management.ManagementFactory +import java.util.concurrent.TimeUnit + +/** + * Waits until [waiter] has finished, or is blocked entering a monitor that [holder] holds. A test + * that lets one thread run into another's lock uses this to tell the two outcomes apart without + * depending on how long anything takes. + * + * @return the state [waiter] was found in: TERMINATED or BLOCKED. + * @throws AssertionError when neither happens within ten seconds. + */ +fun awaitFinishedOrBlockedBy(waiter: Thread, holder: Thread): Thread.State { + val threads = ManagementFactory.getThreadMXBean() + val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10) + while (System.nanoTime() < deadline) { + val state = waiter.state + if (state == Thread.State.TERMINATED) return state + if (state == Thread.State.BLOCKED && threads.getThreadInfo(waiter.id)?.lockOwnerId == holder.id) { + return state + } + Thread.yield() + } + throw AssertionError("${waiter.name} neither finished nor waited for ${holder.name}: ${waiter.state}") +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/AppEndpointReasonTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/AppEndpointReasonTest.kt new file mode 100644 index 000000000..8b395ef7c --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/AppEndpointReasonTest.kt @@ -0,0 +1,160 @@ +package com.itsaky.androidide.plugins.aiagentmcp.tools + +import android.content.Context +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.R +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticEndpoint +import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticServers +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServer +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.aiagentmcp.transport.McpHttpException +import io.mockk.every +import io.mockk.mockk +import java.io.File +import java.io.IOException +import java.net.ConnectException +import java.net.InetAddress +import java.net.ServerSocket +import java.net.SocketTimeoutException +import javax.xml.parsers.DocumentBuilderFactory +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Before +import org.junit.Test +import org.w3c.dom.Element + +/** + * The reason the Agent tab shows when an app's SQLite debugger entry cannot be reached says what + * to do with the app. Read from [McpServerHealth], where the Agent tab gets it, in the words of + * this plugin's own strings.xml. + */ +class AppEndpointReasonTest { + + private val app = "com.example.probe" + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + every { context.androidContext } returns stringsXmlContext() + plugin = McpPlugin().also { it.initialize(context) } + } + + @After + fun tearDown() { + AutomaticServers.install(null) + McpConnections.closeAll() + McpToolCatalog.clear() + McpServerHealth.clear() + plugin.dispose() + } + + @Test + fun `a timed-out connection to an app says Android may have paused it`() { + val server = appEntry(33425) + val paused = "The app com.example.probe did not answer. If the app is in the background, " + + "Android may have paused it. Bring the app to the front and try again." + + // What Android's HttpURLConnection threw on a Galaxy Note 20 for an app frozen in the background. + McpToolCatalog.recordFailure( + server, + SocketTimeoutException( + "failed to connect to /127.0.0.1 (port 33425) from /127.0.0.1 (port 56874) after 15000ms", + ), + ) + assertEquals(paused, reason(server)) + + // Where the system accepts the connection for a paused app, it is the read that times out. + McpToolCatalog.recordFailure(server, SocketTimeoutException("Read timed out")) + assertEquals(paused, reason(server)) + } + + @Test + fun `a refused connection to an app says to open it again from Code on the Go`() { + // A port that was free a moment ago: nothing listens there, as after the app's process died. + val port = ServerSocket(0, 1, InetAddress.getLoopbackAddress()).use { it.localPort } + val server = appEntry(port) + + runCatching { McpToolCatalog.connect(server) } + + assertEquals( + "The app com.example.probe is not running with the SQLite debugger. " + + "Open the app again from Code on the Go.", + reason(server), + ) + } + + @Test + fun `a refusal wrapped in another exception still says to open the app again`() { + val server = appEntry(33425) + + McpToolCatalog.recordFailure( + server, + IOException("request failed", ConnectException("Failed to connect to /127.0.0.1:33425")), + ) + + assertEquals( + "The app com.example.probe is not running with the SQLite debugger. " + + "Open the app again from Code on the Go.", + reason(server), + ) + } + + @Test + fun `a server added by hand keeps the generic reason for a refusal and a timeout`() { + val server = McpServerStore.saveDetails(McpServerStore.newServer("Docs", "http://127.0.0.1:33425/mcp")) + + McpToolCatalog.recordFailure(server, ConnectException("Failed to connect to /127.0.0.1:33425")) + assertEquals("Could not reach Docs: Failed to connect to /127.0.0.1:33425", reason(server)) + + McpToolCatalog.recordFailure(server, SocketTimeoutException("Read timed out")) + assertEquals("Docs did not answer in time. It may be slow or offline.", reason(server)) + } + + @Test + fun `any other failure of an app keeps the generic reason`() { + val server = appEntry(33425) + + McpToolCatalog.recordFailure(server, IOException("socket closed")) + assertEquals("Could not reach SQLite debugger (com.example.probe): socket closed", reason(server)) + + McpToolCatalog.recordFailure(server, McpHttpException(500, "")) + assertEquals("SQLite debugger (com.example.probe) reported a server error (HTTP 500).", reason(server)) + + // A 504 is an answer: the app is running, so it is not the paused-app reason. + McpToolCatalog.recordFailure(server, McpHttpException(504, "")) + assertEquals( + "SQLite debugger (com.example.probe) did not answer in time. It may be slow or offline.", + reason(server), + ) + } + + /** The automatic entry for [app], listening on [port] as far as Code on the Go knows. */ + private fun appEntry(port: Int): McpServer { + AutomaticServers.install({ listOf(AutomaticEndpoint(app, port, "t1")) }) + return AutomaticServers.servers().single() + } + + private fun reason(server: McpServer): String? = McpServerHealth.of(server.id)?.message + + /** A Context answering `getString` from this plugin's strings.xml, so the shipped words are checked. */ + private fun stringsXmlContext(): Context { + val names = R.string::class.java.fields.associate { it.getInt(null) to it.name } + val nodes = DocumentBuilderFactory.newInstance().newDocumentBuilder() + .parse(File("src/main/res/values/strings.xml")) + .getElementsByTagName("string") + val texts = (0 until nodes.length).map { nodes.item(it) as Element } + .associate { it.getAttribute("name") to it.textContent.replace("\\'", "'") } + val text = { id: Int -> texts.getValue(names.getValue(id)) } + return mockk(relaxed = true) { + every { getString(any()) } answers { text(firstArg()) } + every { getString(any(), *anyVararg()) } answers { + String.format(text(firstArg()), *secondArg>()) + } + } + } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/CancelAfterWorkerStartsTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/CancelAfterWorkerStartsTest.kt new file mode 100644 index 000000000..dc488af3b --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/CancelAfterWorkerStartsTest.kt @@ -0,0 +1,185 @@ +package com.itsaky.androidide.plugins.aiagentmcp.tools + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import com.itsaky.androidide.plugins.services.ToolSourceRegistry +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import java.util.concurrent.CompletableFuture +import java.util.concurrent.CancellationException +import java.util.concurrent.CountDownLatch +import java.util.concurrent.ExecutionException +import java.util.concurrent.ExecutorService +import java.util.concurrent.Executors +import java.util.concurrent.RejectedExecutionException +import java.util.concurrent.TimeUnit +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Before +import org.junit.Test + +/** + * A cancel must always find the call it cancels, whatever its worker has reached, and a call must + * leave nothing registered however it ends. + * + * The worker's first instructions used to be the only place a call became known to + * [McpToolSource.cancel]; one landing before them set no flag and found no session, and the + * request went out. The calls are now registered before they are scheduled. These tests force the + * orders with latches: no sleeps, and every wait ends on a latch or on the executor terminating. + */ +class CancelAfterWorkerStartsTest { + + private val delegate = Executors.newSingleThreadExecutor() + private lateinit var server: FakeMcpServer + private lateinit var plugin: McpPlugin + private lateinit var name: String + private var requestsBefore = 0 + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } returns KeystoreSecretStore.Stored.Absent + every { McpServerStore.headers(any()) } returns emptyMap() + server = FakeMcpServer("", listOf(tool("search", true))) + val docs = McpServerStore.saveDetails( + McpServerStore.newServer("Docs", "http://127.0.0.1:${server.port}/mcp") + ) + McpToolCatalog.connect(docs) + McpServerStore.setToolEnabled(docs.id, "search", true) + name = McpToolSource(delegate).listTools().single().name + requestsBefore = server.requests.size + } + + @After + fun tearDown() { + delegate.shutdownNow() + McpConnections.closeAll() + McpToolCatalog.clear() + server.stop() + plugin.dispose() + unmockkObject(McpServerStore) + } + + private fun invoke(source: McpToolSource): CompletableFuture = + source.invoke( + mockk { + every { toolName } returns name + every { arguments } returns emptyMap() + every { callId } returns CALL_ID + } + ) + + private fun awaitWorkers() { + delegate.shutdown() + assertTrue("the worker never finished", delegate.awaitTermination(10, TimeUnit.SECONDS)) + } + + /** The future [McpToolSource.invoke] returns completes with the scheduled future's cancellation. */ + private fun assertEndedCancelled(future: CompletableFuture<*>) { + assertTrue("the call did not end", future.isDone) + val failure = try { + future.get(10, TimeUnit.SECONDS) + null + } catch (e: CancellationException) { + e + } catch (e: ExecutionException) { + e.cause + } + assertTrue("the call did not end cancelled: $failure", failure is CancellationException) + } + + private fun assertNothingSent() = assertEquals( + "the call reached the server after it was cancelled: ${server.requests.drop(requestsBefore)}", + requestsBefore, + server.requests.size, + ) + + @Test + fun `a cancel that lands after the worker started and before its first line sends nothing`() { + val started = CountDownLatch(1) + val proceed = CountDownLatch(1) + val source = McpToolSource(delegate) { + started.countDown() + assertTrue("the test never released the worker", proceed.await(10, TimeUnit.SECONDS)) + } + + val future = invoke(source) + assertTrue("the worker never started", started.await(10, TimeUnit.SECONDS)) + source.cancel(CALL_ID) + proceed.countDown() + awaitWorkers() + + assertNothingSent() + assertEndedCancelled(future) + assertEquals("a cancelled call left its registration behind", 0, source.pendingCalls()) + } + + @Test + fun `a call cancelled before its worker runs sends nothing and leaves no registration`() { + val release = CountDownLatch(1) + val held = object : ExecutorService by delegate { + override fun execute(command: Runnable) = delegate.execute { + assertTrue("the test never released the worker", release.await(10, TimeUnit.SECONDS)) + command.run() + } + } + val source = McpToolSource(held) + + val future = invoke(source) + source.cancel(CALL_ID) + assertEquals("a call cancelled before it ran kept its registration", 0, source.pendingCalls()) + release.countDown() + awaitWorkers() + + assertNothingSent() + assertEndedCancelled(future) + assertEquals(0, source.pendingCalls()) + } + + @Test + fun `a normal call leaves no registration behind`() { + val source = McpToolSource(delegate) + + val outcome = invoke(source).get(10, TimeUnit.SECONDS) + + assertTrue("the call failed: ${outcome.errorMessage}", outcome.isSuccess) + assertTrue("the call never reached the server", server.requests.size > requestsBefore) + assertEquals("a finished call left its registration behind", 0, source.pendingCalls()) + } + + @Test + fun `a call whose scheduling throws leaves no registration behind`() { + val rejecting = object : ExecutorService by delegate { + override fun execute(command: Runnable) = throw RejectedExecutionException("full") + } + val source = McpToolSource(rejecting) + + try { + invoke(source) + fail("scheduling should have thrown") + } catch (expected: RejectedExecutionException) { + assertFalse(expected.message.isNullOrEmpty()) + } + + assertEquals("a call that was never scheduled kept its registration", 0, source.pendingCalls()) + assertNothingSent() + } + + private companion object { + const val CALL_ID = "call-1" + } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/CancelDuringCredentialsReadTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/CancelDuringCredentialsReadTest.kt new file mode 100644 index 000000000..3587e7611 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/CancelDuringCredentialsReadTest.kt @@ -0,0 +1,113 @@ +package com.itsaky.androidide.plugins.aiagentmcp.tools + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import com.itsaky.androidide.plugins.services.ToolSourceRegistry +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicInteger +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * A cancel that lands while a request reads its credentials must stop the call. + * + * Reading them decrypts the token through the Keystore, after the worker's own read of the cancel + * flag and before the request has a connection a cancel could drop. A cancel there used to find the + * session, drop nothing, and leave the `tools/call` to go out; each request now publishes its + * connection to the call's handle and reads the flag again before it sends anything. + * + * The test lands the cancel there for certain. Once armed, the worker reads the server's token + * twice: first while it looks up its session, then while the `tools/call` request reads its + * credentials, and that second read cancels the call. + */ +class CancelDuringCredentialsReadTest { + + private val executor = Executors.newSingleThreadExecutor() + private val source = McpToolSource(executor) + private val armed = AtomicBoolean(false) + private val reads = AtomicInteger(0) + private lateinit var server: FakeMcpServer + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + // The Keystore is not there on the JVM; this server has no secrets. + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } answers { + if (armed.get() && reads.incrementAndGet() == CREDENTIALS_READ) { + armed.set(false) + source.cancel(CALL_ID) + } + KeystoreSecretStore.Stored.Absent + } + every { McpServerStore.headers(any()) } returns emptyMap() + server = FakeMcpServer("", listOf(tool("search", true))) + } + + @After + fun tearDown() { + source.close() + McpConnections.closeAll() + McpToolCatalog.clear() + server.stop() + plugin.dispose() + unmockkObject(McpServerStore) + } + + @Test + fun `a cancel that lands while the request reads its credentials sends nothing`() { + val docs = McpServerStore.saveDetails( + McpServerStore.newServer("Docs", "http://127.0.0.1:${server.port}/mcp") + ) + McpToolCatalog.connect(docs) + McpServerStore.setToolEnabled(docs.id, "search", true) + val name = source.listTools().single().name + val before = server.requests.size + + armed.set(true) + source.invoke( + mockk { + every { toolName } returns name + every { arguments } returns emptyMap() + every { callId } returns CALL_ID + } + ) + // Waits for the worker itself, so whatever it was going to send has been sent. + executor.shutdown() + assertTrue("the call never finished", executor.awaitTermination(10, TimeUnit.SECONDS)) + + assertFalse("the call never read its credentials", armed.get()) + assertEquals( + "the call reached the server after it was cancelled: ${server.requests.drop(before)}", + before, + server.requests.size, + ) + assertEquals("a cancelled call left its registration behind", 0, source.pendingCalls()) + } + + private companion object { + const val CALL_ID = "call-1" + + /** The session lookup reads the token first; the `tools/call` request's read is second. */ + const val CREDENTIALS_READ = 2 + } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/CancelDuringSessionLookupTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/CancelDuringSessionLookupTest.kt new file mode 100644 index 000000000..0a93b7bcc --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/CancelDuringSessionLookupTest.kt @@ -0,0 +1,102 @@ +package com.itsaky.androidide.plugins.aiagentmcp.tools + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import com.itsaky.androidide.plugins.services.ToolSourceRegistry +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * A cancel that lands while a call looks up its session must stop the call. + * + * The lookup sits between the worker's check of the cancel flag and the call's first request. A + * cancel in that window sets the flag but finds no connection to drop, so only a later read of the + * flag, once the request has published its connection to the call's handle, keeps the request from + * going out. The test lands the cancel there for certain: the lookup reads the server's token, and + * the first read after the test arms it cancels the call. + */ +class CancelDuringSessionLookupTest { + + private val executor = Executors.newSingleThreadExecutor() + private val source = McpToolSource(executor) + private val armed = AtomicBoolean(false) + private lateinit var server: FakeMcpServer + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + // The Keystore is not there on the JVM; this server has no secrets. Reading its token is + // also where the call looks up its session, so that is where the cancel lands. + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } answers { + if (armed.getAndSet(false)) source.cancel(CALL_ID) + KeystoreSecretStore.Stored.Absent + } + every { McpServerStore.headers(any()) } returns emptyMap() + server = FakeMcpServer("", listOf(tool("search", true))) + } + + @After + fun tearDown() { + source.close() + McpConnections.closeAll() + McpToolCatalog.clear() + server.stop() + plugin.dispose() + unmockkObject(McpServerStore) + } + + @Test + fun `a cancel that lands while the call looks up its session sends nothing`() { + val docs = McpServerStore.saveDetails( + McpServerStore.newServer("Docs", "http://127.0.0.1:${server.port}/mcp") + ) + McpToolCatalog.connect(docs) + McpServerStore.setToolEnabled(docs.id, "search", true) + val name = source.listTools().single().name + val before = server.requests.size + + armed.set(true) + source.invoke( + mockk { + every { toolName } returns name + every { arguments } returns emptyMap() + every { callId } returns CALL_ID + } + ) + // Waits for the worker itself, so whatever it was going to send has been sent. + executor.shutdown() + assertTrue("the call never finished", executor.awaitTermination(10, TimeUnit.SECONDS)) + + assertFalse("the call never looked up its session", armed.get()) + assertEquals( + "the call reached the server after it was cancelled: ${server.requests.drop(before)}", + before, + server.requests.size, + ) + } + + private companion object { + const val CALL_ID = "call-1" + } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/CloseWithCallsInFlightTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/CloseWithCallsInFlightTest.kt new file mode 100644 index 000000000..2e6ad2178 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/CloseWithCallsInFlightTest.kt @@ -0,0 +1,149 @@ +package com.itsaky.androidide.plugins.aiagentmcp.tools + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServer +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import com.itsaky.androidide.plugins.services.ToolSourceRegistry +import com.sun.net.httpserver.HttpExchange +import com.sun.net.httpserver.HttpServer +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import java.net.InetSocketAddress +import java.util.concurrent.CompletableFuture +import java.util.concurrent.CountDownLatch +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import org.json.JSONArray +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * Closing the tool source ends every call it accepted, running or queued. + * + * `close()` shut the executor down and cleared its maps. A call queued behind a running one was + * never started, so its future never completed and the host waited on it; the running call's + * worker stayed blocked in a socket read until the server answered or the read timed out. + * + * One worker runs the held call, so the second call is queued behind it. The server answers the + * held call only when [release] is counted down, which happens after the assertions: both futures + * must be done by then. Nothing sleeps. + */ +class CloseWithCallsInFlightTest { + + private val pool = Executors.newSingleThreadExecutor() + private val source = McpToolSource(pool) + + /** Counted down when the held `tools/call` reaches the server. */ + private val arrived = CountDownLatch(1) + private val release = CountDownLatch(1) + + private val handlers = Executors.newCachedThreadPool() + private lateinit var http: HttpServer + private lateinit var plugin: McpPlugin + private lateinit var docs: McpServer + private lateinit var name: String + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } returns KeystoreSecretStore.Stored.Absent + every { McpServerStore.headers(any()) } returns emptyMap() + http = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply { + executor = handlers + createContext("/mcp") { exchange -> answer(exchange) } + start() + } + docs = McpServerStore.saveDetails( + McpServerStore.newServer("Docs", "http://127.0.0.1:${http.address.port}/mcp") + ) + McpToolCatalog.connect(docs) + McpServerStore.setToolEnabled(docs.id, "search", true) + name = source.listTools().single().name + } + + @After + fun tearDown() { + release.countDown() + source.close() + pool.shutdownNow() + McpConnections.closeAll() + McpToolCatalog.clear() + http.stop(0) + handlers.shutdownNow() + plugin.dispose() + unmockkObject(McpServerStore) + } + + private fun answer(exchange: HttpExchange) { + if (exchange.requestMethod == "DELETE") { + exchange.sendResponseHeaders(200, -1) + exchange.close() + return + } + val request = JSONObject(exchange.requestBody.use { String(it.readBytes()) }) + val id = request.opt("id") + if (id == null) { + exchange.sendResponseHeaders(202, -1) + exchange.close() + return + } + val result = when (request.getString("method")) { + "initialize" -> JSONObject().put("protocolVersion", "2025-03-26") + "tools/list" -> JSONObject().put("tools", JSONArray(listOf(tool("search", true)))) + "tools/call" -> { + arrived.countDown() + release.await(10, TimeUnit.SECONDS) + JSONObject().put( + "content", + JSONArray().put(JSONObject().put("type", "text").put("text", "ok")), + ) + } + else -> JSONObject() + } + val bytes = JSONObject().put("jsonrpc", "2.0").put("id", id).put("result", result) + .toString().toByteArray() + exchange.responseHeaders.add("Content-Type", "application/json") + // The client is dropped by close(); the write failing then is expected. + runCatching { + exchange.sendResponseHeaders(200, bytes.size.toLong()) + exchange.responseBody.use { it.write(bytes) } + } + exchange.close() + } + + private fun invoke(id: String): CompletableFuture = + source.invoke( + mockk { + every { toolName } returns name + every { arguments } returns mapOf("who" to id) + every { callId } returns id + } + ) + + @Test + fun `close completes a running call and a queued one before the server answers`() { + val running = invoke("running") + assertTrue("the call never reached the server", arrived.await(10, TimeUnit.SECONDS)) + val queued = invoke("queued") + + source.close() + + assertTrue("the running call's future is still pending after close", running.isDone) + assertTrue("the queued call's future is still pending after close", queued.isDone) + assertEquals("a call was left registered", 0, source.pendingCalls()) + } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpServerHealthTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpServerHealthTest.kt index cf9c2967a..24c495de9 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpServerHealthTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpServerHealthTest.kt @@ -1,10 +1,14 @@ package com.itsaky.androidide.plugins.aiagentmcp.tools +import com.itsaky.androidide.plugins.aiagentmcp.testing.awaitFinishedOrBlockedBy import org.junit.After import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test +import kotlin.concurrent.thread /** * Tests [McpServerHealth], which the agent's per-server tags read: a change is announced once, @@ -95,4 +99,22 @@ class McpServerHealthTest { assertEquals(McpServerHealth.State.DEGRADED, McpServerHealth.of(SERVER)?.state) assertEquals(1, changes) } + + @Test + fun givenARefusalBeingRecorded_whenTheCredentialChangesMeanwhile_thenTheRefusalIsCleared() { + McpServerHealth.degraded(SERVER, "refused", refused = true) + var changing: Thread? = null + + // The credential changes while the refused write holds the lock, between its check and + // its write; the change must wait for the write and then clear it. + McpServerHealth.degraded(SERVER, "refused", refused = true) { + changing = thread(name = "changing") { McpServerHealth.credentialChanged(SERVER) } + awaitFinishedOrBlockedBy(changing!!, Thread.currentThread()) + true + } + changing!!.join(10_000) + + assertFalse("the refusal outlived the credential change", McpServerHealth.of(SERVER)!!.refused) + assertTrue(McpServerHealth.of(SERVER)?.state == McpServerHealth.State.DEGRADED) + } } 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..0aad7de40 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolTextTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/McpToolTextTest.kt @@ -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,64 @@ 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 givenAFallbackEqualToAnotherAppsPlainPrefix_whenPrefixed_thenThePlainPrefixKeepsIt() { + // com.a.db and com.d.db share db_db; com.a.db's digest form is db_ec81, com.c.ec81's plain one. + val ids = listOf("com.a.db", "com.d.db", "com.c.ec81") + val prefixes = McpToolText.appPrefixes(ids) + + assertEquals("db_ec81", prefixes.getValue("com.c.ec81")) + assertEquals("db_f048", prefixes.getValue("com.d.db")) + assertEquals("d_ec8102c6", prefixes.getValue("com.a.db")) + assertDistinct(prefixes) + assertEquals(prefixes, McpToolText.appPrefixes(ids.reversed())) + } + + @Test + fun givenTwoAppsWhoseShortDigestsAgree_whenPrefixed_thenTheLongDigestTellsThemApart() { + // Both are db_notes, and both are notes_5599 by the four-digit digest. + val ids = listOf("com.a177.notes", "com.a282.notes", "com.example.shop") + val prefixes = McpToolText.appPrefixes(ids) + + assertEquals("db_shop", prefixes.getValue("com.example.shop")) + assertEquals("n_55990d5b", prefixes.getValue("com.a177.notes")) + assertEquals("n_5599fbc8", prefixes.getValue("com.a282.notes")) + assertDistinct(prefixes) + assertEquals(prefixes, McpToolText.appPrefixes(ids.reversed())) + } + + @Test + fun givenTwoAppsWhoseLongDigestsAgree_whenPrefixed_thenTheyAreNumberedInIdOrder() { + // Both are notes_459b and n_459bb758: the first four bytes of their digests agree. + val ids = listOf("com.pa09e.notes", "com.p182b6.notes") + val prefixes = McpToolText.appPrefixes(ids) + + assertEquals("db_1", prefixes.getValue("com.p182b6.notes")) + assertEquals("db_2", prefixes.getValue("com.pa09e.notes")) + assertEquals(prefixes, McpToolText.appPrefixes(ids.reversed())) + } + + private fun assertDistinct(prefixes: Map) { + assertEquals("two apps share a prefix: $prefixes", prefixes.size, prefixes.values.toSet().size) + assertTrue("a prefix is too long: $prefixes", prefixes.values.all { it.length <= 10 }) + } + + @Test + fun givenAnAppIdWithNothingUsable_whenPrefixed_thenItStillGetsAName() { + assertEquals("db_app", McpToolText.appPrefixes(listOf("com.example.***")).getValue("com.example.***")) + } } diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/RemovalDuringRecordTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/RemovalDuringRecordTest.kt new file mode 100644 index 000000000..8daed3459 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/RemovalDuringRecordTest.kt @@ -0,0 +1,197 @@ +package com.itsaky.androidide.plugins.aiagentmcp.tools + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.debugger.McpServers +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServer +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpSettingsViewModel +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.aiagentmcp.testing.awaitFinishedOrBlockedBy +import com.itsaky.androidide.plugins.aiagentmcp.transport.McpExchangeListener +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import com.itsaky.androidide.plugins.services.ToolSourceRegistry +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean +import kotlin.concurrent.thread +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * A server of the user's removed between the check that it is still configured and the write of + * its health or its tools leaves neither behind. + * + * A listing and a call checked that their server was configured, then wrote its health, with + * nothing to keep a removal from landing in between: the removal forgot the health, and the write + * brought it back. The listing wrote the server's tools with no check at all, so a removal that + * finished first saw them come back too. Each check and its write now share the lock the + * removal's forget takes. + * + * The deletion runs on its own thread from inside the check, once the request before it is over, + * and the check waits until the deletion has finished or is blocked on a lock the checking thread + * holds. Nothing sleeps. + */ +class RemovalDuringRecordTest { + + private val delegate = Executors.newSingleThreadExecutor() + private val removals = CopyOnWriteArrayList() + + /** Whether the next check should run the deletion; read by every check, on any thread. */ + @Volatile private var trigger: () -> Boolean = { false } + private val fired = AtomicBoolean(false) + + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + // The Keystore is not there on the JVM; these servers have no secrets. + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } returns KeystoreSecretStore.Stored.Absent + every { McpServerStore.headers(any()) } returns emptyMap() + mockkObject(McpServers) + every { McpServers.isConfigured(any()) } answers { + // What the check found, before the deletion it lets in. + val configured = callOriginal() + if (trigger() && fired.compareAndSet(false, true)) { + val checking = Thread.currentThread() + val id = firstArg().id + val removal = thread(name = "removing") { McpSettingsViewModel { null }.deleteNow(id) } + removals += removal + awaitFinishedOrBlockedBy(removal, checking) + } + configured + } + } + + @After + fun tearDown() { + removals.forEach { it.join(10_000) } + delegate.shutdownNow() + unmockkObject(McpServers) + McpConnections.closeAll() + McpToolCatalog.clear() + plugin.dispose() + unmockkObject(McpServerStore) + } + + @Test + fun `a listing whose server is removed after the check records neither health nor tools`() { + val server = FakeMcpServer("", listOf(tool("search", true))) + try { + val saved = save(server) + val listed = AtomicBoolean(false) + trigger = { listed.get() } + + McpToolCatalog.connect( + saved, + McpExchangeListener { exchange, _ -> + if (exchange.requestBody.text.contains("\"tools/list\"")) listed.set(true) + }, + ) + removals.forEach { it.join(10_000) } + + assertTrue("no check ran after the listing", fired.get()) + assertNull("the listing brought back the removed server's health", McpServerHealth.of(saved.id)) + assertEquals("the listing brought back the removed server's tools", emptyList(), toolNames(saved)) + } finally { + server.stop() + } + } + + @Test + fun `a listing whose server is removed before its tools are stored leaves no tools`() { + val server = FakeMcpServer("", listOf(tool("search", true))) + try { + val saved = save(server) + + McpToolCatalog.connect( + saved, + McpExchangeListener { exchange, _ -> + // Deleted as the listing is answered, before anything stores its tools. + if (exchange.requestBody.text.contains("\"tools/list\"")) { + McpSettingsViewModel { null }.deleteNow(saved.id) + } + }, + ) + + assertTrue("the server was not deleted", McpServerStore.server(saved.id) == null) + assertEquals("the listing stored the removed server's tools", emptyList(), toolNames(saved)) + assertNull("the listing brought back the removed server's health", McpServerHealth.of(saved.id)) + } finally { + server.stop() + } + } + + @Test + fun `a failed listing whose server is removed after the check records no health`() { + // Refuses the listing: its requests carry no token. + val server = FakeMcpServer("required", listOf(tool("search", true))) + try { + val saved = save(server) + val answered = AtomicBoolean(false) + trigger = { answered.get() } + + val failure = runCatching { + McpToolCatalog.connect(saved, McpExchangeListener { _, _ -> answered.set(true) }) + }.exceptionOrNull() + removals.forEach { it.join(10_000) } + + assertTrue("the listing did not fail: $failure", failure != null) + assertTrue("no check ran after the refusal", fired.get()) + assertNull("the failed listing brought back the removed server's health", McpServerHealth.of(saved.id)) + } finally { + server.stop() + } + } + + @Test + fun `a call whose server is removed after the check records no health`() { + val server = FakeMcpServer("", listOf(tool("search", true))) + try { + val saved = save(server) + McpToolCatalog.connect(saved) + McpServerStore.setToolEnabled(saved.id, "search", true) + val source = McpToolSource(delegate) + val name = source.listTools().single().name + val before = server.requests.size + // Armed by the call's own request: nothing checks the server while that is answered. + trigger = { server.requests.size > before } + + val outcome = source.invoke( + mockk { + every { toolName } returns name + every { arguments } returns emptyMap() + every { callId } returns "call-1" + } + ).get(10, TimeUnit.SECONDS) + removals.forEach { it.join(10_000) } + + assertTrue("the call was not answered: ${outcome.errorMessage}", outcome.isSuccess) + assertTrue("no check ran after the call", fired.get()) + assertNull("the call brought back the removed server's health", McpServerHealth.of(saved.id)) + } finally { + server.stop() + } + } + + private fun save(server: FakeMcpServer): McpServer = + McpServerStore.saveDetails(McpServerStore.newServer("Docs", "http://127.0.0.1:${server.port}/mcp")) + + private fun toolNames(server: McpServer) = McpToolCatalog.tools(server.id).map { it.name } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/RemovedDuringCallTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/RemovedDuringCallTest.kt new file mode 100644 index 000000000..84e3bd921 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/RemovedDuringCallTest.kt @@ -0,0 +1,102 @@ +package com.itsaky.androidide.plugins.aiagentmcp.tools + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticEndpoint +import com.itsaky.androidide.plugins.aiagentmcp.debugger.AutomaticServers +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import com.itsaky.androidide.plugins.services.ToolSourceRegistry +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import java.util.concurrent.CountDownLatch +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicReference +import org.junit.After +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * A tool call still on its way when its SQLite debugger entry goes away leaves nothing of that + * entry behind. + * + * The read that removes an entry takes out its session and its health. A call accepted before that + * looked its session up afterwards, which stored a new one for an entry that no longer exists, and + * once it was answered it marked the entry available again. Both are now skipped for a server that + * is no longer configured, as a listing already skipped recording its health. + * + * The worker is held on a latch before its first line while the entry is removed; nothing sleeps. + */ +class RemovedDuringCallTest { + + private val delegate = Executors.newSingleThreadExecutor() + private lateinit var server: FakeMcpServer + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + // The Keystore is not there on the JVM; nothing here reads a hand-added server's secrets. + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } returns KeystoreSecretStore.Stored.Absent + every { McpServerStore.headers(any()) } returns emptyMap() + // Answers whatever token it is sent: the removed entry's requests go out with none. + server = FakeMcpServer("", listOf(tool("query", true))) + } + + @After + fun tearDown() { + delegate.shutdownNow() + AutomaticServers.install(null) + McpConnections.closeAll() + McpToolCatalog.clear() + server.stop() + plugin.dispose() + unmockkObject(McpServerStore) + } + + @Test + fun `a call that outlives its entry's removal leaves no session and no health behind`() { + val stored = AtomicReference(listOf(AutomaticEndpoint("com.example.notes", server.port, "t"))) + AutomaticServers.install { stored.get() } + val entry = AutomaticServers.servers().single() + McpToolCatalog.connect(entry) + + val started = CountDownLatch(1) + val proceed = CountDownLatch(1) + val source = McpToolSource(delegate) { + started.countDown() + assertTrue("the test never released the worker", proceed.await(10, TimeUnit.SECONDS)) + } + val name = source.listTools().single().name + val future = source.invoke( + mockk { + every { toolName } returns name + every { arguments } returns emptyMap() + every { callId } returns "call-1" + } + ) + assertTrue("the worker never started", started.await(10, TimeUnit.SECONDS)) + + stored.set(emptyList()) + AutomaticServers.refresh() + assertNull("the removal left the entry's health", McpServerHealth.of(entry.id)) + proceed.countDown() + val outcome = future.get(10, TimeUnit.SECONDS) + + assertTrue("the call was not answered: ${outcome.errorMessage}", outcome.isSuccess) + assertNull("the call stored a session for the removed entry", McpConnections.detach(entry.id)) + assertNull("the call brought back the removed entry's health", McpServerHealth.of(entry.id)) + } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/RemovedServerSessionTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/RemovedServerSessionTest.kt new file mode 100644 index 000000000..aeba07efe --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/RemovedServerSessionTest.kt @@ -0,0 +1,108 @@ +package com.itsaky.androidide.plugins.aiagentmcp.tools + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServer +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpSettingsViewModel +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import com.itsaky.androidide.plugins.services.ToolSourceRegistry +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import java.util.concurrent.CountDownLatch +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * A call or a listing made for a server of the user's that is already gone ends the session it + * used. + * + * Such a lookup gets a session that is not kept, since one stored for a server that is gone would + * outlive it with nothing left to end it. But nothing ended the unkept one either, so the server + * kept the session its `initialize` assigned. It is now ended once the call or the listing is done. + * + * The worker is held on a latch before its first line while the server is deleted; nothing sleeps. + */ +class RemovedServerSessionTest { + + private val delegate = Executors.newSingleThreadExecutor() + private val server = FakeMcpServer("", listOf(tool("search", true)), sessionId = "session-1") + private lateinit var plugin: McpPlugin + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + // The Keystore is not there on the JVM; this server has no secrets. + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } returns KeystoreSecretStore.Stored.Absent + every { McpServerStore.headers(any()) } returns emptyMap() + } + + @After + fun tearDown() { + delegate.shutdownNow() + McpConnections.closeAll() + McpToolCatalog.clear() + server.stop() + plugin.dispose() + unmockkObject(McpServerStore) + } + + @Test + fun `a call that outlives its server's removal ends the session it used`() { + val saved = save() + McpToolCatalog.connect(saved) + McpServerStore.setToolEnabled(saved.id, "search", true) + val started = CountDownLatch(1) + val proceed = CountDownLatch(1) + val source = McpToolSource(delegate) { + started.countDown() + assertTrue("the test never released the worker", proceed.await(10, TimeUnit.SECONDS)) + } + val name = source.listTools().single().name + val future = source.invoke( + mockk { + every { toolName } returns name + every { arguments } returns emptyMap() + every { callId } returns "call-1" + } + ) + assertTrue("the worker never started", started.await(10, TimeUnit.SECONDS)) + + McpSettingsViewModel { null }.deleteNow(saved.id) + val ended = deletes() + proceed.countDown() + val outcome = future.get(10, TimeUnit.SECONDS) + + assertTrue("the call was not answered: ${outcome.errorMessage}", outcome.isSuccess) + assertEquals("the session the call used for the removed server was never ended", ended + 1, deletes()) + } + + @Test + fun `a listing of a server already removed ends the session it used`() { + val saved = save() + McpSettingsViewModel { null }.deleteNow(saved.id) + + McpToolCatalog.connect(saved) + + assertEquals("the session the listing used for the removed server was never ended", 1, deletes()) + } + + private fun save(): McpServer = + McpServerStore.saveDetails(McpServerStore.newServer("Docs", "http://127.0.0.1:${server.port}/mcp")) + + private fun deletes() = server.requests.count { it.httpMethod == "DELETE" } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/SameServerCancelTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/SameServerCancelTest.kt new file mode 100644 index 000000000..003a0c494 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/SameServerCancelTest.kt @@ -0,0 +1,241 @@ +package com.itsaky.androidide.plugins.aiagentmcp.tools + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServer +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import com.itsaky.androidide.plugins.services.ToolSourceRegistry +import com.sun.net.httpserver.HttpServer +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import java.net.InetSocketAddress +import java.util.concurrent.CompletableFuture +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.CountDownLatch +import java.util.concurrent.ExecutorService +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicInteger +import org.json.JSONArray +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * Cancelling one tool call stops that call and nothing else on the same server. + * + * Every call to a server, the health probe's listing and a SQLite debugger entry's relisting share + * one session. The session used to hold one connection for a cancel to drop: whichever request had + * published last. Cancelling call A while call B, or the probe, was in flight dropped B's or the + * probe's socket instead (the probe then marked the server degraded), and A's own request went out + * and ran to its timeout. Each call now publishes its requests to its own handle. + * + * A is cancelled while its `tools/call` request reads its credentials, the point at which it has + * no connection of its own yet and the other request's is the session's latest. Every wait ends on + * a latch or a worker finishing; nothing sleeps. + */ +class SameServerCancelTest { + + private val pool = Executors.newFixedThreadPool(2) + + /** Ended latches, one per worker in the order the calls were invoked. */ + private val workerEnded = List(2) { CountDownLatch(1) } + private val scheduled = AtomicInteger(0) + private val executor = object : ExecutorService by pool { + override fun execute(command: Runnable) { + val ended = workerEnded[scheduled.getAndIncrement()] + pool.execute { + try { + command.run() + } finally { + ended.countDown() + } + } + } + } + private val source = McpToolSource(executor) + + private val armed = AtomicBoolean(false) + private val reads = AtomicInteger(0) + + /** Which calls' `tools/call` reached the server, by their `who` argument. */ + private val calls = CopyOnWriteArrayList() + + /** Held: B's `tools/call` stays in flight until [release]. */ + private val bArrived = CountDownLatch(1) + + /** Held when set: the next `tools/list` stays in flight until [release]. */ + private val holdListing = AtomicBoolean(false) + private val listingArrived = CountDownLatch(1) + private val release = CountDownLatch(1) + + private val handlers = Executors.newCachedThreadPool() + private lateinit var http: HttpServer + private lateinit var plugin: McpPlugin + private lateinit var docs: McpServer + private lateinit var name: String + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + // Once armed, A reads the token twice: for its session lookup, then for its tools/call + // request's credentials, which is where A is cancelled. + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } answers { + if (armed.get() && reads.incrementAndGet() == CREDENTIALS_READ) { + armed.set(false) + source.cancel(CALL_A) + } + KeystoreSecretStore.Stored.Absent + } + every { McpServerStore.headers(any()) } returns emptyMap() + http = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply { + // Concurrent, so a held request does not hold the others behind it. + executor = handlers + createContext("/mcp") { exchange -> answer(exchange) } + start() + } + docs = McpServerStore.saveDetails( + McpServerStore.newServer("Docs", "http://127.0.0.1:${http.address.port}/mcp") + ) + McpToolCatalog.connect(docs) + McpServerStore.setToolEnabled(docs.id, "search", true) + name = source.listTools().single().name + } + + @After + fun tearDown() { + release.countDown() + source.close() + pool.shutdownNow() + McpConnections.closeAll() + McpToolCatalog.clear() + http.stop(0) + handlers.shutdownNow() + plugin.dispose() + unmockkObject(McpServerStore) + } + + /** The MCP methods this test needs, holding B's call and, when asked, one listing. */ + private fun answer(exchange: com.sun.net.httpserver.HttpExchange) { + if (exchange.requestMethod == "DELETE") { + exchange.sendResponseHeaders(200, -1) + exchange.close() + return + } + val request = JSONObject(exchange.requestBody.use { String(it.readBytes()) }) + val id = request.opt("id") + if (id == null) { + exchange.sendResponseHeaders(202, -1) + exchange.close() + return + } + val result = when (request.getString("method")) { + "initialize" -> JSONObject().put("protocolVersion", "2025-03-26") + "tools/list" -> { + if (holdListing.getAndSet(false)) { + listingArrived.countDown() + release.await(10, TimeUnit.SECONDS) + } + JSONObject().put("tools", JSONArray(listOf(tool("search", true)))) + } + "tools/call" -> { + val who = request.getJSONObject("params").getJSONObject("arguments").optString("who") + calls += who + if (who == CALL_B) { + bArrived.countDown() + release.await(10, TimeUnit.SECONDS) + } + JSONObject().put( + "content", + JSONArray().put(JSONObject().put("type", "text").put("text", "ok $who")), + ) + } + else -> JSONObject() + } + val bytes = JSONObject().put("jsonrpc", "2.0").put("id", id).put("result", result) + .toString().toByteArray() + exchange.responseHeaders.add("Content-Type", "application/json") + // A dropped client is what the old code did to B; the write failing then is expected. + runCatching { + exchange.sendResponseHeaders(200, bytes.size.toLong()) + exchange.responseBody.use { it.write(bytes) } + } + exchange.close() + } + + private fun invoke(id: String): CompletableFuture = + source.invoke( + mockk { + every { toolName } returns name + every { arguments } returns mapOf("who" to id) + every { callId } returns id + } + ) + + @Test + fun `cancelling a call leaves another call to the same server alone and sends nothing`() { + val b = invoke(CALL_B) + assertTrue("B never reached the server", bArrived.await(10, TimeUnit.SECONDS)) + + armed.set(true) + invoke(CALL_A) + assertTrue("A's worker never finished", workerEnded[1].await(10, TimeUnit.SECONDS)) + release.countDown() + val outcome = b.get(10, TimeUnit.SECONDS) + + assertFalse("A was never cancelled", armed.get()) + assertTrue("B was never cancelled but failed: ${outcome.errorMessage}", outcome.isSuccess) + assertEquals("A was cancelled but its request went out", listOf(CALL_B), calls.toList()) + } + + @Test + fun `cancelling a call leaves the probe's listing of the same server alone`() { + holdListing.set(true) + // The probe's own call, on a thread of its own as the probe's coroutine would be. + var listing: Result? = null + val probe = Thread { listing = runCatching { McpToolCatalog.connect(docs) } }.apply { start() } + assertTrue("the listing never reached the server", listingArrived.await(10, TimeUnit.SECONDS)) + + armed.set(true) + invoke(CALL_A) + assertTrue("A's worker never finished", workerEnded[0].await(10, TimeUnit.SECONDS)) + release.countDown() + probe.join(10_000) + + assertFalse("A was never cancelled", armed.get()) + val result = requireNotNull(listing) { "the listing never finished" } + assertTrue( + "the listing was never cancelled but failed: ${result.exceptionOrNull()}", + result.isSuccess, + ) + assertNotEquals( + "a cancelled call marked the server degraded", + McpServerHealth.State.DEGRADED, + McpServerHealth.of(docs.id)?.state, + ) + assertEquals("A was cancelled but its request went out", emptyList(), calls.toList()) + } + + private companion object { + const val CALL_A = "a" + const val CALL_B = "b" + + /** The session lookup reads the token first; the `tools/call` request's read is second. */ + const val CREDENTIALS_READ = 2 + } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/StaleServerAfterEditTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/StaleServerAfterEditTest.kt new file mode 100644 index 000000000..f2b6e9aef --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/StaleServerAfterEditTest.kt @@ -0,0 +1,91 @@ +package com.itsaky.androidide.plugins.aiagentmcp.tools + +import com.itsaky.androidide.plugins.PluginContext +import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections +import com.itsaky.androidide.plugins.aiagentmcp.plugin.McpPlugin +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServer +import com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeMcpServer.Companion.tool +import com.itsaky.androidide.plugins.aiagentmcp.testing.FakeSharedPreferences +import com.itsaky.androidide.plugins.security.KeystoreSecretStore +import io.mockk.every +import io.mockk.mockk +import io.mockk.mockkObject +import io.mockk.unmockkObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test + +/** + * A probe or a listing handed one of the user's servers before its URL was edited neither marks + * the server refused nor replaces its session. + * + * Such a caller asks the old URL, which gets no credentials once the server has moved. Its 401 + * marked the server degraded and refused after the edit had cleared that, so the probe skipped it + * until the user edited it again; and its lookup, by id alone, stored a session for the old URL in + * place of the one for the new, ending that one. A server of the user's now counts as configured + * only at the URL it is stored with. + */ +class StaleServerAfterEditTest { + + private val before = FakeMcpServer("t", listOf(tool("search", true)), sessionId = "before") + private val after = FakeMcpServer("t", listOf(tool("search", true)), sessionId = "after") + + private lateinit var plugin: McpPlugin + private lateinit var stale: McpServer + private lateinit var current: McpServer + + @Before + fun setUp() { + val context = mockk(relaxed = true) + every { context.getPluginSharedPreferences(any()) } returns FakeSharedPreferences() + plugin = McpPlugin().also { it.initialize(context) } + // The Keystore is not there on the JVM. + mockkObject(McpServerStore) + every { McpServerStore.token(any()) } returns KeystoreSecretStore.Stored.Value("t") + every { McpServerStore.headers(any()) } returns emptyMap() + + // A probe read the server, then the user moved it, and the new URL was listed. + stale = McpServerStore.saveDetails(McpServerStore.newServer("Docs", url(before))) + current = McpServerStore.saveDetails(stale.copy(url = url(after))) + McpServerHealth.credentialChanged(current.id) + McpToolCatalog.connect(current) + } + + @After + fun tearDown() { + McpConnections.closeAll() + McpToolCatalog.clear() + before.stop() + after.stop() + plugin.dispose() + unmockkObject(McpServerStore) + } + + @Test + fun `a listing of the old URL after the edit does not mark the server refused`() { + assertThrows(Exception::class.java) { McpToolCatalog.connect(stale) } + + assertEquals( + "a listing of the old URL changed the moved server's health", + McpServerHealth.Health(McpServerHealth.State.AVAILABLE), + McpServerHealth.of(current.id), + ) + } + + @Test + fun `a listing of the old URL after the edit does not replace the stored session`() { + assertThrows(Exception::class.java) { McpToolCatalog.connect(stale) } + + assertTrue( + "the session for the new URL was ended to store one for the old", + after.requests.none { it.httpMethod == "DELETE" }, + ) + } + + private fun url(server: FakeMcpServer) = "http://127.0.0.1:${server.port}/mcp" +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/CancelledExchangeLogTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/CancelledExchangeLogTest.kt new file mode 100644 index 000000000..af814906a --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/CancelledExchangeLogTest.kt @@ -0,0 +1,121 @@ +package com.itsaky.androidide.plugins.aiagentmcp.transport + +import com.itsaky.androidide.plugins.aiagentmcp.client.McpCallHandle +import com.itsaky.androidide.plugins.aiagentmcp.errors.McpTranscript +import com.sun.net.httpserver.HttpServer +import java.io.InterruptedIOException +import java.net.InetSocketAddress +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.atomic.AtomicInteger +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * A request its caller cancels before it is sent is recorded in the connection log as cancelled, + * not as a request that went out. + * + * The record was built the same way whether the request had gone out or not, so the log showed + * the request's headers and body marked as sent, then "no response". It now says the request was + * cancelled before it was sent, and shows none of it as sent. + * + * A cancel the call's handle catches as the request publishes its connection, before the checks + * below it, is recorded the same way; it left no record at all, so the log did not show the request. + * + * Only a cancel is recorded so. The check caught every Throwable to mark the record, so an + * OutOfMemoryError while checking was logged as a cancel; an Error now propagates unmarked. + */ +class CancelledExchangeLogTest { + + private val bodies = AtomicInteger(0) + + private val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply { + createContext("/mcp") { exchange -> + exchange.requestBody.use { it.readBytes() } + bodies.incrementAndGet() + exchange.sendResponseHeaders(202, -1) + exchange.close() + } + start() + } + + private val labels = object : McpTranscript.Labels { + override fun hidden(length: Int) = "<$length hidden>" + override fun omitted(count: Int) = "<$count more>" + override val nothingSent = "" + override val cancelled = "" + } + + @After + fun tearDown() { + server.stop(0) + } + + @Test + fun `a request cancelled before it is sent is logged as cancelled, not as sent`() { + val exchanges = CopyOnWriteArrayList() + val cancel = InterruptedIOException("The tool call was cancelled before its request was sent") + + assertThrows(InterruptedIOException::class.java) { + McpHttpClient().post( + url = "http://127.0.0.1:${server.address.port}/mcp", + token = "", + body = JSONObject().put("jsonrpc", "2.0").put("id", 1).put("method", "tools/call"), + beforeSend = { throw cancel }, + exchangeListener = { exchange, _ -> exchanges += exchange }, + ) + } + val transcript = McpTranscript.render(exchanges.toList(), cancel, labels) { it } + + assertEquals("the cancelled request reached the server", 0, bodies.get()) + assertTrue("the record does not say the request was cancelled", exchanges.single().cancelled) + assertFalse( + "the transcript shows the cancelled request as sent:\n$transcript", + transcript.lines().any { it.startsWith(">") }, + ) + assertTrue("the transcript does not say it was cancelled:\n$transcript", "* " in transcript) + } + + @Test + fun `a request cancelled as its connection is published is logged as cancelled`() { + val exchanges = CopyOnWriteArrayList() + val handle = McpCallHandle().apply { cancel() } + + val cancel = assertThrows(InterruptedIOException::class.java) { + McpHttpClient().post( + url = "http://127.0.0.1:${server.address.port}/mcp", + token = "", + body = JSONObject().put("jsonrpc", "2.0").put("id", 1).put("method", "tools/call"), + onConnected = { handle.attach(it) }, + exchangeListener = { exchange, _ -> exchanges += exchange }, + ) + } + val transcript = McpTranscript.render(exchanges.toList(), cancel, labels) { it } + + assertEquals("the cancelled request reached the server", 0, bodies.get()) + assertEquals("the cancelled request left no record in the connection log", 1, exchanges.size) + assertTrue("the record does not say the request was cancelled", exchanges.single().cancelled) + assertTrue("the transcript does not say it was cancelled:\n$transcript", "* " in transcript) + } + + @Test + fun `an Error from the check before sending is not logged as a cancel`() { + val exchanges = CopyOnWriteArrayList() + + assertThrows(OutOfMemoryError::class.java) { + McpHttpClient().post( + url = "http://127.0.0.1:${server.address.port}/mcp", + token = "", + body = JSONObject().put("jsonrpc", "2.0").put("id", 1).put("method", "tools/call"), + beforeSend = { throw OutOfMemoryError("reading the cancel flag") }, + exchangeListener = { exchange, _ -> exchanges += exchange }, + ) + } + + assertFalse("an OutOfMemoryError was recorded as a cancel", exchanges.single().cancelled) + } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepthTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepthTest.kt new file mode 100644 index 000000000..5b17e6890 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonDepthTest.kt @@ -0,0 +1,100 @@ +package com.itsaky.androidide.plugins.aiagentmcp.transport + +import com.itsaky.androidide.plugins.aiagentmcp.transport.JsonDepth.Refusal +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +/** + * The scan that keeps a server's deeply nested JSON from any parser. It may count too many + * brackets, which only refuses a body a parser could have read, never too few. Each refusal names + * the rule that tripped, too deep or not strict JSON, which is what the server's author is told. + */ +class JsonDepthTest { + + @Test + fun `nesting at the limit passes and one level more does not`() { + val depth = JsonDepth.MAX + assertNull(JsonDepth.refusal("[".repeat(depth) + "]".repeat(depth))) + assertEquals(Refusal.TooDeep(depth), JsonDepth.refusal("[".repeat(depth + 1) + "]".repeat(depth + 1))) + } + + @Test + fun `brackets inside strings do not count`() { + val brackets = "[".repeat(500) + // An escaped quote at the start of "b" and an escaped backslash at its end: neither ends it. + assertNull(JsonDepth.refusal("""{"a":"$brackets","b":"\"$brackets\\","c":["$brackets"]}""")) + } + + @Test + fun `the characters refused outside a string are read as text inside one`() { + val brackets = "[".repeat(500) + val text = """{"a":"it's; a=b // c /* d */ # e","b":["'$brackets;=/#"],"c" : [ "x" , "y" ]}""" + assertNull(JsonDepth.refusal(text)) + } + + @Test + fun `valid strict JSON is accepted`() { + listOf( + // A byte order mark, which a JSON parser may ignore and Android's org.json skips. + "\uFEFF{\"a\":1}", + """{"n":1e5,"m":-0.5,"p":1E-3,"z":-0,"t":true,"f":false,"x":null}""", + """{"s":"é","u":"\u00e9","q":"\"\\\/"}""", + """{"a":[[],[[]],{"b":[]}],"o":{}}""", + """[{"jsonrpc":"2.0","id":1,"result":{}}]""", + ).forEach { text -> assertNull("refused: $text", JsonDepth.refusal(text)) } + } + + @Test + fun `a single-quoted string is refused`() { + // Not JSON; Android's org.json reads it, and a quote inside it hides nothing from that parser. + assertEquals(Refusal.NotStrict('\''), JsonDepth.refusal("['a']")) + } + + @Test + fun `a semicolon separator hiding a closing bracket is refused`() { + // Android's org.json reads ';' as a separator and "]" as a string, so each unit opens one + // more array; a scan that took the quote for text counted each "]" as a close. + assertEquals(Refusal.NotStrict(';'), JsonDepth.refusal("[;\"]\";".repeat(5_000))) + } + + @Test + fun `a comment hiding a closing bracket is refused`() { + // Android's org.json skips "//]" to the end of the line, so each unit opens one more array. + assertEquals(Refusal.NotStrict('/'), JsonDepth.refusal("[//]\n".repeat(5_000))) + } + + @Test + fun `a quote inside unquoted text is refused`() { + // Android's org.json reads `a"` as one unquoted string, so the brackets after the comma + // are arrays nested in it, not text inside a string the quote opened. + assertEquals(Refusal.NotStrict('"'), JsonDepth.refusal("[a\",${"[".repeat(5_000)}")) + assertEquals(Refusal.NotStrict('"'), JsonDepth.refusal("""{"x":1",${"[".repeat(5_000)}""")) + } + + @Test + fun `the brackets after a double quote inside a single-quoted string count`() { + // org.json reads '"' as a one-character string, then recurses into the brackets after it. + assertEquals(Refusal.NotStrict('\''), JsonDepth.refusal("['\"',${"[".repeat(200)}", 100)) + } + + @Test + fun `the brackets after a quote where no value starts count`() { + // Android's org.json skips the comment, so no string starts at its quote. + assertEquals(Refusal.NotStrict('/'), JsonDepth.refusal("[/*\"*/${"[".repeat(200)}", 100)) + } + + @Test + fun `a single quote is named in words and every other character is shown in quotes`() { + assertEquals( + "a single quote", + Refusal.NotStrict('\'').reason.substringAfter("string (found ").removeSuffix(")"), + ) + listOf('/', ';', '=', '#', '"').forEach { c -> + assertEquals( + "'$c'", + Refusal.NotStrict(c).reason.substringAfter("string (found ").removeSuffix(")"), + ) + } + } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonRpcTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonRpcTest.kt index 6082465d6..99c24680d 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonRpcTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/JsonRpcTest.kt @@ -3,6 +3,7 @@ package com.itsaky.androidide.plugins.aiagentmcp.transport import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows import org.junit.Assert.assertTrue import org.junit.Test @@ -102,4 +103,63 @@ class JsonRpcTest { assertNull(reply) } + + /** + * The org.json these tests run on turns a parse that runs out of stack into a JSONException; + * Android's lets the StackOverflowError through. The refusal must come from the guard, before + * either parser runs, so the type is what this asserts. + */ + @Test + fun givenAReplyNestedTenThousandDeep_whenParsed_thenItIsRefusedBeforeAnyParserRuns() { + assertThrows(JsonRpc.UnparsedReplyException::class.java) { JsonRpc.parseReply("[".repeat(10_000)) } + } + + @Test + fun givenAWellFormedReplyNestedPastTheLimit_whenParsed_thenItIsRefused() { + val nested = "[".repeat(JsonDepth.MAX) + "]".repeat(JsonDepth.MAX) + val payload = """{"jsonrpc":"2.0","id":"7","result":{"tools":[],"extra":$nested}}""" + + assertThrows(JsonRpc.UnparsedReplyException::class.java) { JsonRpc.parseReply(payload) } + } + + @Test + fun givenAReplyOneLevelPastTheLimit_whenParsed_thenTheDepthIsTheReason() { + val depth = JsonDepth.MAX + 1 + val failure = assertThrows(JsonRpc.UnparsedReplyException::class.java) { + JsonRpc.parseReply("[".repeat(depth) + "]".repeat(depth)) + } + + assertEquals(JsonDepth.Refusal.TooDeep(JsonDepth.MAX).reason, failure.message) + } + + @Test + fun givenAReplyWithAComment_whenParsed_thenNotStrictJsonIsTheReason() { + val payload = """{"jsonrpc":"2.0","id":"7","result":{}} // done""" + + val failure = assertThrows(JsonRpc.UnparsedReplyException::class.java) { JsonRpc.parseReply(payload) } + + assertEquals(JsonDepth.Refusal.NotStrict('/').reason, failure.message) + } + + @Test + fun givenValidStrictJsonAfterAByteOrderMark_whenParsed_thenItIsRead() { + val payload = "\uFEFF" + + """{"jsonrpc":"2.0","id":"7","result":{"n":1e5,"m":-0.5,"s":"é","a":[[],[[]],{"b":[]}]}}""" + + val result = JsonRpc.parseReply(payload)?.result + + assertEquals(1e5, result?.getDouble("n")) + assertEquals(-0.5, result?.getDouble("m")) + assertEquals("é", result?.getString("s")) + assertEquals(3, result?.getJSONArray("a")?.length()) + } + + @Test + fun givenAReplyNestedWithinTheLimit_whenParsed_thenItIsRead() { + val depth = JsonDepth.MAX - 3 + val nested = "[".repeat(depth) + "]".repeat(depth) + val payload = """{"jsonrpc":"2.0","id":"7","result":{"extra":$nested}}""" + + assertEquals("7", JsonRpc.parseReply(payload)?.id) + } } diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClientDrainTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClientDrainTest.kt new file mode 100644 index 000000000..f21bb344e --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClientDrainTest.kt @@ -0,0 +1,316 @@ +package com.itsaky.androidide.plugins.aiagentmcp.transport + +import com.sun.net.httpserver.HttpServer +import java.io.IOException +import java.io.InputStream +import java.net.InetSocketAddress +import java.util.Arrays +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The body of a `202 Accepted`, which should be empty, is read to its end so its socket can be + * reused, through a fixed buffer: a server answering a notification with a huge body must not cost + * Code on the Go its memory, and an OutOfMemoryError while reading one is the process failing, not + * the read, so it reaches the IDE's uncaught-exception handler. A body that runs past the drain's + * budget is abandoned and its socket disconnected, so one that never ends cannot hold the handshake. + */ +class McpHttpClientDrainTest { + + /** [size] bytes of `a`, made as they are read; records how far it was read and whether it was closed. */ + private class GeneratedBody(private val size: Long) : InputStream() { + var position = 0L + var closed = false + + override fun read(): Int = if (position < size) 'a'.code.also { position++ } else -1 + + override fun read(b: ByteArray, off: Int, len: Int): Int { + if (position >= size) return -1 + val n = minOf(len.toLong(), size - position).toInt() + Arrays.fill(b, off, off + n, 'a'.code.toByte()) + position += n + return n + } + + override fun close() { + closed = true + } + } + + @Test + fun `a large body within the budget is read to its end but only its start is kept`() { + val size = McpHttpClient.DRAIN_BUDGET_CHARS / 2 + val body = GeneratedBody(size) + + val drained = McpHttpClient.drain(keep = 100) { body }.getOrThrow() + + assertEquals("characters kept", 100, drained.text.length) + assertEquals("characters dropped", size - 100, drained.dropped) + assertEquals("the body was not read to its end", size, body.position) + assertTrue("the body was not closed", body.closed) + } + + @Test + fun `a body past the budget is abandoned without being read to its end`() { + val keep = 100 + val budget = 64L * 1024 + val body = GeneratedBody(64L * 1024 * 1024) + + val drained = McpHttpClient.drain(keep = keep, budget = budget) { body } + + assertTrue( + "a body past the budget was read to its end: ${body.position} bytes", + drained.exceptionOrNull() is McpHttpClient.DrainBudgetException, + ) + // The reader buffers ahead of what the drain has counted, by at most a buffer or two. + assertTrue("read ${body.position} bytes", body.position <= keep + budget + 64 * 1024) + assertTrue("the body was not closed", body.closed) + } + + @Test + fun `a body that outlasts the deadline is abandoned though it is far inside the budget`() { + var now = 0L + val body = object : InputStream() { + var reads = 0 + var closed = false + override fun read(): Int = 'a'.code.also { now += 4_000; reads++ } + override fun read(b: ByteArray, off: Int, len: Int): Int { + b[off] = read().toByte() + return 1 + } + override fun close() { + closed = true + } + } + + val drained = McpHttpClient.drain(deadlineMs = 10_000, nowMs = { now }) { body } + + assertTrue( + "a trickling body was not abandoned at the deadline: ${drained.exceptionOrNull()}", + drained.exceptionOrNull() is McpHttpClient.DrainBudgetException, + ) + assertEquals("reads before the deadline passed", 3, body.reads) + assertTrue("the body was not closed", body.closed) + } + + @Test + fun `an OutOfMemoryError while draining reaches the caller`() { + val body = object : InputStream() { + override fun read(): Int = throw OutOfMemoryError("reading a 202 body") + } + + assertThrows(OutOfMemoryError::class.java) { McpHttpClient.drain { body } } + } + + @Test + fun `a read that fails with an IOException is a failure the caller survives`() { + val body = object : InputStream() { + override fun read(): Int = throw IOException("connection reset") + } + + assertTrue(McpHttpClient.drain { body }.isFailure) + } + + /** + * A 202 whose body never ends: the POST returns once the drain's budget is spent, and the next + * request arrives on a new connection, so the abandoned socket was disconnected rather than + * pooled. Timed out rather than left to hang, should the drain read forever. + */ + @Test(timeout = 30_000) + fun `a 202 whose body never ends returns within the budget and its socket is not reused`() { + val ports = java.util.concurrent.CopyOnWriteArrayList() + val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply { + createContext("/mcp") { exchange -> + ports += exchange.remoteAddress.port + val request = JSONObject(exchange.requestBody.use { String(it.readBytes()) }) + if (request.optString("method") == "notifications/initialized") { + // Chunked, with no end: written until the client goes away. + exchange.sendResponseHeaders(202, 0) + val chunk = ByteArray(8 * 1024) { 'a'.code.toByte() } + runCatching { exchange.responseBody.use { out -> while (true) out.write(chunk) } } + } else { + val bytes = JSONObject().put("jsonrpc", "2.0").put("id", 1) + .put("result", JSONObject()).toString().toByteArray() + exchange.responseHeaders.add("Content-Type", "application/json") + exchange.sendResponseHeaders(200, bytes.size.toLong()) + exchange.responseBody.use { it.write(bytes) } + } + exchange.close() + } + start() + } + try { + val url = "http://127.0.0.1:${server.address.port}/mcp" + val client = McpHttpClient() + + val accepted = client.post( + url, + "", + JSONObject().put("jsonrpc", "2.0").put("method", "notifications/initialized"), + ) + client.post(url, "", JSONObject().put("jsonrpc", "2.0").put("id", 1).put("method", "ping")) + + assertNull(accepted.document) + assertEquals("requests seen", 2, ports.size) + assertNotEquals("the abandoned socket was reused", ports[0], ports[1]) + } finally { + server.stop(0) + } + } + + /** + * A 202 whose body trickles a byte at a time, never tripping a read timeout: the POST returns + * at the drain's deadline and the next request arrives on a new connection. + */ + @Test(timeout = 30_000) + fun `a 202 body that trickles returns at the deadline and its socket is not reused`() { + val ports = java.util.concurrent.CopyOnWriteArrayList() + val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply { + createContext("/mcp") { exchange -> + ports += exchange.remoteAddress.port + val request = JSONObject(exchange.requestBody.use { String(it.readBytes()) }) + if (request.optString("method") == "notifications/initialized") { + exchange.sendResponseHeaders(202, 0) + runCatching { + exchange.responseBody.use { out -> + while (true) { + out.write('a'.code) + out.flush() + Thread.sleep(20) + } + } + } + } else { + val bytes = JSONObject().put("jsonrpc", "2.0").put("id", 1) + .put("result", JSONObject()).toString().toByteArray() + exchange.responseHeaders.add("Content-Type", "application/json") + exchange.sendResponseHeaders(200, bytes.size.toLong()) + exchange.responseBody.use { it.write(bytes) } + } + exchange.close() + } + start() + } + try { + val url = "http://127.0.0.1:${server.address.port}/mcp" + val client = McpHttpClient(drainDeadlineMs = 300) + + val started = System.nanoTime() + val accepted = client.post( + url, + "", + JSONObject().put("jsonrpc", "2.0").put("method", "notifications/initialized"), + ) + val tookMs = (System.nanoTime() - started) / 1_000_000 + client.post(url, "", JSONObject().put("jsonrpc", "2.0").put("id", 1).put("method", "ping")) + + assertNull(accepted.document) + assertTrue("the drain took $tookMs ms against a 300 ms deadline", tookMs < 5_000) + assertEquals("requests seen", 2, ports.size) + assertNotEquals("the abandoned socket was reused", ports[0], ports[1]) + } finally { + server.stop(0) + } + } + + /** The control for the test above: a 202 with no body leaves its socket for the next request. */ + @Test + fun `a 202 with no body leaves its socket for the next request`() { + val ports = java.util.concurrent.CopyOnWriteArrayList() + val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply { + createContext("/mcp") { exchange -> + ports += exchange.remoteAddress.port + exchange.requestBody.use { it.readBytes() } + exchange.sendResponseHeaders(202, -1) + exchange.close() + } + start() + } + try { + val url = "http://127.0.0.1:${server.address.port}/mcp" + val client = McpHttpClient() + val notification = JSONObject().put("jsonrpc", "2.0").put("method", "notifications/initialized") + + client.post(url, "", notification) + client.post(url, "", notification) + + assertEquals("requests seen", 2, ports.size) + assertEquals("a drained 202 did not leave its socket for reuse", ports[0], ports[1]) + } finally { + server.stop(0) + } + } + + /** The drain as [McpHttpClient.post] uses it: the record shows the start and counts the rest. */ + @Test + fun `a 202 with a large body is recorded capped with the rest counted`() { + val size = 100 * 1024 + val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply { + createContext("/mcp") { exchange -> + exchange.requestBody.use { it.readBytes() } + exchange.sendResponseHeaders(202, size.toLong()) + exchange.responseBody.use { it.write(ByteArray(size) { 'a'.code.toByte() }) } + } + start() + } + try { + var recorded: McpExchange? = null + val response = McpHttpClient().post( + "http://127.0.0.1:${server.address.port}/mcp", + "", + JSONObject().put("jsonrpc", "2.0").put("method", "notifications/initialized"), + exchangeListener = { exchange, _ -> recorded = exchange }, + ) + + assertNull(response.document) + val body = requireNotNull(recorded?.responseBody) + assertEquals(McpExchange.Body.MAX_CHARS, body.text.length) + assertEquals(size - McpExchange.Body.MAX_CHARS, body.omitted) + } finally { + server.stop(0) + } + } + + /** + * The drain keeps the start of a 202 body and the record masks credentials in what was kept, + * so the cut can fall inside one: the redactor masks whole credentials only, and a copy of the + * token cut in two would show its start. A body of nothing but the token, repeated, with the + * cut inside a copy: the record shows masks and nothing else. + */ + @Test + fun `a 202 body cut inside a repeated credential shows no part of it`() { + val token = "tok_9f2c7e1a4b8d3f6e0a5c9b2d7e4f1a3c5b7d" + val kept = McpHttpClient.DRAINED_CHARS_KEPT + assertTrue("the cut must fall inside a copy of the token", kept % token.length != 0) + val bytes = token.repeat(kept / token.length + 10).toByteArray() + val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply { + createContext("/mcp") { exchange -> + exchange.requestBody.use { it.readBytes() } + exchange.sendResponseHeaders(202, bytes.size.toLong()) + exchange.responseBody.use { it.write(bytes) } + } + start() + } + try { + var recorded: McpExchange? = null + McpHttpClient().post( + "http://127.0.0.1:${server.address.port}/mcp", + token, + JSONObject().put("jsonrpc", "2.0").put("method", "notifications/initialized"), + exchangeListener = { exchange, _ -> recorded = exchange }, + ) + + val text = requireNotNull(recorded?.responseBody).text + val unmasked = text.replace(McpRedactor.MASK, "") + assertEquals("the record kept part of the credential: '$unmasked'", "", unmasked) + assertTrue("the record ends unmasked: '${text.takeLast(16)}'", text.endsWith(McpRedactor.MASK)) + } finally { + server.stop(0) + } + } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClientListenerFailureTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClientListenerFailureTest.kt new file mode 100644 index 000000000..6cf440510 --- /dev/null +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpHttpClientListenerFailureTest.kt @@ -0,0 +1,62 @@ +package com.itsaky.androidide.plugins.aiagentmcp.transport + +import com.sun.net.httpserver.HttpServer +import java.net.InetSocketAddress +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertThrows +import org.junit.Before +import org.junit.Test + +/** + * The exchange listener feeds the connection log, a convenience: one that fails with an Exception + * costs only its record, and the request's reply still reaches the caller. An OutOfMemoryError + * from it is the process failing, not the listener, so it reaches the IDE's uncaught-exception + * handler rather than being swallowed with the record. + */ +class McpHttpClientListenerFailureTest { + + private val reply = """{"jsonrpc":"2.0","id":1,"result":{}}""" + private lateinit var server: HttpServer + + @Before + fun startServer() { + server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply { + createContext("/mcp") { exchange -> + exchange.requestBody.use { it.readBytes() } + val bytes = reply.toByteArray() + exchange.responseHeaders.add("Content-Type", "application/json") + exchange.sendResponseHeaders(200, bytes.size.toLong()) + exchange.responseBody.use { it.write(bytes) } + } + start() + } + } + + @After + fun stopServer() { + server.stop(0) + } + + private fun postWith(listener: McpExchangeListener) = McpHttpClient().post( + "http://127.0.0.1:${server.address.port}/mcp", + "", + JSONObject().put("jsonrpc", "2.0").put("id", 1).put("method", "ping"), + exchangeListener = listener, + ) + + @Test + fun `a listener that throws an Exception costs only its record`() { + val response = postWith { _, _ -> throw IllegalStateException("the log is full") } + + assertEquals(reply, response.document) + } + + @Test + fun `an OutOfMemoryError from the listener reaches the caller`() { + assertThrows(OutOfMemoryError::class.java) { + postWith { _, _ -> throw OutOfMemoryError("recording an exchange") } + } + } +} diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpRedactorTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpRedactorTest.kt index 19ff65a2b..c06279e03 100644 --- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpRedactorTest.kt +++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/transport/McpRedactorTest.kt @@ -1,6 +1,7 @@ package com.itsaky.androidide.plugins.aiagentmcp.transport import org.junit.Assert.assertEquals +import org.junit.Assert.assertThrows import org.junit.Test /** What an exchange record may show: credentials hidden, echoes of them masked, the rest kept. */ @@ -127,4 +128,50 @@ class McpRedactorTest { assertEquals("https://mcp.example.test/mcp?t=${McpRedactor.MASK} redirected off its origin", message) } + + @Test + fun givenATextCutInsideACredential_whenScrubbedAsCut_thenItEndsInAMask() { + val mask = McpRedactor.MASK + + val shown = redactor("secret-token-123456").scrubCut("ok secret-token-123456 then secret-to") + + assertEquals("ok $mask then $mask", shown) + } + + @Test + fun givenATextCutInsideAnEscapedCredential_whenScrubbedAsCut_thenItEndsInAMask() { + // The cut falls inside the `\u006b` that escapes the token's `k`. + val shown = redactor("secret-token").scrubCut("""{"error":"bad secret-to\u006""") + + assertEquals("""{"error":"bad ${McpRedactor.MASK}""", shown) + } + + @Test + fun givenACutInsideACredentialThatStartsInsideAnother_whenScrubbedAsCut_thenNeitherShows() { + // The second credential's start, cut short, begins inside a whole copy of the first. + val shown = redactor("header-value-123456", "123456-token-abcdef").scrubCut("ok header-value-123456-tok") + + assertEquals("ok ${McpRedactor.MASK}", shown) + } + + @Test + fun givenACutThatEndsInNoCredential_whenScrubbedAsCut_thenOnlyWholeOnesAreMasked() { + val shown = redactor("secret-token").scrubCut("secret-token, and the rest") + + assertEquals("${McpRedactor.MASK}, and the rest", shown) + } + + @Test + fun `a URL value that cannot be decoded is still masked as it is`() { + val secrets = McpRedactor.urlSecrets("https://h/mcp?key=abcdefgh1234") { throw IllegalArgumentException("bad") } + + assertEquals(listOf("abcdefgh1234", "abcdefgh1234"), secrets) + } + + @Test + fun `an OutOfMemoryError while decoding a URL value propagates`() { + assertThrows(OutOfMemoryError::class.java) { + McpRedactor.urlSecrets("https://h/mcp?key=abcdefgh1234") { throw OutOfMemoryError("decoding") } + } + } } 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). ---