diff --git a/plugins/AI-Agent-MCP/README.md b/plugins/AI-Agent-MCP/README.md
index 3a9950ed1..66231f117 100644
--- a/plugins/AI-Agent-MCP/README.md
+++ b/plugins/AI-Agent-MCP/README.md
@@ -107,6 +107,29 @@ Servers you add yourself keep the name prefix taken from their label.
at most 12 contributed tools per message (4 for a small on-device model), in
order, and drops the rest; every app has its own entry. Switching the others
on will come with showing this entry in the settings screen (phase 2).
+- Writes (ADFA-7300). The entry's `execute` tool, which runs one statement that
+ changes the app's database, is offered only while **Let the Agent change app
+ databases** is on in this plugin's settings (one switch for every app, off by
+ default, `McpServerStore.allowDatabaseWrites`). It is never declared
+ read-only, whatever hint the server sends (`ReadOnlyTrust.WRITE_TOOLS`,
+ `ReadOnlyTrust.isReadOnly`), so AI-Core asks before every call and never
+ offers "Always Allow" for it. A change is committed at once and cannot be
+ undone. On a Room database the server refuses the first write until the Agent
+ repeats it with `acknowledge_room: true` (ADFA-7299), so that call asks too.
+ While the switch is off, the entry's `query` description adds that the user
+ can switch writes on there and that the databases must not be changed any
+ other way (`ReadOnlyTrust.needsWriteSwitchHint`). Told only "use execute", a
+ tool it did not have, the model asked to run `sqlite3` in the shell instead
+ (a Note 20, 2026-11-25). The shell would not reach another app's private
+ files, but the user was never told about the switch. When SQLite refuses a
+ write sent through `query` ("not authorized", or a read-only database), the
+ same sentence follows the failure's text (`ReadOnlyTrust.isWriteRefusal`),
+ which AI-Core shows under the chat: after a failed call, AI-Core replaces the
+ Agent's own answer with "I couldn't complete that, the last action failed".
+ With the switch on, each app offers five tools, in the order the server lists
+ them (today `list_databases`, `get_schema`, `query`, `execute`, `get_events`),
+ so two apps take 10 of AI-Core's 12 slots, and in compact mode (4) AI-Core
+ drops the first app's `get_events` and every later tool.
- 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
diff --git a/plugins/AI-Agent-MCP/ai-agent-mcp.html b/plugins/AI-Agent-MCP/ai-agent-mcp.html
index c857fc016..732ac5806 100644
--- a/plugins/AI-Agent-MCP/ai-agent-mcp.html
+++ b/plugins/AI-Agent-MCP/ai-agent-mcp.html
@@ -151,7 +151,9 @@
Usage
New tools always arrive switched off, including on the connection
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
+ supplies for your own debug app. Its tool that changes the app's database, execute, is offered
+ only after you turn on Let the Agent change app databases, and every call of it asks for
+ your approval. Nothing a server adds later becomes visible to the model
without your say-so.
diff --git a/plugins/AI-Agent-MCP/build.gradle.kts b/plugins/AI-Agent-MCP/build.gradle.kts
index 5dc962237..0b31e31ef 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 = 3
- versionName = "2.0.0"
+ versionCode = 4
+ versionName = "2.1.0"
}
buildFeatures {
diff --git a/plugins/AI-Agent-MCP/src/main/assets/docs/index.html b/plugins/AI-Agent-MCP/src/main/assets/docs/index.html
index be9b9b44b..23447fc88 100644
--- a/plugins/AI-Agent-MCP/src/main/assets/docs/index.html
+++ b/plugins/AI-Agent-MCP/src/main/assets/docs/index.html
@@ -86,6 +86,14 @@ Choosing tools
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 one switch it has is Let the Agent change app databases, at the top
+ of the MCP servers screen, off at first. While it is on, every app's SQLite
+ debugger entry also offers execute, which runs one SQL statement that
+ changes data or the schema. The Agent asks for your approval before every
+ change, and "Always Allow" is never offered for it. A change is saved at once
+ and can't be undone. For an app that uses Room, the first change is refused
+ until the Agent asks you again, because Room doesn't notice it and the app can
+ show old data until it reads the database again.
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.
diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt
index d1a4d6c28..59943e672 100644
--- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt
+++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/AutomaticServers.kt
@@ -253,18 +253,25 @@ object AutomaticServers {
return changed
}
- /** The entries to offer, with their tool switches already decided by [ReadOnlyTrust]. */
- fun servers(): List = states.map { (id, state) ->
+ /**
+ * The entries to offer, with their tool switches already decided by [ReadOnlyTrust] and the
+ * settings switch for database writes.
+ */
+ fun servers(): List {
+ val allowWrites = McpServerStore.allowDatabaseWrites()
+ return states.map { (id, state) -> server(id, state, allowWrites) }
+ }
+
+ private fun server(id: String, state: State, allowWrites: Boolean) =
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),
+ enabledTools = ReadOnlyTrust.enabledTools(state.tools, allowWrites),
automatic = true,
)
- }
fun isAutomatic(serverId: String): Boolean = serverId.startsWith(ID_PREFIX)
diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReadOnlyTrust.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReadOnlyTrust.kt
index 6741e97ac..c2c76b5cc 100644
--- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReadOnlyTrust.kt
+++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReadOnlyTrust.kt
@@ -34,12 +34,57 @@ object ReadOnlyTrust {
*/
val CORE_TOOLS: Set = linkedSetOf("list_databases", "get_schema", "query", "get_events")
+ /**
+ * The SQLite debugger's tools that change an app's database (ADFA-7300). Switched on only by the
+ * settings switch [com.itsaky.androidide.plugins.aiagentmcp.settings.McpServerStore.allowDatabaseWrites],
+ * and never read-only, whatever hint the server sends: "Always Allow" must never cover a write.
+ */
+ val WRITE_TOOLS: Set = linkedSetOf("execute")
+
/**
* @param tools what `tools/list` returned.
- * @return the names of the [CORE_TOOLS] that declared `annotations.readOnlyHint` as boolean true.
+ * @param allowWrites the user switched on database writes in this plugin's settings.
+ * @return the names of the [CORE_TOOLS] that declared `annotations.readOnlyHint` as boolean true,
+ * then, when [allowWrites], the listed [WRITE_TOOLS].
+ */
+ fun enabledTools(tools: List, allowWrites: Boolean = false): Set {
+ val on = tools.filter { isReadOnly(it) && it.name in CORE_TOOLS }.mapTo(linkedSetOf()) { it.name }
+ if (allowWrites) tools.filter { it.name in WRITE_TOOLS }.mapTo(on) { it.name }
+ return on
+ }
+
+ /**
+ * Whether this plugin declares [tool] of an SQLite debugger entry read-only to AI-Core, which then
+ * offers "Always Allow" for it. A [WRITE_TOOLS] tool never is, even if its server claims the hint.
+ */
+ fun isReadOnly(tool: McpTool): Boolean = tool.readOnlyHint && tool.name !in WRITE_TOOLS
+
+ /**
+ * Whether [toolName] of an SQLite debugger entry should tell the model how writes get allowed: it
+ * is `query`, whose own description says "Writes are refused: use execute", and the entry's server
+ * offers a [WRITE_TOOLS] tool that the settings switch keeps off. Told only to use a tool it does
+ * not have, the model looked for another way: on a Note 20 it asked to run `sqlite3` in the shell
+ * (ADFA-7300, 2026-11-25).
+ *
+ * @param knownTools every tool the server listed.
+ * @param enabledTools the tools offered now.
+ */
+ fun needsWriteSwitchHint(toolName: String, knownTools: Collection, enabledTools: Collection): Boolean =
+ toolName == "query" && WRITE_TOOLS.any { it in knownTools && it !in enabledTools }
+
+ /**
+ * Whether [message], a failed `query`'s text, is SQLite refusing a write on the server's read-only
+ * connection: "not authorized" from its authorizer, or "attempt to write a readonly database" from
+ * `query_only`. On a Note 20 the model sent an INSERT through `query`, and that refusal was the last
+ * thing the chat showed (ADFA-7300, 2026-11-25).
+ *
+ * It also matches a refused BEGIN, SAVEPOINT, ATTACH or setting PRAGMA, which `execute` refuses
+ * too, so the hint then names a switch that would not help. Accepted: the server reports every
+ * refusal as SQLite's plain "not authorized", and copying its authorizer's rules here would drift.
*/
- fun enabledTools(tools: List): Set =
- tools.filter { it.readOnlyHint && it.name in CORE_TOOLS }.mapTo(linkedSetOf()) { it.name }
+ fun isWriteRefusal(message: String?): Boolean =
+ message != null && (message.contains("not authorized", ignoreCase = true) ||
+ message.contains("readonly database", ignoreCase = true))
/**
* Reads the hint from one `tools/list` entry's `annotations`.
diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/plugin/McpPlugin.kt
index 2434288e8..f004d7629 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
@@ -146,6 +146,7 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension {
const val TOOLTIP_TAG_HEADER_VALUE = "mcp_header_value"
const val TOOLTIP_TAG_HEADER_REMOVE = "mcp_header_remove"
const val TOOLTIP_TAG_BACK = "mcp_back"
+ const val TOOLTIP_TAG_ALLOW_DATABASE_WRITES = "mcp_allow_database_writes"
/**
* Logs a failure that escaped a coroutine of [newScope]. Platform logging, not
@@ -648,10 +649,12 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension {
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).
+ doesn't list that entry on the MCP servers screen. Its tool that changes the
+ app's database, execute, stays off until you turn on Let the Agent change
+ app databases on that 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). Never
+ for execute.
""".trimIndent(),
buttons = listOf(
PluginTooltipButton(
@@ -697,6 +700,26 @@ class McpPlugin : IPlugin, SettingsExtension, DocumentationExtension {
),
),
),
+ PluginTooltipEntry(
+ tag = TOOLTIP_TAG_ALLOW_DATABASE_WRITES,
+ summary = "Lets the Agent change the databases of apps you build with the SQLite debugger. It asks you before every change.",
+ detail = """
+ When this is on, each app's SQLite debugger entry offers its execute tool,
+ which runs one SQL statement that changes data or the schema. The Agent asks
+ for your approval every time, and Always Allow is never offered for it.
+ A change is saved at once and can't be undone. For an app that uses Room, the
+ first change asks you again, because Room doesn't notice it: the app can show
+ old data until it reads the database again.
+ """.trimIndent(),
+ buttons = listOf(
+ PluginTooltipButton(
+ description = "Learn more",
+ uri = "i/ai-addons-other.html#mcp",
+ order = 0,
+ directPath = true,
+ ),
+ ),
+ ),
PluginTooltipEntry(
tag = TOOLTIP_TAG_SERVER_ENABLED,
summary = "Turns this server on or off without deleting it.",
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 e648bebb7..d6d5b744a 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
@@ -31,6 +31,7 @@ object McpServerStore {
private const val KEY_SERVERS = "servers"
private const val KEY_TOKEN_PREFIX = "token_"
private const val KEY_HEADERS_PREFIX = "headers_"
+ private const val KEY_ALLOW_DATABASE_WRITES = "allowDatabaseWrites"
private const val FIELD_ID = "id"
private const val FIELD_NAME = "name"
@@ -269,6 +270,32 @@ object McpServerStore {
fireChanged()
}
+ /**
+ * Whether the SQLite debugger entries offer their tools that change an app's database
+ * (`ReadOnlyTrust.WRITE_TOOLS`, ADFA-7300). Off unless the user switched it on; every call of
+ * such a tool still asks, and none is read-only, so "Always Allow" never covers one.
+ */
+ fun allowDatabaseWrites(): Boolean = prefs()?.getBoolean(KEY_ALLOW_DATABASE_WRITES, false) ?: false
+
+ /**
+ * Switches [allowDatabaseWrites], then tells the listeners, so the Agent's tool list follows.
+ *
+ * @return false when the value could not be stored, and the switch is then unchanged. A failed
+ * commit still leaves the new value in SharedPreferences' memory, where it would hold until the
+ * app restarts and then turn back, so it is put back to the stored one.
+ */
+ fun setAllowDatabaseWrites(allow: Boolean): Boolean {
+ val prefs = prefs() ?: return false
+ val stored = prefs.getBoolean(KEY_ALLOW_DATABASE_WRITES, false)
+ if (!prefs.edit().putBoolean(KEY_ALLOW_DATABASE_WRITES, allow).commit()) {
+ Log.w(TAG, "Could not store the database-writes switch")
+ prefs.edit().putBoolean(KEY_ALLOW_DATABASE_WRITES, stored).commit()
+ return false
+ }
+ fireChanged()
+ return true
+ }
+
/**
* The stored record for [id].
* @param id the server.
diff --git a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsFragment.kt b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsFragment.kt
index 6621e0807..0f629d78a 100644
--- a/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsFragment.kt
+++ b/plugins/AI-Agent-MCP/src/main/kotlin/com/itsaky/androidide/plugins/aiagentmcp/settings/McpSettingsFragment.kt
@@ -11,6 +11,7 @@ import android.widget.EditText
import android.widget.ImageButton
import android.widget.LinearLayout
import android.widget.TextView
+import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
@@ -105,6 +106,25 @@ class McpSettingsFragment : Fragment() {
viewLifecycleOwner.lifecycleScope.launch {
viewModel.servers.collect { servers -> renderServers(view, servers) }
}
+
+ // The switch is set from the store before its listener goes on, so showing it writes nothing.
+ val writes = view.findViewById(R.id.mcpAllowDatabaseWrites)
+ wireTooltip(writes, McpPlugin.TOOLTIP_TAG_ALLOW_DATABASE_WRITES)
+ fun showWrites(allow: Boolean) {
+ writes.setOnCheckedChangeListener(null)
+ writes.isChecked = allow
+ writes.setOnCheckedChangeListener { _, isChecked -> viewModel.setAllowDatabaseWrites(isChecked) }
+ }
+ viewLifecycleOwner.lifecycleScope.launch {
+ viewModel.allowDatabaseWrites.collect { showWrites(it) }
+ }
+ viewLifecycleOwner.lifecycleScope.launch {
+ viewModel.writesNotSaved.collect {
+ showWrites(viewModel.allowDatabaseWrites.value)
+ val text = getString(R.string.mcp_allow_database_writes_not_saved)
+ Toast.makeText(requireContext(), text, Toast.LENGTH_LONG).show()
+ }
+ }
}
override fun onResume() {
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 df01a9433..f3bb0965f 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
@@ -16,8 +16,11 @@ import com.itsaky.androidide.plugins.aiagentmcp.tools.McpToolCatalog
import com.itsaky.androidide.plugins.aiagentmcp.transport.McpExchangeLog
import com.itsaky.androidide.plugins.security.KeystoreSecretStore
import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@@ -39,9 +42,32 @@ class McpSettingsViewModel(
/** The configured servers, re-read after every change. */
val servers: StateFlow> = _servers.asStateFlow()
+ private val _allowDatabaseWrites = MutableStateFlow(McpServerStore.allowDatabaseWrites())
+
+ /** The switch that lets the SQLite debugger entries offer their write tool (ADFA-7300). */
+ val allowDatabaseWrites: StateFlow = _allowDatabaseWrites.asStateFlow()
+
/** Re-reads the stored servers, e.g. after returning to the screen. */
fun reload() {
_servers.value = McpServerStore.servers()
+ _allowDatabaseWrites.value = McpServerStore.allowDatabaseWrites()
+ }
+
+ private val _writesNotSaved = MutableSharedFlow(extraBufferCapacity = 1)
+
+ /**
+ * Fires when the database-writes switch could not be stored. [allowDatabaseWrites] keeps the stored
+ * value, which may equal what it held, so the screen sets the switch back itself.
+ */
+ val writesNotSaved: SharedFlow = _writesNotSaved.asSharedFlow()
+
+ /** Stores the database-writes switch off the main thread, then re-reads it. */
+ fun setAllowDatabaseWrites(allow: Boolean) {
+ viewModelScope.launch {
+ val stored = withContext(Dispatchers.IO) { McpServerStore.setAllowDatabaseWrites(allow) }
+ reload()
+ if (!stored) _writesNotSaved.tryEmit(Unit)
+ }
}
/**
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 610c2ee52..a78ac8e00 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
@@ -6,6 +6,7 @@ import com.itsaky.androidide.plugins.aiagentmcp.client.McpConnections
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.debugger.ReadOnlyTrust
import com.itsaky.androidide.plugins.aiagentmcp.errors.McpErrorFormatter
import com.itsaky.androidide.plugins.aiagentmcp.R
import com.itsaky.androidide.plugins.aiagentmcp.logging.LOG_PREFIX
@@ -92,7 +93,7 @@ class McpToolSource internal constructor(
name = exposed.name,
description = exposed.description,
parametersSchema = exposed.tool.inputSchema,
- preApproved = exposed.server.automatic && exposed.tool.readOnlyHint,
+ preApproved = exposed.server.automatic && ReadOnlyTrust.isReadOnly(exposed.tool),
)
}
@@ -227,7 +228,7 @@ class McpToolSource internal constructor(
// 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)
+ Outcome(result.success, result.text, errorWithHint(server, tool, 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
@@ -337,21 +338,43 @@ class McpToolSource internal constructor(
/**
* 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.
+ * not tell which app's database one reads. A hand-added server's text is passed through. While the
+ * settings switch keeps an entry's `execute` off, its `query` also says how writes get allowed
+ * ([ReadOnlyTrust.needsWriteSwitchHint]).
*/
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}"
+ val text = if (tool.description.isBlank()) app else "$app: ${tool.description}"
+ if (!needsWriteSwitchHint(server, tool)) return text
+ return "$text ${writeSwitchHint()}"
}
+ /**
+ * A failed call's text, with [writeSwitchHint] after it when SQLite refused a write through an
+ * app's `query` while the switch keeps `execute` off. AI-Core shows that text under the chat, so the
+ * user reads how to allow writes even when the Agent's own answer is not shown.
+ */
+ private fun errorWithHint(server: McpServer, tool: McpTool, error: String?): String? {
+ if (error == null || !needsWriteSwitchHint(server, tool) || !ReadOnlyTrust.isWriteRefusal(error)) return error
+ return "${error.trimEnd().trimEnd('.')}. ${writeSwitchHint()}"
+ }
+
+ private fun needsWriteSwitchHint(server: McpServer, tool: McpTool): Boolean =
+ server.automatic && ReadOnlyTrust.needsWriteSwitchHint(tool.name, server.knownTools, server.enabledTools)
+
+ /** How the user allows writes, naming the switch by its own label. */
+ private fun writeSwitchHint(): String =
+ string(R.string.mcp_write_switch_hint, string(R.string.mcp_allow_database_writes))
+
/**
* One tool, as the host contract describes it.
*
* 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 one exception is [preApproved]: a readOnlyHint tool of the automatic
- * debugger entry, whose server Code on the Go itself installed, declares no approval needed.
+ * debugger entry, whose server Code on the Go itself installed, declares no approval needed. Its
+ * `execute`, which writes, never does, whatever hint it carries (`ReadOnlyTrust.isReadOnly`).
* 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
diff --git a/plugins/AI-Agent-MCP/src/main/res/layout/fragment_mcp_settings.xml b/plugins/AI-Agent-MCP/src/main/res/layout/fragment_mcp_settings.xml
index 88154b8c9..b83c80c01 100644
--- a/plugins/AI-Agent-MCP/src/main/res/layout/fragment_mcp_settings.xml
+++ b/plugins/AI-Agent-MCP/src/main/res/layout/fragment_mcp_settings.xml
@@ -67,6 +67,25 @@
android:textColor="@color/plugin_text_muted"
android:textSize="14sp" />
+
+
+
+
+
Connect the Agent to Model Context Protocol servers. Their tools appear alongside the Agent\'s own, and every one of them asks for your approval before it runs.
No servers yet. Add one to give the Agent remote tools.
Add server
+ Let the Agent change app databases
+ The setting could not be saved, so it is unchanged.
+ Offers the SQLite debugger\'s execute tool for each app. The Agent asks before every change, and Always Allow is never offered for it. A change is saved at once and cannot be undone, and the app may show old data until it reads again.
+
+ Changes to this app\'s databases are off. To make one, ask the user to switch on this setting on AI-Agent-MCP\'s MCP servers screen: %1$s. Don\'t change the databases any other way, for example through the shell.
%1$d of %2$d tools enabled
Not connecting: this http:// URL is not on this device. Tap to change it to https://.
Use this server
diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReadOnlyHintParsingTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReadOnlyHintParsingTest.kt
index 6301ddfc4..f1c0693c7 100644
--- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReadOnlyHintParsingTest.kt
+++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/ReadOnlyHintParsingTest.kt
@@ -74,6 +74,28 @@ class ReadOnlyHintParsingTest {
assertEquals(setOf("list_databases", "get_schema", "query", "get_events"), ReadOnlyTrust.CORE_TOOLS)
}
+ @Test
+ fun `execute is off unless writes are allowed, whatever its hint`() {
+ val tools = listOf(McpTool("query", "", readOnlyHint = true), McpTool("execute", "", readOnlyHint = true))
+ assertEquals(setOf("query"), ReadOnlyTrust.enabledTools(tools))
+ assertEquals(setOf("query", "execute"), ReadOnlyTrust.enabledTools(tools, allowWrites = true))
+ assertEquals(setOf("execute"), ReadOnlyTrust.enabledTools(listOf(McpTool("execute", "")), allowWrites = true))
+ }
+
+ @Test
+ fun `allowing writes switches on no other tool`() {
+ val tools = listOf(McpTool("get_stats", "", readOnlyHint = true), McpTool("run_sql", ""))
+ assertEquals(emptySet(), ReadOnlyTrust.enabledTools(tools, allowWrites = true))
+ }
+
+ @Test
+ fun `execute is never read-only, even claiming the hint`() {
+ assertFalse(ReadOnlyTrust.isReadOnly(McpTool("execute", "", readOnlyHint = true)))
+ assertTrue(ReadOnlyTrust.isReadOnly(McpTool("query", "", readOnlyHint = true)))
+ assertFalse(ReadOnlyTrust.isReadOnly(McpTool("query", "")))
+ assertEquals(setOf("execute"), ReadOnlyTrust.WRITE_TOOLS)
+ }
+
@Test
fun `a query tool that is not read only stays off`() {
val tools = listOf(McpTool("query", "", readOnlyHint = false), McpTool("list_databases", ""))
diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/WriteToolTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/WriteToolTest.kt
new file mode 100644
index 000000000..c189ecb52
--- /dev/null
+++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/debugger/WriteToolTest.kt
@@ -0,0 +1,221 @@
+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.testing.stringsXmlContext
+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
+
+/**
+ * The SQLite debugger's `execute` (ADFA-7300): offered only while the settings switch is on, and
+ * never read-only, so AI-Core asks before every call and never offers "Always Allow" for it.
+ */
+class WriteToolTest {
+
+ private val app = "com.example.app"
+ private var server: FakeMcpServer? = null
+ private val source = McpToolSource()
+ private lateinit var plugin: McpPlugin
+ private val prefs = FakeSharedPreferences()
+
+ @Before
+ fun setUp() {
+ val context = mockk(relaxed = true)
+ every { context.getPluginSharedPreferences(any()) } returns prefs
+ every { context.androidContext } returns stringsXmlContext()
+ plugin = McpPlugin().also { it.initialize(context) }
+ 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()
+ server?.stop()
+ plugin.dispose()
+ unmockkObject(McpServerStore)
+ }
+
+ /** A debugger whose execute claims readOnlyHint, as a buggy or hostile server could. */
+ private fun connect(failing: Map = emptyMap()) {
+ val fake = FakeMcpServer(
+ "t1",
+ listOf(tool("list_databases", true), tool("query", true), tool("execute", true)),
+ failing = failing,
+ )
+ server = fake
+ AutomaticServers.install { listOf(AutomaticEndpoint(app, fake.port, "t1")) }
+ McpToolCatalog.connect(AutomaticServers.servers().single())
+ }
+
+ /** What `query` adds while the switch is off, as strings.xml words it. */
+ private val hint = "Changes to this app's databases are off. To make one, ask the user to switch on this setting on " +
+ "AI-Agent-MCP's MCP servers screen: Let the Agent change app databases. Don't change the databases any other " +
+ "way, for example through the shell."
+
+ /** Calls the offered tool [suffix] (as [offered] keys it) and waits for its outcome. */
+ private fun call(suffix: String): ToolSourceRegistry.ToolOutcome {
+ val exposed = offered().getValue(suffix).name
+ return source.invoke(
+ mockk {
+ every { toolName } returns exposed
+ every { arguments } returns mapOf("sql" to "INSERT INTO notes (title) VALUES ('x')")
+ every { callId } returns "call-1"
+ },
+ ).get(30, TimeUnit.SECONDS)
+ }
+
+ /** The offered tools, keyed by the tool name after the app prefix (`db_app_list_databases` -> `databases`). */
+ private fun offered() = source.listTools().associateBy { it.name.substringAfterLast("_") }
+
+ @Test
+ fun `the switch is off by default and execute is not offered, even claiming the hint`() {
+ assertFalse(McpServerStore.allowDatabaseWrites())
+ connect()
+ assertEquals(setOf("databases", "query"), offered().keys)
+ assertEquals(setOf("list_databases", "query"), AutomaticServers.servers().single().enabledTools)
+ }
+
+ @Test
+ fun `with the switch on execute is offered, asks every time and is not read-only`() {
+ connect()
+ McpServerStore.setAllowDatabaseWrites(true)
+ assertTrue(McpServerStore.allowDatabaseWrites())
+ val execute = offered().getValue("execute")
+ assertTrue(execute.requiresApproval())
+ assertFalse(execute.isReadOnly)
+ // the read-only tools keep their grant
+ assertFalse(offered().getValue("query").requiresApproval())
+ }
+
+ @Test
+ fun `switching it off takes execute away again`() {
+ connect()
+ McpServerStore.setAllowDatabaseWrites(true)
+ McpServerStore.setAllowDatabaseWrites(false)
+ assertFalse("execute" in offered())
+ }
+
+ @Test
+ fun `a switch that cannot be stored stays as stored, in memory too, and tells no listener`() {
+ var calls = 0
+ val listener = { calls++; Unit }
+ McpServerStore.addChangeListener(listener)
+ try {
+ prefs.failCommits = true
+ assertFalse(McpServerStore.setAllowDatabaseWrites(true))
+ assertFalse("not on for this session only, to turn off again at restart", McpServerStore.allowDatabaseWrites())
+ assertEquals(0, calls)
+ prefs.failCommits = false
+ assertTrue(McpServerStore.setAllowDatabaseWrites(true))
+ assertTrue(McpServerStore.allowDatabaseWrites())
+ assertEquals(1, calls)
+ } finally {
+ McpServerStore.removeChangeListener(listener)
+ }
+ }
+
+ @Test
+ fun `changing the switch tells the change listeners, so the Agent's list follows`() {
+ var calls = 0
+ val listener = { calls++; Unit }
+ McpServerStore.addChangeListener(listener)
+ try {
+ McpServerStore.setAllowDatabaseWrites(true)
+ McpServerStore.setAllowDatabaseWrites(false)
+ } finally {
+ McpServerStore.removeChangeListener(listener)
+ }
+ assertEquals(2, calls)
+ }
+
+ @Test
+ fun `a hand-added server's execute is an ordinary tool, off until switched on, never read-only`() {
+ McpServerStore.setAllowDatabaseWrites(true)
+ val fake = FakeMcpServer("", listOf(tool("execute", true)))
+ server = fake
+ val handAdded = McpServerStore.saveDetails(McpServerStore.newServer("Mine", "http://127.0.0.1:${fake.port}/mcp"))
+ McpToolCatalog.connect(handAdded)
+ assertTrue(offered().isEmpty())
+ McpServerStore.setToolEnabled(handAdded.id, "execute", true)
+ val spec = offered().values.single()
+ assertTrue(spec.requiresApproval())
+ assertFalse(spec.isReadOnly)
+ }
+
+ @Test
+ fun `with the switch off, query says how writes get allowed`() {
+ connect()
+ assertEquals("$app (SQLite debugger): query $hint", offered().getValue("query").description)
+ assertEquals("$app (SQLite debugger): list_databases", offered().getValue("databases").description)
+ }
+
+ @Test
+ fun `with the switch on, query has no hint`() {
+ connect()
+ McpServerStore.setAllowDatabaseWrites(true)
+ assertEquals("$app (SQLite debugger): query", offered().getValue("query").description)
+ }
+
+ @Test
+ fun `a debugger without execute gets no hint`() {
+ val fake = FakeMcpServer("t1", listOf(tool("list_databases", true), tool("query", true)))
+ server = fake
+ AutomaticServers.install { listOf(AutomaticEndpoint(app, fake.port, "t1")) }
+ McpToolCatalog.connect(AutomaticServers.servers().single())
+ assertEquals("$app (SQLite debugger): query", offered().getValue("query").description)
+ }
+
+ @Test
+ fun `a hand-added server's query is passed through, execute on or off`() {
+ val fake = FakeMcpServer("", listOf(tool("query", true), tool("execute", true)))
+ server = fake
+ val handAdded = McpServerStore.saveDetails(McpServerStore.newServer("Mine", "http://127.0.0.1:${fake.port}/mcp"))
+ McpToolCatalog.connect(handAdded)
+ McpServerStore.setToolEnabled(handAdded.id, "query", true)
+ assertEquals("query", offered().values.single().description)
+ }
+
+ @Test
+ fun `with the switch off, a write refused through query says how writes get allowed`() {
+ connect(failing = mapOf("query" to "not authorized"))
+ val outcome = call("query")
+ assertFalse(outcome.isSuccess)
+ assertEquals("not authorized. $hint", outcome.errorMessage)
+ }
+
+ @Test
+ fun `with the switch on, a refused query's text is passed through`() {
+ connect(failing = mapOf("query" to "not authorized"))
+ McpServerStore.setAllowDatabaseWrites(true)
+ assertEquals("not authorized", call("query").errorMessage)
+ }
+
+ @Test
+ fun `a query failing for another reason gets no hint`() {
+ connect(failing = mapOf("query" to "no such table: notes"))
+ assertEquals("no such table: notes", call("query").errorMessage)
+ }
+}
diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/testing/FakeMcpServer.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/testing/FakeMcpServer.kt
index 1ff532fcb..c25f451f5 100644
--- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/testing/FakeMcpServer.kt
+++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/testing/FakeMcpServer.kt
@@ -15,11 +15,13 @@ import org.json.JSONObject
*
* @param tools the `tools/list` entries.
* @param sessionId the `Mcp-Session-Id` to assign, or null for a server without sessions.
+ * @param failing tools whose `tools/call` answers `isError` with the mapped text, by tool name.
*/
class FakeMcpServer(
val token: String,
private val tools: List,
private val sessionId: String? = null,
+ private val failing: Map = emptyMap(),
) {
/**
@@ -64,7 +66,11 @@ class FakeMcpServer(
.put("protocolVersion", "2025-03-26")
.put("serverInfo", JSONObject().put("name", "fake"))
"tools/list" -> JSONObject().put("tools", JSONArray(tools))
- "tools/call" -> JSONObject().put(
+ "tools/call" -> failing[request.getJSONObject("params").optString("name")]?.let { error ->
+ JSONObject()
+ .put("content", JSONArray().put(JSONObject().put("type", "text").put("text", error)))
+ .put("isError", true)
+ } ?: JSONObject().put(
"content",
JSONArray().put(JSONObject().put("type", "text").put("text", "served by $port")),
)
diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/testing/FakeSharedPreferences.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/testing/FakeSharedPreferences.kt
index ef47fbca5..b66e5d3aa 100644
--- a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/testing/FakeSharedPreferences.kt
+++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/testing/FakeSharedPreferences.kt
@@ -22,6 +22,13 @@ class FakeSharedPreferences : SharedPreferences {
@Volatile
var readDelayMillis: Long = 0
+ /**
+ * Makes every commit report failure, as a full disk or a storage error does. The values still change
+ * in memory, as Android's implementation keeps them there when its disk write fails.
+ */
+ @Volatile
+ var failCommits = false
+
override fun getAll(): MutableMap = HashMap(values)
override fun getString(key: String, defValue: String?): String? {
@@ -108,7 +115,7 @@ class FakeSharedPreferences : SharedPreferences {
if (cleared) values.clear()
removals.forEach { values.remove(it) }
values.putAll(puts)
- return true
+ return !failCommits
}
override fun apply() {
diff --git a/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/testing/StringsXmlContext.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/testing/StringsXmlContext.kt
new file mode 100644
index 000000000..20048d5cc
--- /dev/null
+++ b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/testing/StringsXmlContext.kt
@@ -0,0 +1,26 @@
+package com.itsaky.androidide.plugins.aiagentmcp.testing
+
+import android.content.Context
+import com.itsaky.androidide.plugins.aiagentmcp.R
+import io.mockk.every
+import io.mockk.mockk
+import java.io.File
+import javax.xml.parsers.DocumentBuilderFactory
+import org.w3c.dom.Element
+
+/** A Context answering `getString` from this plugin's strings.xml, so the shipped words are checked. */
+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/AppEndpointReasonTest.kt b/plugins/AI-Agent-MCP/src/test/kotlin/com/itsaky/androidide/plugins/aiagentmcp/tools/AppEndpointReasonTest.kt
index 8b395ef7c..622b442af 100644
--- 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
@@ -1,8 +1,6 @@
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
@@ -10,21 +8,19 @@ 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.testing.stringsXmlContext
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
@@ -140,21 +136,4 @@ class AppEndpointReasonTest {
}
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>())
- }
- }
- }
}