Skip to content

Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.

feat(connectors): add your own MCP servers (#130)

Durganshud9cec116a78e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index edd23d2..1072676 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,15 @@ All notable changes to Gotcha are documented here.
download ready. The check skips quiet hours and stays silent when offline.
It can be turned off under Settings ▸ Notifications ▸ App updates, or muted
through its own "App updates" channel in Android's settings.
+- **Your own MCP servers** (#130). Connectors has a new **MCP servers** card:
+ add any Model Context Protocol server that speaks Streamable HTTP, with an
+ optional bearer token or extra headers, test the connection, and see the
+ tools it offers. While a server is on, the assistant can use its tools in
+ Operator, and the ones the server marks read-only in Monitor too. Each
+ server has its own switch, and Remove deletes it with its stored token.
+ A token or header is only sent over plain http to a server on your local
+ network.
+ See [docs/mcp-servers.md](docs/mcp-servers.md).
- **Russian voice and replies, and roubles** (#122). Russian can now be picked
as the voice language and the reply language: Android speech is asked for
`ru-RU` and API speech-to-text for `ru`, and the short phrases Gotcha speaks
diff --git a/README.md b/README.md
index 26935c0..3bd985b 100644
--- a/README.md
+++ b/README.md
@@ -84,6 +84,7 @@ one-time setup walkthrough.
* 🛡️ [**Safety & Permissions**](https://samosa-ai.com/gotcha/docs/safety-permissions) — capability tiers, confirmation gates, audit log.
* ❓ [**FAQ & Known Limitations**](https://samosa-ai.com/gotcha/docs/faq) — backend compatibility and rough edges.
* ✅ [**Feature Test Coverage**](docs/FEATURE_TEST_COVERAGE.md) — every tool and how it's verified.
+* 🔌 [**MCP Servers**](docs/mcp-servers.md) — add your own Model Context Protocol servers and use their tools.
## 🧪 Beta Testers
diff --git a/app/src/main/java/com/gotcha/connectors/ConnectorCatalog.kt b/app/src/main/java/com/gotcha/connectors/ConnectorCatalog.kt
index dbfe032..f9e812b 100644
--- a/app/src/main/java/com/gotcha/connectors/ConnectorCatalog.kt
+++ b/app/src/main/java/com/gotcha/connectors/ConnectorCatalog.kt
@@ -105,7 +105,19 @@ object ConnectorCatalog {
hasDynamicTools = true
)
- val all: List<ConnectorSpec> = listOf(IMAP, GOOGLE, MICROSOFT, NOTION, HOME_ASSISTANT)
+ /**
+ * The user's own MCP servers (issue #130). Server-defined like Home
+ * Assistant: every tool is registered at connect time, named
+ * `mcp_<server>__<tool>`.
+ */
+ val MCP = ConnectorSpec(
+ id = "mcp",
+ displayName = "MCP servers",
+ ownedToolNames = emptySet(),
+ hasDynamicTools = true
+ )
+
+ val all: List<ConnectorSpec> = listOf(IMAP, GOOGLE, MICROSOFT, NOTION, HOME_ASSISTANT, MCP)
fun byId(id: String): ConnectorSpec? = all.firstOrNull { it.id == id }
diff --git a/app/src/main/java/com/gotcha/connectors/ConnectorRegistry.kt b/app/src/main/java/com/gotcha/connectors/ConnectorRegistry.kt
index 0b1ed78..69a256a 100644
--- a/app/src/main/java/com/gotcha/connectors/ConnectorRegistry.kt
+++ b/app/src/main/java/com/gotcha/connectors/ConnectorRegistry.kt
@@ -9,6 +9,8 @@ import com.gotcha.connectors.homeassistant.HomeAssistantConnector
import com.gotcha.connectors.homeassistant.HomeAssistantTools
import com.gotcha.connectors.imap.ImapConnector
import com.gotcha.connectors.mail.EmailTools
+import com.gotcha.connectors.mcp.McpServerTools
+import com.gotcha.connectors.mcp.McpServersConnector
import com.gotcha.connectors.microsoft.MicrosoftConnector
import com.gotcha.connectors.microsoft.TaskTools
import com.gotcha.connectors.notion.NotionConnector
@@ -51,7 +53,8 @@ object ConnectorRegistry {
val microsoft = MicrosoftConnector(store)
val notion = NotionConnector(store)
val homeAssistant = HomeAssistantConnector(store)
- connectors = listOf(imap, google, microsoft, notion, homeAssistant)
+ val mcp = McpServersConnector(store)
+ connectors = listOf(imap, google, microsoft, notion, homeAssistant, mcp)
val email = EmailTools(appContext, imap, google, microsoft)
emailTools = email
@@ -66,7 +69,8 @@ object ConnectorRegistry {
microsoft = { microsoft }
),
NotionTools { notion },
- HomeAssistantTools { homeAssistant }
+ HomeAssistantTools { homeAssistant },
+ McpServerTools { mcp }
)
initialized = true
}
@@ -103,7 +107,7 @@ object ConnectorRegistry {
* Tool names to withhold from the model right now, because every connector
* that could serve them is disconnected or disabled. Falls back to hiding
* all connector-owned tools before [init] runs — nothing can serve them at
- * that point either. Server-defined tools (such as Home Assistant's) are
+ * that point either. Server-defined tools (Home Assistant, MCP servers) are
* not in the compile-time catalog: whatever a connector has registered is
* hidden whenever that connector is not usable.
*/
diff --git a/app/src/main/java/com/gotcha/connectors/mcp/McpHttpClient.kt b/app/src/main/java/com/gotcha/connectors/mcp/McpHttpClient.kt
new file mode 100644
index 0000000..e05a71c
--- /dev/null
+++ b/app/src/main/java/com/gotcha/connectors/mcp/McpHttpClient.kt
@@ -0,0 +1,427 @@
+package com.gotcha.connectors.mcp
+
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
+import kotlinx.coroutines.withContext
+import kotlinx.serialization.Serializable
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonArray
+import kotlinx.serialization.json.JsonElement
+import kotlinx.serialization.json.JsonNull
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonPrimitive
+import kotlinx.serialization.json.booleanOrNull
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.contentOrNull
+import kotlinx.serialization.json.longOrNull
+import kotlinx.serialization.json.put
+import okhttp3.MediaType.Companion.toMediaType
+import okhttp3.OkHttpClient
+import okhttp3.Request
+import okhttp3.RequestBody.Companion.toRequestBody
+import okhttp3.Response
+import okio.BufferedSource
+import java.io.IOException
+import java.util.concurrent.TimeUnit
+import java.util.concurrent.atomic.AtomicLong
+
+/**
+ * A tool an MCP server advertises through `tools/list`. [readOnly] is the
+ * server's own `readOnlyHint` annotation: MCP has no other way to say a tool
+ * only reads, so a tool without it is treated as one that acts.
+ */
+@Serializable
+data class McpTool(
+ val name: String,
+ val description: String = "",
+ val inputSchema: JsonObject,
+ val readOnly: Boolean = false
+)
+
+/** Who answered `initialize`. */
+data class McpServerInfo(val name: String, val version: String, val protocolVersion: String)
+
+/** A `tools/call` outcome, as text for the model. */
+data class McpToolOutput(val isError: Boolean, val text: String)
+
+/** Why an MCP request failed, so the connector can say it in the user's language. */
+enum class McpFailure {
+ /** 401 or 403: the token or headers were refused. */
+ AUTH,
+
+ /** 404 on the first request: nothing at that URL. */
+ NOT_FOUND,
+
+ /** The server speaks the 2024-11-05 HTTP+SSE transport, which this client does not. */
+ OLD_TRANSPORT,
+
+ /** It answered, but not with MCP's JSON-RPC. */
+ NOT_MCP,
+
+ /** Any other HTTP status. */
+ HTTP,
+
+ /** A JSON-RPC error from the server (unknown tool, bad arguments, ...). */
+ RPC,
+
+ /** DNS, refused connection, TLS, timeout. */
+ NETWORK
+}
+
+/** An MCP failure: [kind] for the message, [detail] for what the server or the socket said. */
+class McpException(
+ val kind: McpFailure,
+ val detail: String,
+ val httpCode: Int = 0,
+ cause: Throwable? = null
+) : IOException("$kind${if (httpCode != 0) " ($httpCode)" else ""}: $detail", cause)
+
+/** Throws [McpFailure.NOT_MCP]: the server answered, but not with what MCP promises. */
+private fun notMcp(detail: String): Nothing = throw McpException(McpFailure.NOT_MCP, detail)
+
+/** Where a server lives and what every request to it carries (auth and custom headers). */
+data class McpEndpoint(val url: String, val headers: Map<String, String> = emptyMap())
+
+/**
+ * An MCP client for the **Streamable HTTP** transport (MCP 2025-06-18), for
+ * servers the user adds themselves (issue #130).
+ *
+ * Home Assistant's client ([com.gotcha.connectors.homeassistant.HomeAssistantMcpClient])
+ * gets away with three bare round trips because that server keeps no state.
+ * A general server may not, so this one also:
+ * - sends `notifications/initialized` after `initialize`;
+ * - keeps the `Mcp-Session-Id` the server hands out, sends it and the
+ * negotiated `MCP-Protocol-Version` on every later request, and starts a
+ * new session once when the server says the old one is gone (404);
+ * - follows `tools/list` pages through `nextCursor`;
+ * - reads a `text/event-stream` reply event by event and stops at the
+ * response whose id matches, skipping the server's own notifications and
+ * requests, so a stream the server keeps open cannot hang the call;
+ * - caps how much of a reply it reads.
+ *
+ * Stdio servers and the older HTTP+SSE transport are out of scope; the latter
+ * is recognised and reported as [McpFailure.OLD_TRANSPORT].
+ */
+class McpHttpClient(
+ private val client: OkHttpClient = OkHttpClient.Builder()
+ .connectTimeout(15, TimeUnit.SECONDS)
+ .readTimeout(60, TimeUnit.SECONDS)
+ .callTimeout(90, TimeUnit.SECONDS)
+ .build()
+) {
+
+ /** One server's session. Requests on it are serialized, which also keeps re-initialising race-free. */
+ inner class Session internal constructor(val endpoint: McpEndpoint) {
+ private val mutex = Mutex()
+ private var sessionId: String? = null
+ private var protocolVersion: String? = null
+
+ /** Set by the first successful [initialize]. */
+ var server: McpServerInfo? = null
+ private set
+
+ suspend fun initialize(): McpServerInfo = mutex.withLock { initializeLocked() }
+
+ suspend fun listTools(): List<McpTool> = mutex.withLock {
+ val tools = mutableListOf<McpTool>()
+ var cursor: String? = null
+ var pages = 0
+ do {
+ val params = buildJsonObject { cursor?.let { put("cursor", it) } }
+ val result = requestLocked("tools/list", params)
+ (result["tools"] as? JsonArray)?.mapNotNullTo(tools) { parseTool(it) }
+ cursor = (result["nextCursor"] as? JsonPrimitive)?.contentOrNull?.takeIf { it.isNotEmpty() }
+ pages++
+ } while (cursor != null && pages < MAX_TOOL_PAGES)
+ tools
+ }
+
+ suspend fun callTool(name: String, args: JsonObject): McpToolOutput = mutex.withLock {
+ val result = requestLocked(
+ "tools/call",
+ buildJsonObject {
+ put("name", name)
+ put("arguments", args)
+ }
+ )
+ toolOutput(result)
+ }
+
+ private suspend fun initializeLocked(): McpServerInfo {
+ sessionId = null
+ protocolVersion = null
+ val reply = exchange(
+ this,
+ rpcRequest(
+ "initialize",
+ buildJsonObject {
+ put("protocolVersion", PROTOCOL_VERSION)
+ put("capabilities", buildJsonObject {})
+ put(
+ "clientInfo",
+ buildJsonObject {
+ put("name", CLIENT_NAME)
+ put("version", CLIENT_VERSION)
+ }
+ )
+ }
+ ),
+ firstRequest = true
+ )
+ sessionId = reply.sessionId
+ val result = reply.result()
+ val version = (result["protocolVersion"] as? JsonPrimitive)?.contentOrNull
+ ?: notMcp("initialize returned no protocolVersion")
+ protocolVersion = version
+ val info = result["serverInfo"] as? JsonObject
+ val server = McpServerInfo(
+ name = (info?.get("name") as? JsonPrimitive)?.contentOrNull.orEmpty(),
+ version = (info?.get("version") as? JsonPrimitive)?.contentOrNull.orEmpty(),
+ protocolVersion = version
+ )
+ // A server that is loose about this one notification still works; only
+ // a refusal of the credentials is worth stopping for.
+ try {
+ exchange(this, notification("notifications/initialized"), firstRequest = false)
+ } catch (e: McpException) {
+ if (e.kind == McpFailure.AUTH) throw e
+ }
+ this.server = server
+ return server
+ }
+
+ /** One request, initialising first if needed, and once more if the server dropped the session. */
+ private suspend fun requestLocked(method: String, params: JsonObject): JsonObject {
+ if (protocolVersion == null) initializeLocked()
+ return try {
+ exchange(this, rpcRequest(method, params), firstRequest = false).result()
+ } catch (e: McpException) {
+ if (e.kind != McpFailure.NOT_FOUND || sessionId == null) throw e
+ initializeLocked()
+ exchange(this, rpcRequest(method, params), firstRequest = false).result()
+ }
+ }
+
+ internal fun headers(): Map<String, String> = buildMap {
+ sessionId?.let { put(HEADER_SESSION_ID, it) }
+ protocolVersion?.let { put(HEADER_PROTOCOL_VERSION, it) }
+ }
+ }
+
+ /** A new session with [endpoint]; nothing is sent until its first call. */
+ fun session(endpoint: McpEndpoint): Session = Session(endpoint)
+
+ private val json = Json { ignoreUnknownKeys = true }
+ private val jsonMediaType = "application/json".toMediaType()
+ private val nextId = AtomicLong(1)
+
+ /** A JSON-RPC message to send: [id] is null for a notification. */
+ private class Outgoing(val id: Long?, val body: JsonObject)
+
+ /** What came back: the matching response (null for a notification) and the session id header. */
+ private class Reply(val message: JsonObject?, val sessionId: String?) {
+ fun result(): JsonObject {
+ val msg = message ?: notMcp("empty reply")
+ (msg["error"] as? JsonObject)?.let { err ->
+ throw McpException(
+ McpFailure.RPC,
+ (err["message"] as? JsonPrimitive)?.contentOrNull ?: err.toString()
+ )
+ }
+ return msg["result"] as? JsonObject ?: notMcp("reply has no result")
+ }
+ }
+
+ private fun rpcRequest(method: String, params: JsonObject): Outgoing {
+ val id = nextId.getAndIncrement()
+ return Outgoing(
+ id,
+ buildJsonObject {
+ put("jsonrpc", "2.0")
+ put("id", id)
+ put("method", method)
+ put("params", params)
+ }
+ )
+ }
+
+ private fun notification(method: String) = Outgoing(
+ null,
+ buildJsonObject {
+ put("jsonrpc", "2.0")
+ put("method", method)
+ }
+ )
+
+ /**
+ * One POST. Every failure leaves as an [McpException], including a timeout
+ * while the reply is still being read and a header OkHttp refuses to send,
+ * so callers have one exception type to handle.
+ */
+ private suspend fun exchange(session: Session, out: Outgoing, firstRequest: Boolean): Reply =
+ withContext(Dispatchers.IO) {
+ try {
+ post(session, out, firstRequest)
+ } catch (e: IOException) {
+ throw asMcp(e)
+ } catch (e: IllegalArgumentException) {
+ throw asMcp(e)
+ }
+ }
+
+ private fun post(session: Session, out: Outgoing, firstRequest: Boolean): Reply {
+ val builder = Request.Builder()
+ .url(session.endpoint.url)
+ .header("Accept", "application/json, text/event-stream")
+ .post(out.body.toString().toRequestBody(jsonMediaType))
+ session.endpoint.headers.forEach { (k, v) -> builder.header(k, v) }
+ session.headers().forEach { (k, v) -> builder.header(k, v) }
+ return client.newCall(builder.build()).execute().use { r ->
+ if (!r.isSuccessful) throw httpFailure(session, r, firstRequest)
+ val sessionId = r.header(HEADER_SESSION_ID)
+ val message = if (out.id == null) null else readResponse(r, out.id)
+ Reply(message, sessionId)
+ }
+ }
+
+ /** Socket, TLS and timeout errors, and headers OkHttp refuses, as [McpFailure.NETWORK]. */
+ private fun asMcp(e: Exception): McpException =
+ e as? McpException ?: McpException(McpFailure.NETWORK, e.message ?: e.javaClass.simpleName, cause = e)
+
+ private fun httpFailure(session: Session, r: Response, firstRequest: Boolean): McpException {
+ val detail = runCatching { r.peekBody(ERROR_BODY_CHARS.toLong()).string() }.getOrDefault("").trim()
+ return when (r.code) {
+ 401, 403 -> McpException(McpFailure.AUTH, detail, r.code)
+ // The old transport answers POSTs on its SSE URL with 404/405 and
+ // streams an `endpoint` event to a GET instead.
+ 400, 404, 405 -> if (firstRequest && speaksOldTransport(session)) {
+ McpException(McpFailure.OLD_TRANSPORT, detail, r.code)
+ } else if (r.code == 404) {
+ McpException(McpFailure.NOT_FOUND, detail, r.code)
+ } else {
+ McpException(McpFailure.HTTP, detail, r.code)
+ }
+ else -> McpException(McpFailure.HTTP, detail, r.code)
+ }
+ }
+
+ /** True when a GET opens an event stream: the 2024-11-05 HTTP+SSE transport. Reads only the headers. */
+ private fun speaksOldTransport(session: Session): Boolean = runCatching {
+ val builder = Request.Builder().url(session.endpoint.url).header("Accept", "text/event-stream").get()
+ session.endpoint.headers.forEach { (k, v) -> builder.header(k, v) }
+ client.newCall(builder.build()).execute().use { r ->
+ r.isSuccessful && r.header("Content-Type").orEmpty().startsWith("text/event-stream")
+ }
+ }.getOrDefault(false)
+
+ private fun readResponse(r: Response, id: Long): JsonObject {
+ val body = r.body ?: notMcp("empty body")
+ val type = r.header("Content-Type").orEmpty()
+ return if (type.startsWith("text/event-stream")) {
+ readEventStream(body.source(), id)
+ } else {
+ val text = body.source().readCapped()
+ val element = parseJson(text) ?: notMcp(text.take(ERROR_BODY_CHARS))
+ matching(element, id) ?: notMcp("no response with id $id")
+ }
+ }
+
+ /**
+ * Walks SSE events until one carries the response to [id]. Notifications and
+ * server-to-client requests in between are skipped; there is no client
+ * capability that would need answering them.
+ */
+ private fun readEventStream(source: BufferedSource, id: Long): JsonObject {
+ val data = StringBuilder()
+ var read = 0L
+ while (true) {
+ val line = source.readUtf8Line() ?: break
+ read += line.length + 1
+ if (read > MAX_REPLY_BYTES) notMcp("reply larger than $MAX_REPLY_BYTES bytes")
+ when {
+ line.isEmpty() -> {
+ if (data.isNotEmpty()) {
+ parseJson(data.toString())?.let { matching(it, id) }?.let { return it }
+ data.clear()
+ }
+ }
+ line.startsWith("data:") -> {
+ if (data.isNotEmpty()) data.append('\n')
+ data.append(line.removePrefix("data:").removePrefix(" "))
+ }
+ }
+ }
+ if (data.isNotEmpty()) parseJson(data.toString())?.let { matching(it, id) }?.let { return it }
+ notMcp("event stream ended without a response")
+ }
+
+ private fun BufferedSource.readCapped(): String {
+ if (!request(MAX_REPLY_BYTES + 1)) return readUtf8()
+ notMcp("reply larger than $MAX_REPLY_BYTES bytes")
+ }
+
+ private fun parseJson(text: String): JsonElement? =
+ if (text.isBlank()) null else runCatching { json.parseToJsonElement(text) }.getOrNull()
+
+ /** The response to [id] in [element], which may be one message or a JSON-RPC batch. */
+ private fun matching(element: JsonElement, id: Long): JsonObject? = when (element) {
+ is JsonObject -> element.takeIf { (it["id"] as? JsonPrimitive)?.longOrNull == id && "method" !in it }
+ is JsonArray -> element.firstNotNullOfOrNull { matching(it, id) }
+ else -> null
+ }
+
+ private fun parseTool(element: JsonElement): McpTool? {
+ val obj = element as? JsonObject ?: return null
+ val name = (obj["name"] as? JsonPrimitive)?.contentOrNull?.takeIf { it.isNotBlank() } ?: return null
+ val annotations = obj["annotations"] as? JsonObject
+ return McpTool(
+ name = name,
+ description = (obj["description"] as? JsonPrimitive)?.contentOrNull
+ ?: (obj["title"] as? JsonPrimitive)?.contentOrNull
+ ?: "",
+ inputSchema = obj["inputSchema"] as? JsonObject ?: buildJsonObject { put("type", "object") },
+ readOnly = (annotations?.get("readOnlyHint") as? JsonPrimitive)?.booleanOrNull == true
+ )
+ }
+
+ /** Flattens `tools/call` content to text: images and audio are named, not inlined. */
+ private fun toolOutput(result: JsonObject): McpToolOutput {
+ val isError = (result["isError"] as? JsonPrimitive)?.booleanOrNull == true
+ val parts = (result["content"] as? JsonArray).orEmpty().mapNotNull { el ->
+ val item = el as? JsonObject ?: return@mapNotNull null
+ fun str(key: String, from: JsonObject = item) = (from[key] as? JsonPrimitive)?.contentOrNull
+ when (str("type")) {
+ "text" -> str("text")
+ "image", "audio" -> "[${str("type")} ${str("mimeType").orEmpty()} not shown]"
+ "resource_link" -> "[link: ${str("name").orEmpty()} ${str("uri").orEmpty()}]".replace(" ", " ")
+ "resource" -> (item["resource"] as? JsonObject)?.let { res ->
+ str("text", res) ?: "[resource: ${str("uri", res).orEmpty()}]"
+ }
+ else -> item.toString()
+ }
+ }
+ val structured = result["structuredContent"]?.takeUnless { it is JsonNull }
+ val text = parts.joinToString("\n").ifBlank { structured?.toString().orEmpty() }.ifBlank { "(no output)" }
+ val capped = if (text.length > MAX_OUTPUT_CHARS) {
+ text.take(MAX_OUTPUT_CHARS) + "\n[output cut at $MAX_OUTPUT_CHARS characters]"
+ } else {
+ text
+ }
+ return McpToolOutput(isError, capped)
+ }
+
+ companion object {
+ /** The newest MCP version this client speaks; the server answers with the one it will use. */
+ const val PROTOCOL_VERSION = "2025-06-18"
+ private const val CLIENT_NAME = "Gotcha"
+ private const val CLIENT_VERSION = "1.0"
+ const val HEADER_SESSION_ID = "Mcp-Session-Id"
+ const val HEADER_PROTOCOL_VERSION = "MCP-Protocol-Version"
+
+ private const val MAX_TOOL_PAGES = 20
+ private const val MAX_REPLY_BYTES = 4L * 1024 * 1024
+ private const val MAX_OUTPUT_CHARS = 50_000
+ private const val ERROR_BODY_CHARS = 300
+ }
+}
diff --git a/app/src/main/java/com/gotcha/connectors/mcp/McpServers.kt b/app/src/main/java/com/gotcha/connectors/mcp/McpServers.kt
new file mode 100644
index 0000000..835f77e
--- /dev/null
+++ b/app/src/main/java/com/gotcha/connectors/mcp/McpServers.kt
@@ -0,0 +1,174 @@
+package com.gotcha.connectors.mcp
+
+import kotlinx.serialization.Serializable
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.buildJsonObject
+import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
+import java.net.InetAddress
+import java.security.MessageDigest
+
+/**
+ * One MCP server the user added (issue #130), as stored in the encrypted
+ * connector store. [tools] is the last `tools/list`, so the tools exist after
+ * a restart before any network call.
+ */
+@Serializable
+data class McpServerConfig(
+ val id: String,
+ val name: String,
+ val url: String,
+ /** Sent as `Authorization: Bearer <token>` when not blank. */
+ val token: String = "",
+ /** Extra request headers, e.g. an API-key header a server wants instead of a bearer token. */
+ val headers: Map<String, String> = emptyMap(),
+ val enabled: Boolean = true,
+ val tools: List<McpTool> = emptyList(),
+ /** `serverInfo.name` from the last successful connect, for the card. */
+ val serverName: String = "",
+ /** Why the last connect or refresh failed, or null when it worked. Shown on the card. */
+ val lastError: String? = null
+) {
+ fun endpoint(): McpEndpoint = McpEndpoint(
+ url = url,
+ headers = buildMap {
+ putAll(headers)
+ if (token.isNotBlank()) put("Authorization", "Bearer ${token.trim()}")
+ }
+ )
+}
+
+/** What is wrong with a server's URL or headers before anything is sent. */
+enum class McpConfigProblem { BAD_URL, CLEARTEXT_WITH_SECRET, BAD_HEADER, BAD_TOKEN }
+
+/**
+ * Checks a server before it is contacted. Plain http is accepted for the local
+ * network (a Home Assistant box, a dev machine), and anywhere when nothing
+ * secret would travel with it; a token or header sent over http to the
+ * internet could be read on the way, so that is refused.
+ */
+fun validateMcpServer(url: String, token: String, headers: Map<String, String>): McpConfigProblem? {
+ val parsed = url.trim().toHttpUrlOrNull() ?: return McpConfigProblem.BAD_URL
+ if (headers.keys.any { !isValidHeaderName(it) }) return McpConfigProblem.BAD_HEADER
+ // OkHttp refuses to send anything else, so it is caught here rather than on the wire.
+ if (!isHeaderValue(token) || headers.values.any { !isHeaderValue(it) }) return McpConfigProblem.BAD_TOKEN
+ val secret = token.isNotBlank() || headers.isNotEmpty()
+ if (!parsed.isHttps && secret && !isLocalHost(parsed.host)) return McpConfigProblem.CLEARTEXT_WITH_SECRET
+ return null
+}
+
+private fun isHeaderValue(value: String): Boolean = value.all { it == '\t' || it in ' '..'~' }
+
+private fun isValidHeaderName(name: String): Boolean =
+ name.isNotEmpty() && name.all { it.isLetterOrDigit() || it in "!#$%&'*+-.^_`|~" } && name.all { it.code < 128 }
+
+/**
+ * True for hosts on the user's own network: localhost, mDNS and home-router
+ * names, and private, loopback, link-local and CGNAT (Tailscale) addresses.
+ * Never resolves a name: only IP literals are inspected as addresses.
+ */
+fun isLocalHost(host: String): Boolean {
+ val h = host.lowercase().trimEnd('.')
+ if (h == "localhost" || LOCAL_SUFFIXES.any { h.endsWith(it) }) return true
+ val literal = h.removePrefix("[").removeSuffix("]")
+ val looksLikeIp = literal.contains(':') || literal.matches(Regex("""\d{1,3}(\.\d{1,3}){3}"""))
+ if (!looksLikeIp) return false
+ val address = runCatching { InetAddress.getByName(literal) }.getOrNull() ?: return false
+ val bytes = address.address
+ val cgnat = bytes.size == 4 && bytes[0].toInt() and 0xFF == 100 && (bytes[1].toInt() and 0xC0) == 64
+ val uniqueLocalV6 = bytes.size == 16 && (bytes[0].toInt() and 0xFE) == 0xFC
+ return address.isLoopbackAddress || address.isSiteLocalAddress || address.isLinkLocalAddress || cgnat || uniqueLocalV6
+}
+
+private val LOCAL_SUFFIXES = listOf(".local", ".lan", ".home", ".home.arpa", ".internal")
+
+/** Parses the headers field: one `Name: value` per line, blank lines ignored. Null when a line has no colon. */
+fun parseHeaderLines(text: String): Map<String, String>? {
+ val headers = linkedMapOf<String, String>()
+ text.lines().map { it.trim() }.filter { it.isNotEmpty() }.forEach { line ->
+ val colon = line.indexOf(':')
+ if (colon <= 0) return null
+ headers[line.substring(0, colon).trim()] = line.substring(colon + 1).trim()
+ }
+ return headers
+}
+
+fun formatHeaderLines(headers: Map<String, String>): String =
+ headers.entries.joinToString("\n") { "${it.key}: ${it.value}" }
+
+/**
+ * The names a server's tools get in front of the model: `mcp_<server>__<tool>`.
+ *
+ * Servers choose their own tool names, and two servers may both have `search`,
+ * so each is prefixed with its server's slug. Function names must match
+ * `^[a-zA-Z0-9_-]{1,64}$` for the chat APIs Gotcha talks to, so anything else
+ * becomes `_`, and a name that is too long, or that clashes after cleaning, is
+ * shortened and given a hash of the original.
+ */
+object McpToolNames {
+
+ const val PREFIX = "mcp_"
+ private const val MAX_NAME = 64
+ private const val MAX_SLUG = 16
+ private const val HASH_CHARS = 6
+
+ /** A short, stable label for [name]: lowercase letters, digits and `_`. */
+ fun slug(name: String): String =
+ clean(name.lowercase()).trim('_').take(MAX_SLUG).trimEnd('_').ifEmpty { "server" }
+
+ /**
+ * Slugs for [servers] in order, made unique by a numeric suffix. The order is
+ * the stored order, so a server keeps its slug as long as none before it
+ * is renamed into a clash.
+ */
+ fun slugs(servers: List<McpServerConfig>): Map<String, String> {
+ val used = mutableSetOf<String>()
+ return servers.associate { server ->
+ val base = slug(server.name)
+ var candidate = base
+ var n = 2
+ while (!used.add(candidate)) candidate = "${base.take(MAX_SLUG - 2)}$n".also { n++ }
+ server.id to candidate
+ }
+ }
+
+ /** Exposed name → the server's own tool name, for one server's [tools]. */
+ fun exposedNames(slug: String, tools: List<McpTool>): Map<String, String> {
+ val result = linkedMapOf<String, String>()
+ tools.forEach { tool ->
+ var exposed = fit("$PREFIX${slug}__${clean(tool.name)}", tool.name)
+ if (exposed in result) exposed = fit(exposed, "${tool.name}#${result.size}", force = true)
+ result[exposed] = tool.name
+ }
+ return result
+ }
+
+ private fun clean(s: String): String = s.map {
+ if (it.isLetterOrDigit() && it.code < 128 || it == '_' || it == '-') it else '_'
+ }
+ .joinToString("")
+
+ private fun fit(name: String, original: String, force: Boolean = false): String {
+ if (name.length <= MAX_NAME && !force) return name
+ val hash = MessageDigest.getInstance("SHA-256").digest(original.toByteArray())
+ .joinToString("") { "%02x".format(it) }.take(HASH_CHARS)
+ return name.take(MAX_NAME - HASH_CHARS - 1) + "_" + hash
+ }
+}
+
+/**
+ * Makes a server's input schema acceptable to the chat APIs: it must be an
+ * object schema, and OpenAI-compatible endpoints reject one without
+ * `properties`. Null for a schema that is not an object at all.
+ */
+fun normalizedInputSchema(schema: JsonObject): JsonObject? {
+ val type = schema["type"]?.toString()?.trim('"')
+ if (type != null && type != "object") return null
+ if (type != null && "properties" in schema) return schema
+ return JsonObject(
+ buildMap {
+ putAll(schema)
+ put("type", kotlinx.serialization.json.JsonPrimitive("object"))
+ if ("properties" !in schema) put("properties", buildJsonObject {})
+ }
+ )
+}
diff --git a/app/src/main/java/com/gotcha/connectors/mcp/McpServersConnector.kt b/app/src/main/java/com/gotcha/connectors/mcp/McpServersConnector.kt
new file mode 100644
index 0000000..99ad230
--- /dev/null
+++ b/app/src/main/java/com/gotcha/connectors/mcp/McpServersConnector.kt
@@ -0,0 +1,314 @@
+package com.gotcha.connectors.mcp
+
+import com.gotcha.R
+import com.gotcha.connectors.Connector
+import com.gotcha.connectors.ConnectorCatalog
+import com.gotcha.connectors.CredentialStore
+import com.gotcha.connectors.ToolRouter
+import com.gotcha.i18n.StringLookup
+import com.gotcha.llm.FunctionDefinition
+import com.gotcha.llm.ToolDefinition
+import com.gotcha.tools.ToolRegistry
+import com.gotcha.tools.ToolResult
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.async
+import kotlinx.coroutines.awaitAll
+import kotlinx.coroutines.coroutineScope
+import kotlinx.serialization.builtins.ListSerializer
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonObject
+import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
+import java.util.UUID
+
+/** The outcome of contacting a server: what it is and what it offers, or why it failed. */
+sealed interface McpProbe {
+ data class Ok(val server: McpServerInfo, val tools: List<McpTool>) : McpProbe
+ data class Failed(val message: String) : McpProbe
+}
+
+/**
+ * The user's own MCP servers (issue #130), as one connector.
+ *
+ * Each server is added with a URL, an optional bearer token and optional
+ * headers, and can be switched on or off by itself; the connector switch turns
+ * them all off at once. The tools of the servers that are on are registered
+ * with [ToolRegistry] under this connector's id, named by [McpToolNames], so
+ * the hidden-tools gating withholds them whenever the connector is off. A
+ * server that is off or removed has its tools unregistered.
+ *
+ * Only tools a server marks `readOnlyHint` reach Monitor; every other tool is
+ * Operator-only, as there is no other way to know what it does.
+ */
+class McpServersConnector(
+ private val store: CredentialStore,
+ private val client: McpHttpClient = McpHttpClient()
+) : Connector {
+
+ private val json = Json { ignoreUnknownKeys = true }
+ private val serializer = ListSerializer(McpServerConfig.serializer())
+ private val stateLock = Any()
+
+ @Volatile
+ private var servers: List<McpServerConfig> = store.loadRaw(ID)
+ ?.let { runCatching { json.decodeFromString(serializer, it) }.getOrNull() }
+ .orEmpty()
+
+ /** Exposed tool name → (server id, the server's own tool name), for the servers that are on. */
+ @Volatile
+ private var routes: Map<String, Pair<String, String>> = emptyMap()
+
+ /** Live sessions by server id. Dropped when a server is edited or removed. */
+ private val sessions = mutableMapOf<String, McpHttpClient.Session>()
+
+ init {
+ register()
+ }
+
+ override val id = ID
+ override val displayName = "MCP servers"
+ override val description = "Your own Model Context Protocol servers, over Streamable HTTP."
+ override val spec = ConnectorCatalog.MCP
+ override val toolNames: Set<String>
+ get() = routes.keys
+
+ fun servers(): List<McpServerConfig> = servers
+
+ fun server(id: String): McpServerConfig? = servers.firstOrNull { it.id == id }
+
+ /** Exposed name → server tool name for [server], as the model sees them. */
+ fun exposedNames(server: McpServerConfig): Map<String, String> =
+ McpToolNames.exposedNames(
+ McpToolNames.slugs(servers)[server.id] ?: McpToolNames.slug(server.name),
+ server.tools
+ )
+
+ override fun isConnected(): Boolean = servers.isNotEmpty()
+
+ override fun statusLine(strings: StringLookup): String {
+ val list = servers
+ if (list.isEmpty()) return strings(R.string.connector_not_connected)
+ return strings(R.string.mcp_status_summary, list.count { it.enabled }, list.size, routes.size)
+ }
+
+ /** Removes every server. */
+ override fun disconnect() {
+ synchronized(stateLock) {
+ servers = emptyList()
+ sessions.clear()
+ store.clear(ID)
+ register()
+ }
+ }
+
+ /**
+ * Checks [url], [token] and [headers] and contacts the server, without
+ * saving anything. The card's "Test connection".
+ */
+ suspend fun probe(url: String, token: String, headers: Map<String, String>, strings: StringLookup): McpProbe {
+ validateMcpServer(url, token, headers)?.let { return McpProbe.Failed(problemMessage(it, strings)) }
+ val draft = McpServerConfig(id = "probe", name = "probe", url = url.trim(), token = token, headers = headers)
+ return try {
+ val session = client.session(draft.endpoint())
+ val info = session.initialize()
+ McpProbe.Ok(info, session.listTools())
+ } catch (e: CancellationException) {
+ throw e
+ } catch (e: McpException) {
+ McpProbe.Failed(failureMessage(e, strings))
+ }
+ }
+
+ /**
+ * Adds a server, or updates the one with [id], after a successful probe.
+ * Nothing is saved when the server cannot be reached. Returns the message
+ * for the card and whether it was saved.
+ */
+ suspend fun save(
+ id: String?,
+ name: String,
+ url: String,
+ token: String,
+ headers: Map<String, String>,
+ strings: StringLookup
+ ): Pair<Boolean, String> {
+ if (name.isBlank()) return false to strings(R.string.mcp_error_name)
+ val probe = probe(url, token, headers, strings)
+ if (probe is McpProbe.Failed) return false to probe.message
+ probe as McpProbe.Ok
+ val tools = usableTools(probe.tools)
+ val saved = synchronized(stateLock) {
+ val existing = id?.let { server(it) }
+ if (id != null && existing == null) return false to strings(R.string.mcp_removed_while_saving)
+ val config = McpServerConfig(
+ id = existing?.id ?: UUID.randomUUID().toString(),
+ name = name.trim(),
+ url = url.trim(),
+ token = token.trim(),
+ headers = headers,
+ enabled = existing?.enabled ?: true,
+ tools = tools,
+ serverName = probe.server.name
+ )
+ servers = if (existing == null) servers + config else servers.map { if (it.id == config.id) config else it }
+ sessions.remove(config.id)
+ persist()
+ register()
+ config
+ }
+ return true to connectedMessage(saved, probe.tools.size, strings)
+ }
+
+ fun remove(id: String) {
+ synchronized(stateLock) {
+ servers = servers.filterNot { it.id == id }
+ sessions.remove(id)
+ persist()
+ register()
+ }
+ }
+
+ fun setServerEnabled(id: String, enabled: Boolean) {
+ synchronized(stateLock) {
+ servers = servers.map { if (it.id == id) it.copy(enabled = enabled) else it }
+ persist()
+ register()
+ }
+ }
+
+ /** Re-reads one server's tools. Returns the message for the card. */
+ suspend fun refresh(id: String, strings: StringLookup): String {
+ val config = server(id) ?: return strings(R.string.mcp_removed_while_saving)
+ return try {
+ val tools = usableTools(sessionFor(config).listTools())
+ commit(config) { it.copy(tools = tools, lastError = null) }
+ strings.quantity(R.plurals.mcp_tools_count, tools.size, tools.size)
+ } catch (e: CancellationException) {
+ throw e
+ } catch (e: McpException) {
+ val message = failureMessage(e, strings)
+ commit(config) { it.copy(lastError = message) }
+ message
+ }
+ }
+
+ /** Refreshes every server that is on, for the Connectors page's "Refresh all" and auto-sync. */
+ override suspend fun refreshTools(strings: StringLookup): String = coroutineScope {
+ servers.filter { it.enabled }.map { async { refresh(it.id, strings) } }.awaitAll()
+ statusLine(strings)
+ }
+
+ /** Runs exposed tool [exposedName] on its server. */
+ suspend fun callTool(exposedName: String, args: JsonObject): ToolResult {
+ val (serverId, toolName) = routes[exposedName]
+ ?: return ToolResult.error("Tool '$exposedName' belongs to no MCP server that is switched on.")
+ val config = server(serverId) ?: return ToolResult.error("The MCP server for '$exposedName' was removed.")
+ return try {
+ val output = sessionFor(config).callTool(toolName, args)
+ if (output.isError) ToolResult.error(output.text) else ToolResult.ok(output.text)
+ } catch (e: CancellationException) {
+ throw e
+ } catch (e: McpException) {
+ ToolResult.error("MCP server '${config.name}' failed to run '$toolName': ${e.message}")
+ }
+ }
+
+ private fun sessionFor(config: McpServerConfig): McpHttpClient.Session = synchronized(stateLock) {
+ sessions.getOrPut(config.id) { client.session(config.endpoint()) }
+ }
+
+ /** Applies [change] to the stored server, unless it was edited or removed since [seen] was read. */
+ private fun commit(seen: McpServerConfig, change: (McpServerConfig) -> McpServerConfig) {
+ synchronized(stateLock) {
+ val current = server(seen.id) ?: return
+ if (current.url != seen.url || current.token != seen.token || current.headers != seen.headers) return
+ servers = servers.map { if (it.id == seen.id) change(it) else it }
+ persist()
+ register()
+ }
+ }
+
+ private fun persist() {
+ if (servers.isEmpty()) store.clear(ID) else store.saveRaw(ID, json.encodeToString(serializer, servers))
+ }
+
+ /**
+ * Registers the tools of every server that is on, replacing what this
+ * connector had registered. Called under [stateLock] (or from the
+ * constructor), so two changes can't register out of order.
+ */
+ private fun register() {
+ val list = servers
+ val slugs = McpToolNames.slugs(list)
+ val definitions = mutableListOf<ToolDefinition>()
+ val readOnly = mutableSetOf<String>()
+ val newRoutes = mutableMapOf<String, Pair<String, String>>()
+ list.filter { it.enabled }.forEach { server ->
+ val byName = server.tools.associateBy { it.name }
+ McpToolNames.exposedNames(slugs.getValue(server.id), server.tools).forEach { (exposed, original) ->
+ val tool = byName.getValue(original)
+ definitions += ToolDefinition(
+ function = FunctionDefinition(
+ exposed,
+ "[MCP server \"${server.name}\"] ${tool.description}".take(MAX_DESCRIPTION),
+ tool.inputSchema
+ )
+ )
+ if (tool.readOnly) readOnly += exposed
+ newRoutes[exposed] = server.id to original
+ }
+ }
+ val registered = ToolRegistry.setDynamicTools(ID, definitions, readOnly)
+ routes = newRoutes.filterKeys { it in registered }
+ }
+
+ private fun connectedMessage(config: McpServerConfig, offered: Int, strings: StringLookup): String {
+ val label = config.serverName.ifBlank { hostOf(config.url) }
+ val tools = strings.quantity(R.plurals.mcp_tools_count, config.tools.size, config.tools.size)
+ val capped = if (offered > MAX_TOOLS) " " + strings(R.string.mcp_tools_capped, MAX_TOOLS) else ""
+ return strings(R.string.mcp_connected, label, tools) + capped
+ }
+
+ fun failureMessage(e: McpException, strings: StringLookup): String = when (e.kind) {
+ McpFailure.AUTH -> strings(R.string.mcp_error_auth, e.httpCode)
+ McpFailure.NOT_FOUND -> strings(R.string.mcp_error_not_found)
+ McpFailure.OLD_TRANSPORT -> strings(R.string.mcp_error_old_transport)
+ McpFailure.NOT_MCP -> strings(R.string.mcp_error_not_mcp, e.detail.take(DETAIL_CHARS))
+ McpFailure.HTTP -> strings(R.string.mcp_error_http, e.httpCode, e.detail.take(DETAIL_CHARS))
+ McpFailure.RPC -> strings(R.string.mcp_error_rpc, e.detail.take(DETAIL_CHARS))
+ McpFailure.NETWORK -> strings(R.string.mcp_error_network, e.detail.take(DETAIL_CHARS))
+ }
+
+ companion object {
+ const val ID = "mcp"
+
+ /** Tools kept per server: past this, a server costs more prompt than it is likely worth. */
+ const val MAX_TOOLS = 64
+ private const val MAX_DESCRIPTION = 1024
+ private const val DETAIL_CHARS = 200
+
+ /** The tools a model can be offered: object schemas only, capped at [MAX_TOOLS]. */
+ internal fun usableTools(tools: List<McpTool>): List<McpTool> =
+ tools.mapNotNull { tool -> normalizedInputSchema(tool.inputSchema)?.let { tool.copy(inputSchema = it) } }
+ .take(MAX_TOOLS)
+
+ fun problemMessage(problem: McpConfigProblem, strings: StringLookup): String = when (problem) {
+ McpConfigProblem.BAD_URL -> strings(R.string.mcp_error_bad_url)
+ McpConfigProblem.CLEARTEXT_WITH_SECRET -> strings(R.string.mcp_error_cleartext)
+ McpConfigProblem.BAD_HEADER -> strings(R.string.mcp_error_bad_header)
+ McpConfigProblem.BAD_TOKEN -> strings(R.string.mcp_error_bad_token)
+ }
+
+ fun hostOf(url: String): String = url.toHttpUrlOrNull()?.host ?: url
+ }
+}
+
+/** Routes the exposed MCP tool names to [McpServersConnector]. */
+class McpServerTools(private val backend: () -> McpServersConnector?) : ToolRouter {
+
+ override val toolNames: Set<String>
+ get() = backend()?.toolNames.orEmpty()
+
+ override suspend fun execute(name: String, args: JsonObject): ToolResult =
+ backend()?.callTool(name, args)
+ ?: ToolResult.error("No MCP servers are set up. Ask the user to add one in Settings → Connectors.")
+}
diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
index bd0ed16..42d36bf 100644
--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt
@@ -710,7 +710,7 @@ class ToolExecutor(
/** The connector half of [unavailableResult] — no device grant to deep-link to. */
private fun connectorUnavailableMessage(name: String): String {
- // Dynamic tools (such as Home Assistant's) are registered at runtime, so the
+ // Dynamic tools (Home Assistant, MCP servers) are registered at runtime, so the
// compile-time catalog cannot know them; name the owning connector explicitly.
ToolRegistry.dynamicOwnerOf(name)?.let { owner ->
val connector = ConnectorCatalog.byId(owner)?.displayName ?: owner
diff --git a/app/src/main/java/com/gotcha/ui/ConnectorCards.kt b/app/src/main/java/com/gotcha/ui/ConnectorCards.kt
index c180aa4..ae47bed 100644
--- a/app/src/main/java/com/gotcha/ui/ConnectorCards.kt
+++ b/app/src/main/java/com/gotcha/ui/ConnectorCards.kt
@@ -68,7 +68,7 @@ import kotlinx.coroutines.launch
* switch toggles the body.
*/
@Composable
-private fun ConnectorHeader(
+internal fun ConnectorHeader(
title: String,
status: String,
expanded: Boolean,
@@ -153,7 +153,7 @@ private fun EnabledRow(
* credentials yet — the "tap to set up" affordance hint.
*/
@Composable
-private fun disconnectedHint(status: String): String =
+internal fun disconnectedHint(status: String): String =
if (status == stringResource(R.string.connector_not_connected)) {
stringResource(R.string.connector_cards_not_connected_hint)
} else {
diff --git a/app/src/main/java/com/gotcha/ui/ConnectorsSection.kt b/app/src/main/java/com/gotcha/ui/ConnectorsSection.kt
index 6287a72..6f8eab6 100644
--- a/app/src/main/java/com/gotcha/ui/ConnectorsSection.kt
+++ b/app/src/main/java/com/gotcha/ui/ConnectorsSection.kt
@@ -35,6 +35,7 @@ import com.gotcha.connectors.google.GoogleConnector
import com.gotcha.connectors.homeassistant.HomeAssistantConnector
import com.gotcha.connectors.imap.ImapConnector
import com.gotcha.connectors.imap.ImapCredentials
+import com.gotcha.connectors.mcp.McpServersConnector
import com.gotcha.connectors.microsoft.MicrosoftConnector
import com.gotcha.connectors.notion.NotionConnector
import com.gotcha.connectors.oauth.OAuthConnectFlow
@@ -64,6 +65,7 @@ fun ConnectorsSection() {
val microsoft = remember(registry) { registry.byId("microsoft") as MicrosoftConnector }
val notion = remember(registry) { registry.byId("notion") as NotionConnector }
val homeAssistant = remember(registry) { registry.byId("homeassistant") as HomeAssistantConnector }
+ val mcp = remember(registry) { registry.byId(McpServersConnector.ID) as McpServersConnector }
// The one piece of connector state that is *not* a credential, so it lives in
// Settings rather than the connector's own encrypted blob.
@@ -134,6 +136,8 @@ fun ConnectorsSection() {
NotionCard(notion, "notion" !in disabled) { setEnabled("notion", it) }
HorizontalDivider(thickness = 1.dp)
HomeAssistantCard(homeAssistant, "homeassistant" !in disabled) { setEnabled("homeassistant", it) }
+ HorizontalDivider(thickness = 1.dp)
+ McpServersCard(mcp, McpServersConnector.ID !in disabled) { setEnabled(McpServersConnector.ID, it) }
}
}
diff --git a/app/src/main/java/com/gotcha/ui/McpServersCard.kt b/app/src/main/java/com/gotcha/ui/McpServersCard.kt
new file mode 100644
index 0000000..0777683
--- /dev/null
+++ b/app/src/main/java/com/gotcha/ui/McpServersCard.kt
@@ -0,0 +1,363 @@
+package com.gotcha.ui
+
+import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.ExperimentalLayoutApi
+import androidx.compose.foundation.layout.FlowRow
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.text.KeyboardOptions
+import androidx.compose.material3.Button
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.OutlinedButton
+import androidx.compose.material3.OutlinedTextField
+import androidx.compose.material3.Switch
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.key
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.platform.testTag
+import androidx.compose.ui.res.pluralStringResource
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.input.KeyboardType
+import androidx.compose.ui.text.input.PasswordVisualTransformation
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import com.gotcha.R
+import com.gotcha.connectors.mcp.McpProbe
+import com.gotcha.connectors.mcp.McpServerConfig
+import com.gotcha.connectors.mcp.McpServersConnector
+import com.gotcha.connectors.mcp.formatHeaderLines
+import com.gotcha.connectors.mcp.parseHeaderLines
+import com.gotcha.i18n.stringLookup
+import kotlinx.coroutines.launch
+
+/** [editing] value for the add form, as opposed to a server id. */
+private const val NEW_SERVER = "+new"
+
+/**
+ * The Connectors card for the user's own MCP servers (issue #130): one row per
+ * server with its own switch, its tools, Refresh, Edit and Remove, and a form
+ * to add or edit one. Shaped like the other connector cards — collapsed to a
+ * header with the connector switch — but holds a list instead of one account.
+ *
+ * The form is inline rather than a dialog, like the other cards' fields.
+ */
+@Composable
+internal fun McpServersCard(
+ mcp: McpServersConnector,
+ enabled: Boolean,
+ onEnabledChange: (Boolean) -> Unit
+) {
+ val strings = LocalContext.current.stringLookup()
+ // Bumped after every change, so the server list and status are read again.
+ var tick by remember { mutableStateOf(0) }
+ var expanded by remember { mutableStateOf(false) }
+ var editing by remember { mutableStateOf<String?>(null) }
+ var message by remember { mutableStateOf("") }
+ val servers = remember(tick) { mcp.servers() }
+ val changed = { tick++ }
+
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ key(tick) {
+ val status = mcp.statusLine(strings)
+ ConnectorHeader(
+ title = stringResource(R.string.mcp_card_title),
+ status = if (mcp.isConnected()) status else disconnectedHint(status),
+ expanded = expanded,
+ onToggle = { expanded = !expanded },
+ showSwitch = mcp.isConnected(),
+ enabled = enabled,
+ onEnabledChange = onEnabledChange,
+ headerTestTag = "connector_header_mcp"
+ )
+ }
+ if (message.isNotBlank()) Text(message, style = MaterialTheme.typography.bodySmall)
+
+ AnimatedVisibility(visible = expanded) {
+ Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
+ Text(stringResource(R.string.mcp_card_blurb), style = MaterialTheme.typography.bodySmall)
+ Text(stringResource(R.string.mcp_card_monitor_note), style = MaterialTheme.typography.bodySmall)
+ Text(
+ stringResource(R.string.mcp_card_trust),
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.error
+ )
+ servers.forEach { server ->
+ if (editing == server.id) {
+ McpServerForm(mcp, server, onDone = { saved, text ->
+ message = text
+ if (saved) editing = null
+ changed()
+ }, onCancel = { editing = null })
+ } else {
+ McpServerRow(
+ mcp = mcp,
+ server = server,
+ onEdit = { editing = server.id },
+ onChanged = { text ->
+ message = text
+ changed()
+ }
+ )
+ }
+ }
+ if (editing == NEW_SERVER) {
+ McpServerForm(mcp, null, onDone = { saved, text ->
+ message = text
+ if (saved) editing = null
+ changed()
+ }, onCancel = { editing = null })
+ } else {
+ OutlinedButton(
+ onClick = {
+ editing = NEW_SERVER
+ message = ""
+ },
+ modifier = Modifier.fillMaxWidth().testTag("mcp_add_server")
+ ) { Text(stringResource(R.string.mcp_add_server)) }
+ }
+ }
+ }
+ }
+}
+
+@OptIn(ExperimentalLayoutApi::class)
+@Composable
+private fun McpServerRow(
+ mcp: McpServersConnector,
+ server: McpServerConfig,
+ onEdit: () -> Unit,
+ onChanged: (String) -> Unit
+) {
+ val strings = LocalContext.current.stringLookup()
+ val scope = rememberCoroutineScope()
+ var busy by remember { mutableStateOf(false) }
+ var showTools by remember { mutableStateOf(false) }
+ var confirmRemove by remember(server.id) { mutableStateOf(false) }
+ val toolCount = pluralStringResource(R.plurals.mcp_tools_count, server.tools.size, server.tools.size)
+
+ Column(verticalArrangement = Arrangement.spacedBy(4.dp), modifier = Modifier.testTag("mcp_server_${server.id}")) {
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ Column(modifier = Modifier.weight(1f)) {
+ Text(server.name, style = MaterialTheme.typography.bodyLarge, fontWeight = FontWeight.Medium)
+ val error = server.lastError
+ when {
+ error != null -> Text(
+ error,
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.error
+ )
+ !server.enabled -> Text(
+ stringResource(R.string.mcp_server_off),
+ style = MaterialTheme.typography.bodySmall
+ )
+ else -> Text(
+ stringResource(R.string.mcp_server_status, McpServersConnector.hostOf(server.url), toolCount),
+ style = MaterialTheme.typography.bodySmall
+ )
+ }
+ }
+ val switchDescription = stringResource(R.string.connector_cards_enable, server.name)
+ Switch(
+ checked = server.enabled,
+ onCheckedChange = {
+ mcp.setServerEnabled(server.id, it)
+ onChanged("")
+ },
+ modifier = Modifier.semantics { contentDescription = switchDescription }
+ )
+ }
+ FlowRow(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
+ TextButton(onClick = { showTools = !showTools }) {
+ Text(
+ if (showTools) {
+ stringResource(R.string.mcp_hide_tools)
+ } else {
+ stringResource(R.string.mcp_show_tools, server.tools.size)
+ }
+ )
+ }
+ TextButton(
+ enabled = !busy,
+ onClick = {
+ busy = true
+ scope.launch {
+ val text = mcp.refresh(server.id, strings)
+ busy = false
+ onChanged(text)
+ }
+ }
+ ) {
+ Text(
+ stringResource(
+ if (busy) R.string.connector_cards_refreshing_tools else R.string.connector_cards_refresh_tools
+ )
+ )
+ }
+ TextButton(onClick = onEdit) { Text(stringResource(R.string.mcp_edit)) }
+ TextButton(onClick = {
+ if (confirmRemove) {
+ mcp.remove(server.id)
+ onChanged("")
+ } else {
+ confirmRemove = true
+ }
+ }) {
+ Text(
+ if (confirmRemove) {
+ stringResource(R.string.mcp_remove_confirm, server.name)
+ } else {
+ stringResource(R.string.mcp_remove)
+ },
+ color = MaterialTheme.colorScheme.error
+ )
+ }
+ }
+ if (showTools) {
+ if (server.tools.isEmpty()) {
+ Text(stringResource(R.string.mcp_no_tools), style = MaterialTheme.typography.bodySmall)
+ }
+ val byName = server.tools.associateBy { it.name }
+ Column(
+ verticalArrangement = Arrangement.spacedBy(6.dp),
+ modifier = Modifier.padding(start = 12.dp)
+ ) {
+ mcp.exposedNames(server).values.forEach { name ->
+ val tool = byName[name] ?: return@forEach
+ Column {
+ Text(tool.name, style = MaterialTheme.typography.bodyMedium)
+ Text(
+ stringResource(
+ if (tool.readOnly) R.string.mcp_tool_read_only else R.string.mcp_tool_operator
+ ),
+ style = MaterialTheme.typography.labelSmall,
+ color = MaterialTheme.colorScheme.primary
+ )
+ if (tool.description.isNotBlank()) {
+ Text(
+ tool.description,
+ style = MaterialTheme.typography.bodySmall,
+ maxLines = 2,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+/** Add ([existing] null) or edit a server. Test contacts it; Save tests again and stores it only if it answers. */
+@Composable
+private fun McpServerForm(
+ mcp: McpServersConnector,
+ existing: McpServerConfig?,
+ onDone: (saved: Boolean, message: String) -> Unit,
+ onCancel: () -> Unit
+) {
+ val strings = LocalContext.current.stringLookup()
+ val scope = rememberCoroutineScope()
+ var name by remember { mutableStateOf(existing?.name.orEmpty()) }
+ var url by remember { mutableStateOf(existing?.url.orEmpty()) }
+ var token by remember { mutableStateOf(existing?.token.orEmpty()) }
+ var headers by remember { mutableStateOf(existing?.headers?.let(::formatHeaderLines).orEmpty()) }
+ var busy by remember { mutableStateOf(false) }
+ var result by remember { mutableStateOf("") }
+ val badHeaders = stringResource(R.string.mcp_error_bad_header)
+
+ Column(
+ verticalArrangement = Arrangement.spacedBy(8.dp),
+ modifier = Modifier.testTag("mcp_server_form")
+ ) {
+ OutlinedTextField(
+ value = name,
+ onValueChange = { name = it },
+ label = { Text(stringResource(R.string.mcp_field_name)) },
+ singleLine = true,
+ modifier = Modifier.fillMaxWidth().testTag("mcp_field_name")
+ )
+ OutlinedTextField(
+ value = url,
+ onValueChange = { url = it },
+ label = { Text(stringResource(R.string.mcp_field_url)) },
+ placeholder = { Text("https://example.com/mcp") },
+ singleLine = true,
+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri),
+ modifier = Modifier.fillMaxWidth().testTag("mcp_field_url")
+ )
+ OutlinedTextField(
+ value = token,
+ onValueChange = { token = it },
+ label = { Text(stringResource(R.string.mcp_field_token)) },
+ singleLine = true,
+ visualTransformation = PasswordVisualTransformation(),
+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
+ modifier = Modifier.fillMaxWidth().testTag("mcp_field_token")
+ )
+ OutlinedTextField(
+ value = headers,
+ onValueChange = { headers = it },
+ label = { Text(stringResource(R.string.mcp_field_headers)) },
+ supportingText = { Text(stringResource(R.string.mcp_field_headers_hint)) },
+ minLines = 2,
+ modifier = Modifier.fillMaxWidth().testTag("mcp_field_headers")
+ )
+ if (result.isNotBlank()) Text(result, style = MaterialTheme.typography.bodySmall)
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ OutlinedButton(
+ enabled = !busy && url.isNotBlank(),
+ onClick = {
+ val parsed = parseHeaderLines(headers) ?: run {
+ result = badHeaders
+ return@OutlinedButton
+ }
+ busy = true
+ scope.launch {
+ result = when (val probe = mcp.probe(url, token, parsed, strings)) {
+ is McpProbe.Ok -> strings(
+ R.string.mcp_connected,
+ probe.server.name.ifBlank { McpServersConnector.hostOf(url) },
+ strings.quantity(R.plurals.mcp_tools_count, probe.tools.size, probe.tools.size)
+ )
+ is McpProbe.Failed -> probe.message
+ }
+ busy = false
+ }
+ },
+ modifier = Modifier.weight(1f).testTag("mcp_test")
+ ) { Text(stringResource(if (busy) R.string.mcp_testing else R.string.mcp_test_connection)) }
+ Button(
+ enabled = !busy && url.isNotBlank() && name.isNotBlank(),
+ onClick = {
+ val parsed = parseHeaderLines(headers) ?: run {
+ result = badHeaders
+ return@Button
+ }
+ busy = true
+ scope.launch {
+ val (saved, text) = mcp.save(existing?.id, name, url, token, parsed, strings)
+ busy = false
+ if (saved) onDone(true, text) else result = text
+ }
+ },
+ modifier = Modifier.weight(1f).testTag("mcp_save")
+ ) { Text(stringResource(if (busy) R.string.mcp_saving else R.string.mcp_save)) }
+ }
+ TextButton(onClick = onCancel, enabled = !busy) { Text(stringResource(R.string.mcp_cancel)) }
+ }
+}
diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml
index 253e5c6..0372625 100644
--- a/app/src/main/res/values-de/strings.xml
+++ b/app/src/main/res/values-de/strings.xml
@@ -1419,4 +1419,49 @@
<string name="notifications_app_updates_description">Etwa zweimal am Tag lädt Gotcha eine kleine Datei von GitHub (raw.githubusercontent.com), um zu prüfen, ob eine neue Version erschienen ist. Die Anfrage enthält nichts über dich; GitHub sieht deine IP-Adresse, wie bei jedem Download.</string>
<string name="notifications_notify_about_new_versions">Über neue Versionen benachrichtigen</string>
<string name="settings_field_update_notifications_enabled">Update-Benachrichtigungen</string>
+ <string name="mcp_card_title">MCP-Server</string>
+ <string name="mcp_card_blurb">Füge deine eigenen Model-Context-Protocol-Server hinzu. Gotcha verbindet sich über Streamable HTTP, listet die Tools jedes Servers auf und lässt den Assistenten sie nutzen, solange der Server eingeschaltet ist.</string>
+ <string name="mcp_card_monitor_note">Tools, die ein Server als nur lesend kennzeichnet, gibt es im Beobachter-Modus. Alle anderen Tools gibt es nur im Operator-Modus.</string>
+ <string name="mcp_card_trust">Die Tool-Beschreibungen und Ergebnisse eines Servers gehen unverändert an den Assistenten und können ihn lenken. Füge nur Server hinzu, denen du vertraust.</string>
+ <string name="mcp_add_server">Server hinzufügen</string>
+ <string name="mcp_field_name">Name</string>
+ <string name="mcp_field_url">Server-URL</string>
+ <string name="mcp_field_token">Bearer-Token (optional)</string>
+ <string name="mcp_field_headers">Zusätzliche Header (optional)</string>
+ <string name="mcp_field_headers_hint">Einer pro Zeile, als Name: Wert</string>
+ <string name="mcp_test_connection">Verbindung testen</string>
+ <string name="mcp_testing">Wird getestet…</string>
+ <string name="mcp_save">Speichern</string>
+ <string name="mcp_saving">Wird gespeichert…</string>
+ <string name="mcp_cancel">Abbrechen</string>
+ <string name="mcp_edit">Bearbeiten</string>
+ <string name="mcp_remove">Entfernen</string>
+ <string name="mcp_remove_confirm">Noch einmal tippen, um %1$s zu entfernen</string>
+ <string name="mcp_show_tools">Tools (%1$d)</string>
+ <string name="mcp_hide_tools">Tools ausblenden</string>
+ <string name="mcp_tool_read_only">Nur lesend: Beobachter und Operator</string>
+ <string name="mcp_tool_operator">Nur Operator</string>
+ <string name="mcp_server_off">Ausgeschaltet</string>
+ <string name="mcp_server_status">%1$s · %2$s</string>
+ <string name="mcp_no_tools">Dieser Server bietet keine Tools an.</string>
+ <string name="mcp_status_summary">%1$d von %2$d Servern an · %3$d Tools</string>
+ <plurals name="mcp_tools_count">
+ <item quantity="one">%1$d Tool</item>
+ <item quantity="other">%1$d Tools</item>
+ </plurals>
+ <string name="mcp_connected">Verbunden mit %1$s: %2$s.</string>
+ <string name="mcp_tools_capped">Nur die ersten %1$d werden genutzt.</string>
+ <string name="mcp_removed_while_saving">Dieser Server wurde inzwischen entfernt.</string>
+ <string name="mcp_error_name">Gib einen Namen für den Server ein.</string>
+ <string name="mcp_error_bad_url">Gib eine vollständige URL ein, die mit https:// beginnt (oder http:// in deinem lokalen Netzwerk).</string>
+ <string name="mcp_error_cleartext">Nutze https für einen Server außerhalb deines lokalen Netzwerks. Ein Token oder Header, der über http gesendet wird, kann unterwegs mitgelesen werden.</string>
+ <string name="mcp_error_bad_header">Schreibe jeden Header in eine eigene Zeile, als Name: Wert.</string>
+ <string name="mcp_error_auth">Der Server hat das Token oder die Header abgelehnt (HTTP %1$d). Prüfe sie und versuche es noch einmal.</string>
+ <string name="mcp_error_not_found">Unter dieser URL hat nichts geantwortet (HTTP 404). Prüfe die Adresse samt Pfad, der oft /mcp lautet.</string>
+ <string name="mcp_error_old_transport">Dieser Server nutzt den älteren HTTP+SSE-Transport, den Gotcha noch nicht unterstützt. Nutze die Streamable-HTTP-Adresse des Servers, falls es eine gibt.</string>
+ <string name="mcp_error_not_mcp">Der Server hat geantwortet, aber nicht als MCP-Server: %1$s</string>
+ <string name="mcp_error_http">Der Server hat HTTP %1$d zurückgegeben: %2$s</string>
+ <string name="mcp_error_rpc">Der Server hat einen Fehler gemeldet: %1$s</string>
+ <string name="mcp_error_network">Der Server ist nicht erreichbar: %1$s</string>
+ <string name="mcp_error_bad_token">Token und Header-Werte dürfen nur einfache ASCII-Zeichen enthalten.</string>
</resources>
diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml
index 2c9d722..9a09b07 100644
--- a/app/src/main/res/values-es/strings.xml
+++ b/app/src/main/res/values-es/strings.xml
@@ -1438,4 +1438,49 @@
<string name="notifications_app_updates_description">Unas dos veces al día, Gotcha descarga un pequeño archivo de GitHub (raw.githubusercontent.com) para ver si hay una versión nueva. La solicitud no lleva nada sobre ti; GitHub ve tu dirección IP, como en cualquier descarga.</string>
<string name="notifications_notify_about_new_versions">Avisarme de nuevas versiones</string>
<string name="settings_field_update_notifications_enabled">Avisos de actualización</string>
+ <string name="mcp_card_title">Servidores MCP</string>
+ <string name="mcp_card_blurb">Añade tus propios servidores Model Context Protocol. Gotcha se conecta por Streamable HTTP, muestra las herramientas de cada servidor y deja que el asistente las use mientras ese servidor esté activado.</string>
+ <string name="mcp_card_monitor_note">Las herramientas que un servidor marca como de solo lectura se pueden usar en Monitor. Todas las demás son solo para Operador.</string>
+ <string name="mcp_card_trust">Las descripciones y los resultados de las herramientas de un servidor llegan al asistente tal cual y pueden dirigirlo. Añade solo servidores de confianza.</string>
+ <string name="mcp_add_server">Añadir servidor</string>
+ <string name="mcp_field_name">Nombre</string>
+ <string name="mcp_field_url">URL del servidor</string>
+ <string name="mcp_field_token">Token Bearer (opcional)</string>
+ <string name="mcp_field_headers">Cabeceras adicionales (opcional)</string>
+ <string name="mcp_field_headers_hint">Una por línea, como Nombre: valor</string>
+ <string name="mcp_test_connection">Probar conexión</string>
+ <string name="mcp_testing">Probando…</string>
+ <string name="mcp_save">Guardar</string>
+ <string name="mcp_saving">Guardando…</string>
+ <string name="mcp_cancel">Cancelar</string>
+ <string name="mcp_edit">Editar</string>
+ <string name="mcp_remove">Quitar</string>
+ <string name="mcp_remove_confirm">Toca otra vez para quitar %1$s</string>
+ <string name="mcp_show_tools">Herramientas (%1$d)</string>
+ <string name="mcp_hide_tools">Ocultar herramientas</string>
+ <string name="mcp_tool_read_only">Solo lectura: Monitor y Operador</string>
+ <string name="mcp_tool_operator">Solo Operador</string>
+ <string name="mcp_server_off">Desactivado</string>
+ <string name="mcp_server_status">%1$s · %2$s</string>
+ <string name="mcp_no_tools">Este servidor no ofrece herramientas.</string>
+ <string name="mcp_status_summary">%1$d de %2$d servidores activos · %3$d herramientas</string>
+ <plurals name="mcp_tools_count">
+ <item quantity="one">%1$d herramienta</item>
+ <item quantity="other">%1$d herramientas</item>
+ </plurals>
+ <string name="mcp_connected">Conectado a %1$s: %2$s.</string>
+ <string name="mcp_tools_capped">Solo se usan las primeras %1$d.</string>
+ <string name="mcp_removed_while_saving">Ese servidor se quitó mientras tanto.</string>
+ <string name="mcp_error_name">Escribe un nombre para el servidor.</string>
+ <string name="mcp_error_bad_url">Escribe una URL completa que empiece por https:// (o http:// en tu red local).</string>
+ <string name="mcp_error_cleartext">Usa https para un servidor fuera de tu red local. Un token o una cabecera enviados por http se pueden leer por el camino.</string>
+ <string name="mcp_error_bad_header">Escribe cada cabecera en su propia línea, como Nombre: valor.</string>
+ <string name="mcp_error_auth">El servidor rechazó el token o las cabeceras (HTTP %1$d). Revísalos y vuelve a intentarlo.</string>
+ <string name="mcp_error_not_found">Nada respondió en esta URL (HTTP 404). Revisa la dirección, incluida la ruta, que suele ser /mcp.</string>
+ <string name="mcp_error_old_transport">Este servidor usa el transporte HTTP+SSE antiguo, que Gotcha aún no admite. Usa la dirección Streamable HTTP del servidor si la tiene.</string>
+ <string name="mcp_error_not_mcp">El servidor respondió, pero no como un servidor MCP: %1$s</string>
+ <string name="mcp_error_http">El servidor devolvió HTTP %1$d: %2$s</string>
+ <string name="mcp_error_rpc">El servidor devolvió un error: %1$s</string>
+ <string name="mcp_error_network">No se pudo conectar con el servidor: %1$s</string>
+ <string name="mcp_error_bad_token">El token y los valores de las cabeceras solo pueden contener caracteres ASCII simples.</string>
</resources>
diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml
index 3bc93b7..2574d65 100644
--- a/app/src/main/res/values-fr/strings.xml
+++ b/app/src/main/res/values-fr/strings.xml
@@ -1438,4 +1438,49 @@
<string name="notifications_app_updates_description">Environ deux fois par jour, Gotcha télécharge un petit fichier depuis GitHub (raw.githubusercontent.com) pour voir si une nouvelle version est sortie. La requête ne contient rien sur vous ; GitHub voit votre adresse IP, comme pour tout téléchargement.</string>
<string name="notifications_notify_about_new_versions">M\'avertir des nouvelles versions</string>
<string name="settings_field_update_notifications_enabled">Notifications de mise à jour</string>
+ <string name="mcp_card_title">Serveurs MCP</string>
+ <string name="mcp_card_blurb">Ajoutez vos propres serveurs Model Context Protocol. Gotcha s\'y connecte en Streamable HTTP, liste les outils de chaque serveur et laisse l\'assistant s\'en servir tant que ce serveur est activé.</string>
+ <string name="mcp_card_monitor_note">Les outils qu\'un serveur indique en lecture seule sont utilisables en mode Observateur. Tous ses autres outils sont réservés au mode Opérateur.</string>
+ <string name="mcp_card_trust">Les descriptions et les résultats des outils d\'un serveur arrivent tels quels à l\'assistant et peuvent l\'orienter. N\'ajoutez que des serveurs de confiance.</string>
+ <string name="mcp_add_server">Ajouter un serveur</string>
+ <string name="mcp_field_name">Nom</string>
+ <string name="mcp_field_url">URL du serveur</string>
+ <string name="mcp_field_token">Jeton Bearer (facultatif)</string>
+ <string name="mcp_field_headers">En-têtes supplémentaires (facultatif)</string>
+ <string name="mcp_field_headers_hint">Un par ligne, sous la forme Nom: valeur</string>
+ <string name="mcp_test_connection">Tester la connexion</string>
+ <string name="mcp_testing">Test en cours…</string>
+ <string name="mcp_save">Enregistrer</string>
+ <string name="mcp_saving">Enregistrement…</string>
+ <string name="mcp_cancel">Annuler</string>
+ <string name="mcp_edit">Modifier</string>
+ <string name="mcp_remove">Retirer</string>
+ <string name="mcp_remove_confirm">Touchez encore pour retirer %1$s</string>
+ <string name="mcp_show_tools">Outils (%1$d)</string>
+ <string name="mcp_hide_tools">Masquer les outils</string>
+ <string name="mcp_tool_read_only">Lecture seule : Observateur et Opérateur</string>
+ <string name="mcp_tool_operator">Opérateur uniquement</string>
+ <string name="mcp_server_off">Désactivé</string>
+ <string name="mcp_server_status">%1$s · %2$s</string>
+ <string name="mcp_no_tools">Ce serveur ne propose aucun outil.</string>
+ <string name="mcp_status_summary">%1$d serveurs actifs sur %2$d · %3$d outils</string>
+ <plurals name="mcp_tools_count">
+ <item quantity="one">%1$d outil</item>
+ <item quantity="other">%1$d outils</item>
+ </plurals>
+ <string name="mcp_connected">Connecté à %1$s : %2$s.</string>
+ <string name="mcp_tools_capped">Seuls les %1$d premiers sont utilisés.</string>
+ <string name="mcp_removed_while_saving">Ce serveur a été retiré entre-temps.</string>
+ <string name="mcp_error_name">Saisissez un nom pour le serveur.</string>
+ <string name="mcp_error_bad_url">Saisissez une URL complète commençant par https:// (ou http:// sur votre réseau local).</string>
+ <string name="mcp_error_cleartext">Utilisez https pour un serveur hors de votre réseau local. Un jeton ou un en-tête envoyé en http peut être lu en chemin.</string>
+ <string name="mcp_error_bad_header">Écrivez chaque en-tête sur sa propre ligne, sous la forme Nom: valeur.</string>
+ <string name="mcp_error_auth">Le serveur a refusé le jeton ou les en-têtes (HTTP %1$d). Vérifiez-les et réessayez.</string>
+ <string name="mcp_error_not_found">Rien n\'a répondu à cette URL (HTTP 404). Vérifiez l\'adresse, y compris son chemin, souvent /mcp.</string>
+ <string name="mcp_error_old_transport">Ce serveur utilise l\'ancien transport HTTP+SSE, que Gotcha ne prend pas encore en charge. Utilisez l\'adresse Streamable HTTP du serveur s\'il en a une.</string>
+ <string name="mcp_error_not_mcp">Le serveur a répondu, mais pas comme un serveur MCP : %1$s</string>
+ <string name="mcp_error_http">Le serveur a renvoyé HTTP %1$d : %2$s</string>
+ <string name="mcp_error_rpc">Le serveur a renvoyé une erreur : %1$s</string>
+ <string name="mcp_error_network">Impossible de joindre le serveur : %1$s</string>
+ <string name="mcp_error_bad_token">Le jeton et les valeurs des en-têtes ne peuvent contenir que des caractères ASCII simples.</string>
</resources>
diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml
index d13311f..fceba37 100644
--- a/app/src/main/res/values-hi/strings.xml
+++ b/app/src/main/res/values-hi/strings.xml
@@ -1419,4 +1419,49 @@
<string name="notifications_app_updates_description">दिन में लगभग दो बार Gotcha यह देखने के लिए GitHub (raw.githubusercontent.com) से एक छोटी फ़ाइल डाउनलोड करता है कि नया वर्शन आया है या नहीं। इस अनुरोध में आपके बारे में कुछ नहीं होता; किसी भी डाउनलोड की तरह GitHub आपका IP पता देखता है।</string>
<string name="notifications_notify_about_new_versions">नए वर्शन के बारे में सूचित करें</string>
<string name="settings_field_update_notifications_enabled">अपडेट सूचनाएँ</string>
+ <string name="mcp_card_title">MCP सर्वर</string>
+ <string name="mcp_card_blurb">अपने खुद के Model Context Protocol सर्वर जोड़ें। Gotcha, Streamable HTTP से जुड़ता है, हर सर्वर के टूल की सूची दिखाता है, और जब तक वह सर्वर चालू है, असिस्टेंट को उनका इस्तेमाल करने देता है।</string>
+ <string name="mcp_card_monitor_note">जिन टूल को सर्वर सिर्फ़ पढ़ने वाला बताता है, वे मॉनिटर में इस्तेमाल हो सकते हैं। बाकी सभी टूल सिर्फ़ ऑपरेटर के लिए हैं।</string>
+ <string name="mcp_card_trust">सर्वर के टूल का विवरण और नतीजे जैसे के तैसे असिस्टेंट तक पहुँचते हैं और उसे दिशा दे सकते हैं। सिर्फ़ भरोसेमंद सर्वर जोड़ें।</string>
+ <string name="mcp_add_server">सर्वर जोड़ें</string>
+ <string name="mcp_field_name">नाम</string>
+ <string name="mcp_field_url">सर्वर URL</string>
+ <string name="mcp_field_token">Bearer टोकन (वैकल्पिक)</string>
+ <string name="mcp_field_headers">अतिरिक्त हेडर (वैकल्पिक)</string>
+ <string name="mcp_field_headers_hint">हर लाइन में एक, Name: value के रूप में</string>
+ <string name="mcp_test_connection">कनेक्शन जाँचें</string>
+ <string name="mcp_testing">जाँच हो रही है…</string>
+ <string name="mcp_save">सहेजें</string>
+ <string name="mcp_saving">सहेजा जा रहा है…</string>
+ <string name="mcp_cancel">रद्द करें</string>
+ <string name="mcp_edit">बदलें</string>
+ <string name="mcp_remove">हटाएँ</string>
+ <string name="mcp_remove_confirm">%1$s हटाने के लिए फिर से टैप करें</string>
+ <string name="mcp_show_tools">टूल (%1$d)</string>
+ <string name="mcp_hide_tools">टूल छिपाएँ</string>
+ <string name="mcp_tool_read_only">सिर्फ़ पढ़ने वाला: मॉनिटर और ऑपरेटर</string>
+ <string name="mcp_tool_operator">सिर्फ़ ऑपरेटर</string>
+ <string name="mcp_server_off">बंद है</string>
+ <string name="mcp_server_status">%1$s · %2$s</string>
+ <string name="mcp_no_tools">यह सर्वर कोई टूल नहीं देता।</string>
+ <string name="mcp_status_summary">%2$d में से %1$d सर्वर चालू · %3$d टूल</string>
+ <plurals name="mcp_tools_count">
+ <item quantity="one">%1$d टूल</item>
+ <item quantity="other">%1$d टूल</item>
+ </plurals>
+ <string name="mcp_connected">%1$s से जुड़ गए: %2$s।</string>
+ <string name="mcp_tools_capped">सिर्फ़ पहले %1$d इस्तेमाल होते हैं।</string>
+ <string name="mcp_removed_while_saving">इस बीच वह सर्वर हटा दिया गया।</string>
+ <string name="mcp_error_name">सर्वर का नाम लिखें।</string>
+ <string name="mcp_error_bad_url">https:// से शुरू होने वाला पूरा URL लिखें (या अपने लोकल नेटवर्क पर http://)।</string>
+ <string name="mcp_error_cleartext">अपने लोकल नेटवर्क से बाहर के सर्वर के लिए https इस्तेमाल करें। http पर भेजा गया टोकन या हेडर रास्ते में पढ़ा जा सकता है।</string>
+ <string name="mcp_error_bad_header">हर हेडर अलग लाइन में Name: value के रूप में लिखें।</string>
+ <string name="mcp_error_auth">सर्वर ने टोकन या हेडर अस्वीकार कर दिए (HTTP %1$d)। उन्हें जाँचें और फिर से कोशिश करें।</string>
+ <string name="mcp_error_not_found">इस URL पर किसी ने जवाब नहीं दिया (HTTP 404)। पता और उसका पाथ जाँचें, जो अक्सर /mcp होता है।</string>
+ <string name="mcp_error_old_transport">यह सर्वर पुराना HTTP+SSE ट्रांसपोर्ट इस्तेमाल करता है, जिसे Gotcha अभी सपोर्ट नहीं करता। अगर सर्वर का Streamable HTTP पता है, तो वह इस्तेमाल करें।</string>
+ <string name="mcp_error_not_mcp">सर्वर ने जवाब दिया, लेकिन MCP सर्वर की तरह नहीं: %1$s</string>
+ <string name="mcp_error_http">सर्वर ने HTTP %1$d लौटाया: %2$s</string>
+ <string name="mcp_error_rpc">सर्वर ने एक त्रुटि लौटाई: %1$s</string>
+ <string name="mcp_error_network">सर्वर तक नहीं पहुँच सके: %1$s</string>
+ <string name="mcp_error_bad_token">टोकन और हेडर की वैल्यू में सिर्फ़ सामान्य ASCII अक्षर हो सकते हैं।</string>
</resources>
diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml
index 21dbcf2..236b536 100644
--- a/app/src/main/res/values-it/strings.xml
+++ b/app/src/main/res/values-it/strings.xml
@@ -1438,4 +1438,49 @@
<string name="notifications_app_updates_description">Circa due volte al giorno Gotcha scarica un piccolo file da GitHub (raw.githubusercontent.com) per vedere se è uscita una nuova versione. La richiesta non contiene nulla su di te; GitHub vede il tuo indirizzo IP, come per qualsiasi download.</string>
<string name="notifications_notify_about_new_versions">Avvisami delle nuove versioni</string>
<string name="settings_field_update_notifications_enabled">Notifiche di aggiornamento</string>
+ <string name="mcp_card_title">Server MCP</string>
+ <string name="mcp_card_blurb">Aggiungi i tuoi server Model Context Protocol. Gotcha si collega tramite Streamable HTTP, elenca gli strumenti di ogni server e permette all\'assistente di usarli finché quel server è attivo.</string>
+ <string name="mcp_card_monitor_note">Gli strumenti che un server segna come di sola lettura si possono usare in modalità Osservatore. Tutti gli altri sono solo per la modalità Operatore.</string>
+ <string name="mcp_card_trust">Le descrizioni e i risultati degli strumenti di un server arrivano all\'assistente così come sono e possono guidarlo. Aggiungi solo server di cui ti fidi.</string>
+ <string name="mcp_add_server">Aggiungi server</string>
+ <string name="mcp_field_name">Nome</string>
+ <string name="mcp_field_url">URL del server</string>
+ <string name="mcp_field_token">Token Bearer (facoltativo)</string>
+ <string name="mcp_field_headers">Intestazioni aggiuntive (facoltativo)</string>
+ <string name="mcp_field_headers_hint">Una per riga, come Nome: valore</string>
+ <string name="mcp_test_connection">Prova connessione</string>
+ <string name="mcp_testing">Prova in corso…</string>
+ <string name="mcp_save">Salva</string>
+ <string name="mcp_saving">Salvataggio…</string>
+ <string name="mcp_cancel">Annulla</string>
+ <string name="mcp_edit">Modifica</string>
+ <string name="mcp_remove">Rimuovi</string>
+ <string name="mcp_remove_confirm">Tocca di nuovo per rimuovere %1$s</string>
+ <string name="mcp_show_tools">Strumenti (%1$d)</string>
+ <string name="mcp_hide_tools">Nascondi strumenti</string>
+ <string name="mcp_tool_read_only">Sola lettura: Osservatore e Operatore</string>
+ <string name="mcp_tool_operator">Solo Operatore</string>
+ <string name="mcp_server_off">Disattivato</string>
+ <string name="mcp_server_status">%1$s · %2$s</string>
+ <string name="mcp_no_tools">Questo server non offre strumenti.</string>
+ <string name="mcp_status_summary">%1$d server attivi su %2$d · %3$d strumenti</string>
+ <plurals name="mcp_tools_count">
+ <item quantity="one">%1$d strumento</item>
+ <item quantity="other">%1$d strumenti</item>
+ </plurals>
+ <string name="mcp_connected">Connesso a %1$s: %2$s.</string>
+ <string name="mcp_tools_capped">Vengono usati solo i primi %1$d.</string>
+ <string name="mcp_removed_while_saving">Quel server è stato rimosso nel frattempo.</string>
+ <string name="mcp_error_name">Inserisci un nome per il server.</string>
+ <string name="mcp_error_bad_url">Inserisci un URL completo che inizi con https:// (o http:// sulla tua rete locale).</string>
+ <string name="mcp_error_cleartext">Usa https per un server fuori dalla tua rete locale. Un token o un\'intestazione inviati via http possono essere letti lungo il percorso.</string>
+ <string name="mcp_error_bad_header">Scrivi ogni intestazione su una riga, come Nome: valore.</string>
+ <string name="mcp_error_auth">Il server ha rifiutato il token o le intestazioni (HTTP %1$d). Controllali e riprova.</string>
+ <string name="mcp_error_not_found">Nessuno ha risposto a questo URL (HTTP 404). Controlla l\'indirizzo, compreso il percorso, spesso /mcp.</string>
+ <string name="mcp_error_old_transport">Questo server usa il vecchio trasporto HTTP+SSE, che Gotcha non supporta ancora. Usa l\'indirizzo Streamable HTTP del server, se ne ha uno.</string>
+ <string name="mcp_error_not_mcp">Il server ha risposto, ma non come server MCP: %1$s</string>
+ <string name="mcp_error_http">Il server ha restituito HTTP %1$d: %2$s</string>
+ <string name="mcp_error_rpc">Il server ha restituito un errore: %1$s</string>
+ <string name="mcp_error_network">Impossibile raggiungere il server: %1$s</string>
+ <string name="mcp_error_bad_token">Il token e i valori delle intestazioni possono contenere solo caratteri ASCII semplici.</string>
</resources>
diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml
index 10eff14..913ebf8 100644
--- a/app/src/main/res/values-ja/strings.xml
+++ b/app/src/main/res/values-ja/strings.xml
@@ -1400,4 +1400,48 @@
<string name="notifications_app_updates_description">Gotcha は 1 日に 2 回ほど、新しいバージョンが出ているかを確かめるために GitHub(raw.githubusercontent.com)から小さなファイルをダウンロードします。このリクエストにあなたに関する情報は含まれません。ほかのダウンロードと同じく、GitHub には IP アドレスが見えます。</string>
<string name="notifications_notify_about_new_versions">新しいバージョンを通知する</string>
<string name="settings_field_update_notifications_enabled">更新の通知</string>
+ <string name="mcp_card_title">MCP サーバー</string>
+ <string name="mcp_card_blurb">自分の Model Context Protocol サーバーを追加します。Gotcha は Streamable HTTP で接続し、各サーバーのツールを一覧にして、そのサーバーがオンの間はアシスタントが使えるようにします。</string>
+ <string name="mcp_card_monitor_note">サーバーが読み取り専用としているツールはモニターでも使えます。それ以外のツールはオペレーター専用です。</string>
+ <string name="mcp_card_trust">サーバーのツールの説明と結果はそのままアシスタントに渡り、その動きに影響することがあります。信頼できるサーバーだけを追加してください。</string>
+ <string name="mcp_add_server">サーバーを追加</string>
+ <string name="mcp_field_name">名前</string>
+ <string name="mcp_field_url">サーバーの URL</string>
+ <string name="mcp_field_token">Bearer トークン(任意)</string>
+ <string name="mcp_field_headers">追加のヘッダー(任意)</string>
+ <string name="mcp_field_headers_hint">1 行に 1 つ、Name: value の形で</string>
+ <string name="mcp_test_connection">接続をテスト</string>
+ <string name="mcp_testing">テスト中…</string>
+ <string name="mcp_save">保存</string>
+ <string name="mcp_saving">保存中…</string>
+ <string name="mcp_cancel">キャンセル</string>
+ <string name="mcp_edit">編集</string>
+ <string name="mcp_remove">削除</string>
+ <string name="mcp_remove_confirm">もう一度タップすると %1$s を削除します</string>
+ <string name="mcp_show_tools">ツール(%1$d)</string>
+ <string name="mcp_hide_tools">ツールを隠す</string>
+ <string name="mcp_tool_read_only">読み取り専用:モニターとオペレーター</string>
+ <string name="mcp_tool_operator">オペレーターのみ</string>
+ <string name="mcp_server_off">オフ</string>
+ <string name="mcp_server_status">%1$s · %2$s</string>
+ <string name="mcp_no_tools">このサーバーにはツールがありません。</string>
+ <string name="mcp_status_summary">%2$d 台中 %1$d 台がオン · ツール %3$d 個</string>
+ <plurals name="mcp_tools_count">
+ <item quantity="other">ツール %1$d 個</item>
+ </plurals>
+ <string name="mcp_connected">%1$s に接続しました:%2$s。</string>
+ <string name="mcp_tools_capped">使われるのは最初の %1$d 個だけです。</string>
+ <string name="mcp_removed_while_saving">そのサーバーはその間に削除されました。</string>
+ <string name="mcp_error_name">サーバーの名前を入力してください。</string>
+ <string name="mcp_error_bad_url">https:// で始まる完全な URL を入力してください(ローカルネットワークでは http:// も可)。</string>
+ <string name="mcp_error_cleartext">ローカルネットワーク外のサーバーには https を使ってください。http で送ったトークンやヘッダーは途中で読まれるおそれがあります。</string>
+ <string name="mcp_error_bad_header">ヘッダーは 1 行に 1 つ、Name: value の形で書いてください。</string>
+ <string name="mcp_error_auth">サーバーがトークンまたはヘッダーを拒否しました(HTTP %1$d)。確認してもう一度お試しください。</string>
+ <string name="mcp_error_not_found">この URL からは応答がありません(HTTP 404)。パス(多くは /mcp)も含めてアドレスを確認してください。</string>
+ <string name="mcp_error_old_transport">このサーバーは古い HTTP+SSE トランスポートを使っていて、Gotcha はまだ対応していません。サーバーに Streamable HTTP のアドレスがあればそちらを使ってください。</string>
+ <string name="mcp_error_not_mcp">サーバーは応答しましたが、MCP サーバーとしての応答ではありません:%1$s</string>
+ <string name="mcp_error_http">サーバーが HTTP %1$d を返しました:%2$s</string>
+ <string name="mcp_error_rpc">サーバーがエラーを返しました:%1$s</string>
+ <string name="mcp_error_network">サーバーに接続できません:%1$s</string>
+ <string name="mcp_error_bad_token">トークンとヘッダーの値には半角の ASCII 文字しか使えません。</string>
</resources>
diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml
index 801eea6..a4d4515 100644
--- a/app/src/main/res/values-pt-rBR/strings.xml
+++ b/app/src/main/res/values-pt-rBR/strings.xml
@@ -1438,4 +1438,49 @@
<string name="notifications_app_updates_description">Cerca de duas vezes por dia, o Gotcha baixa um pequeno arquivo do GitHub (raw.githubusercontent.com) para ver se saiu uma nova versão. A solicitação não leva nada sobre você; o GitHub vê seu endereço IP, como em qualquer download.</string>
<string name="notifications_notify_about_new_versions">Avisar sobre novas versões</string>
<string name="settings_field_update_notifications_enabled">Avisos de atualização</string>
+ <string name="mcp_card_title">Servidores MCP</string>
+ <string name="mcp_card_blurb">Adicione seus próprios servidores Model Context Protocol. O Gotcha se conecta por Streamable HTTP, lista as ferramentas de cada servidor e deixa o assistente usá-las enquanto aquele servidor estiver ativado.</string>
+ <string name="mcp_card_monitor_note">As ferramentas que um servidor marca como somente leitura podem ser usadas no modo Observador. Todas as outras são só para o modo Operador.</string>
+ <string name="mcp_card_trust">As descrições e os resultados das ferramentas de um servidor chegam ao assistente como estão e podem direcioná-lo. Adicione só servidores em que você confia.</string>
+ <string name="mcp_add_server">Adicionar servidor</string>
+ <string name="mcp_field_name">Nome</string>
+ <string name="mcp_field_url">URL do servidor</string>
+ <string name="mcp_field_token">Token Bearer (opcional)</string>
+ <string name="mcp_field_headers">Cabeçalhos extras (opcional)</string>
+ <string name="mcp_field_headers_hint">Um por linha, como Nome: valor</string>
+ <string name="mcp_test_connection">Testar conexão</string>
+ <string name="mcp_testing">Testando…</string>
+ <string name="mcp_save">Salvar</string>
+ <string name="mcp_saving">Salvando…</string>
+ <string name="mcp_cancel">Cancelar</string>
+ <string name="mcp_edit">Editar</string>
+ <string name="mcp_remove">Remover</string>
+ <string name="mcp_remove_confirm">Toque de novo para remover %1$s</string>
+ <string name="mcp_show_tools">Ferramentas (%1$d)</string>
+ <string name="mcp_hide_tools">Ocultar ferramentas</string>
+ <string name="mcp_tool_read_only">Somente leitura: Observador e Operador</string>
+ <string name="mcp_tool_operator">Só Operador</string>
+ <string name="mcp_server_off">Desativado</string>
+ <string name="mcp_server_status">%1$s · %2$s</string>
+ <string name="mcp_no_tools">Este servidor não oferece ferramentas.</string>
+ <string name="mcp_status_summary">%1$d de %2$d servidores ativos · %3$d ferramentas</string>
+ <plurals name="mcp_tools_count">
+ <item quantity="one">%1$d ferramenta</item>
+ <item quantity="other">%1$d ferramentas</item>
+ </plurals>
+ <string name="mcp_connected">Conectado a %1$s: %2$s.</string>
+ <string name="mcp_tools_capped">Só as primeiras %1$d são usadas.</string>
+ <string name="mcp_removed_while_saving">Esse servidor foi removido nesse meio-tempo.</string>
+ <string name="mcp_error_name">Digite um nome para o servidor.</string>
+ <string name="mcp_error_bad_url">Digite uma URL completa que comece com https:// (ou http:// na sua rede local).</string>
+ <string name="mcp_error_cleartext">Use https para um servidor fora da sua rede local. Um token ou cabeçalho enviado por http pode ser lido no caminho.</string>
+ <string name="mcp_error_bad_header">Escreva cada cabeçalho em uma linha, como Nome: valor.</string>
+ <string name="mcp_error_auth">O servidor recusou o token ou os cabeçalhos (HTTP %1$d). Confira e tente de novo.</string>
+ <string name="mcp_error_not_found">Nada respondeu nesta URL (HTTP 404). Confira o endereço, incluindo o caminho, que muitas vezes é /mcp.</string>
+ <string name="mcp_error_old_transport">Este servidor usa o transporte HTTP+SSE antigo, que o Gotcha ainda não suporta. Use o endereço Streamable HTTP do servidor, se houver.</string>
+ <string name="mcp_error_not_mcp">O servidor respondeu, mas não como um servidor MCP: %1$s</string>
+ <string name="mcp_error_http">O servidor retornou HTTP %1$d: %2$s</string>
+ <string name="mcp_error_rpc">O servidor retornou um erro: %1$s</string>
+ <string name="mcp_error_network">Não foi possível acessar o servidor: %1$s</string>
+ <string name="mcp_error_bad_token">O token e os valores dos cabeçalhos só podem conter caracteres ASCII simples.</string>
</resources>
diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml
index dc872f7..5dbd70e 100644
--- a/app/src/main/res/values-zh-rCN/strings.xml
+++ b/app/src/main/res/values-zh-rCN/strings.xml
@@ -1400,4 +1400,48 @@
<string name="notifications_app_updates_description">Gotcha 每天大约两次从 GitHub(raw.githubusercontent.com)下载一个小文件,查看是否有新版本。该请求不包含任何关于你的信息;与任何下载一样,GitHub 能看到你的 IP 地址。</string>
<string name="notifications_notify_about_new_versions">有新版本时通知我</string>
<string name="settings_field_update_notifications_enabled">更新通知</string>
+ <string name="mcp_card_title">MCP 服务器</string>
+ <string name="mcp_card_blurb">添加你自己的 Model Context Protocol 服务器。Gotcha 通过 Streamable HTTP 连接,列出每个服务器的工具,并在该服务器开启时让助手使用它们。</string>
+ <string name="mcp_card_monitor_note">服务器标为只读的工具可在观察模式中使用,其余工具仅限操作模式。</string>
+ <string name="mcp_card_trust">服务器的工具说明和结果会原样传给助手,并可能左右它的行为。请只添加你信任的服务器。</string>
+ <string name="mcp_add_server">添加服务器</string>
+ <string name="mcp_field_name">名称</string>
+ <string name="mcp_field_url">服务器 URL</string>
+ <string name="mcp_field_token">Bearer 令牌(可选)</string>
+ <string name="mcp_field_headers">额外请求头(可选)</string>
+ <string name="mcp_field_headers_hint">每行一个,格式为 Name: value</string>
+ <string name="mcp_test_connection">测试连接</string>
+ <string name="mcp_testing">正在测试…</string>
+ <string name="mcp_save">保存</string>
+ <string name="mcp_saving">正在保存…</string>
+ <string name="mcp_cancel">取消</string>
+ <string name="mcp_edit">编辑</string>
+ <string name="mcp_remove">移除</string>
+ <string name="mcp_remove_confirm">再点一次即可移除 %1$s</string>
+ <string name="mcp_show_tools">工具(%1$d)</string>
+ <string name="mcp_hide_tools">隐藏工具</string>
+ <string name="mcp_tool_read_only">只读:观察和操作</string>
+ <string name="mcp_tool_operator">仅限操作</string>
+ <string name="mcp_server_off">已关闭</string>
+ <string name="mcp_server_status">%1$s · %2$s</string>
+ <string name="mcp_no_tools">此服务器不提供任何工具。</string>
+ <string name="mcp_status_summary">%2$d 个服务器中 %1$d 个已开启 · %3$d 个工具</string>
+ <plurals name="mcp_tools_count">
+ <item quantity="other">%1$d 个工具</item>
+ </plurals>
+ <string name="mcp_connected">已连接到 %1$s:%2$s。</string>
+ <string name="mcp_tools_capped">只使用前 %1$d 个。</string>
+ <string name="mcp_removed_while_saving">该服务器在此期间已被移除。</string>
+ <string name="mcp_error_name">请输入服务器名称。</string>
+ <string name="mcp_error_bad_url">请输入以 https:// 开头的完整 URL(在本地网络中也可用 http://)。</string>
+ <string name="mcp_error_cleartext">本地网络之外的服务器请使用 https。通过 http 发送的令牌或请求头可能在途中被读取。</string>
+ <string name="mcp_error_bad_header">每个请求头单独一行,格式为 Name: value。</string>
+ <string name="mcp_error_auth">服务器拒绝了令牌或请求头(HTTP %1$d)。请检查后重试。</string>
+ <string name="mcp_error_not_found">此 URL 没有响应(HTTP 404)。请检查地址及其路径,通常是 /mcp。</string>
+ <string name="mcp_error_old_transport">此服务器使用旧版 HTTP+SSE 传输,Gotcha 暂不支持。如果服务器有 Streamable HTTP 地址,请改用该地址。</string>
+ <string name="mcp_error_not_mcp">服务器有响应,但不是 MCP 服务器的响应:%1$s</string>
+ <string name="mcp_error_http">服务器返回了 HTTP %1$d:%2$s</string>
+ <string name="mcp_error_rpc">服务器返回了错误:%1$s</string>
+ <string name="mcp_error_network">无法连接到服务器:%1$s</string>
+ <string name="mcp_error_bad_token">令牌和请求头的值只能包含普通 ASCII 字符。</string>
</resources>
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 1270302..408ff31 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -1646,4 +1646,49 @@
<string name="notifications_app_updates_description">About twice a day, Gotcha downloads a small file from GitHub (raw.githubusercontent.com) to see whether a new version is out. The request carries nothing about you; GitHub sees your IP address, as with any download.</string>
<string name="notifications_notify_about_new_versions">Notify me about new versions</string>
<string name="settings_field_update_notifications_enabled">Update notifications</string>
+ <string name="mcp_card_title">MCP servers</string>
+ <string name="mcp_card_blurb">Add your own Model Context Protocol servers. Gotcha connects over Streamable HTTP, lists each server\'s tools, and lets the assistant use them while that server is switched on.</string>
+ <string name="mcp_card_monitor_note">Tools a server marks as read-only can be used in Monitor. All its other tools are for Operator only.</string>
+ <string name="mcp_card_trust">A server\'s tool descriptions and results go to the assistant as they are, and can steer it. Add only servers you trust.</string>
+ <string name="mcp_add_server">Add server</string>
+ <string name="mcp_field_name">Name</string>
+ <string name="mcp_field_url">Server URL</string>
+ <string name="mcp_field_token">Bearer token (optional)</string>
+ <string name="mcp_field_headers">Extra headers (optional)</string>
+ <string name="mcp_field_headers_hint">One per line, as Name: value</string>
+ <string name="mcp_test_connection">Test connection</string>
+ <string name="mcp_testing">Testing…</string>
+ <string name="mcp_save">Save</string>
+ <string name="mcp_saving">Saving…</string>
+ <string name="mcp_cancel">Cancel</string>
+ <string name="mcp_edit">Edit</string>
+ <string name="mcp_remove">Remove</string>
+ <string name="mcp_remove_confirm">Tap again to remove %1$s</string>
+ <string name="mcp_show_tools">Tools (%1$d)</string>
+ <string name="mcp_hide_tools">Hide tools</string>
+ <string name="mcp_tool_read_only">Read-only: Monitor and Operator</string>
+ <string name="mcp_tool_operator">Operator only</string>
+ <string name="mcp_server_off">Switched off</string>
+ <string name="mcp_server_status">%1$s · %2$s</string>
+ <string name="mcp_no_tools">This server offers no tools.</string>
+ <string name="mcp_status_summary">%1$d of %2$d servers on · %3$d tools</string>
+ <plurals name="mcp_tools_count">
+ <item quantity="one">%1$d tool</item>
+ <item quantity="other">%1$d tools</item>
+ </plurals>
+ <string name="mcp_connected">Connected to %1$s: %2$s.</string>
+ <string name="mcp_tools_capped">Only the first %1$d are used.</string>
+ <string name="mcp_removed_while_saving">That server was removed in the meantime.</string>
+ <string name="mcp_error_name">Enter a name for the server.</string>
+ <string name="mcp_error_bad_url">Enter a full URL that starts with https:// (or http:// on your local network).</string>
+ <string name="mcp_error_cleartext">Use https for a server outside your local network. A token or header sent over http can be read on the way.</string>
+ <string name="mcp_error_bad_header">Write each header on its own line, as Name: value.</string>
+ <string name="mcp_error_auth">The server refused the token or headers (HTTP %1$d). Check them and try again.</string>
+ <string name="mcp_error_not_found">Nothing answered at this URL (HTTP 404). Check the address, including its path, which is often /mcp.</string>
+ <string name="mcp_error_old_transport">This server uses the older HTTP+SSE transport, which Gotcha doesn\'t support yet. Use the server\'s Streamable HTTP address if it has one.</string>
+ <string name="mcp_error_not_mcp">The server answered, but not as an MCP server: %1$s</string>
+ <string name="mcp_error_http">The server returned HTTP %1$d: %2$s</string>
+ <string name="mcp_error_rpc">The server returned an error: %1$s</string>
+ <string name="mcp_error_network">Couldn\'t reach the server: %1$s</string>
+ <string name="mcp_error_bad_token">The token and header values can only contain plain ASCII characters.</string>
</resources>
diff --git a/app/src/test/java/com/gotcha/connectors/ConnectorGatingTest.kt b/app/src/test/java/com/gotcha/connectors/ConnectorGatingTest.kt
index d79b822..02a47d2 100644
--- a/app/src/test/java/com/gotcha/connectors/ConnectorGatingTest.kt
+++ b/app/src/test/java/com/gotcha/connectors/ConnectorGatingTest.kt
@@ -187,7 +187,7 @@ class ConnectorGatingTest {
@Test
fun `catalog ids match the connector ids the registry uses`() {
assertEquals(
- setOf("imap", "google", "microsoft", "notion", "homeassistant"),
+ setOf("imap", "google", "microsoft", "notion", "homeassistant", "mcp"),
ConnectorCatalog.all.map { it.id }.toSet()
)
}
diff --git a/app/src/test/java/com/gotcha/connectors/mcp/FakeMcpServer.kt b/app/src/test/java/com/gotcha/connectors/mcp/FakeMcpServer.kt
new file mode 100644
index 0000000..6877d81
--- /dev/null
+++ b/app/src/test/java/com/gotcha/connectors/mcp/FakeMcpServer.kt
@@ -0,0 +1,110 @@
+package com.gotcha.connectors.mcp
+
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonPrimitive
+import kotlinx.serialization.json.contentOrNull
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.jsonPrimitive
+import kotlinx.serialization.json.longOrNull
+import okhttp3.mockwebserver.Dispatcher
+import okhttp3.mockwebserver.MockResponse
+import okhttp3.mockwebserver.RecordedRequest
+import java.util.concurrent.CopyOnWriteArrayList
+
+/**
+ * A stateful Streamable HTTP MCP server for tests: hands out a session id,
+ * insists on it (and on the auth header, when [requiredAuth] is set), pages
+ * `tools/list` two tools at a time, and can answer over SSE.
+ */
+class FakeMcpServer(
+ var tools: List<String> = listOf(
+ """{"name":"search","description":"Search the docs",""" +
+ """"inputSchema":{"type":"object","properties":{"q":{"type":"string"}}},""" +
+ """"annotations":{"readOnlyHint":true}}""",
+ """{"name":"create_page","description":"Create a page","inputSchema":{"type":"object","properties":{}}}""",
+ """{"name":"delete_page","inputSchema":{"type":"object"}}"""
+ ),
+ var requiredAuth: String? = null,
+ var sse: Boolean = false
+) : Dispatcher() {
+
+ data class Seen(
+ val method: String?,
+ val sessionId: String?,
+ val protocolVersion: String?,
+ val auth: String?,
+ val headers: Map<String, String>
+ )
+
+ val seen = CopyOnWriteArrayList<Seen>()
+ private var session = 0
+ var currentSession: String? = null
+ private set
+
+ /** Forget the session, as a restarted server would: the next request with the old id gets 404. */
+ fun expireSession() {
+ currentSession = null
+ }
+
+ var callResult: String = """{"content":[{"type":"text","text":"found 3 pages"}]}"""
+
+ /** When set, `tools/call` answers with a JSON-RPC error carrying this message. */
+ var callError: String? = null
+
+ override fun dispatch(request: RecordedRequest): MockResponse {
+ if (request.method == "GET") return MockResponse().setResponseCode(405)
+ val body = Json.parseToJsonElement(request.body.readUtf8()).jsonObject
+ val method = body["method"]?.jsonPrimitive?.contentOrNull
+ val id = (body["id"] as? JsonPrimitive)?.longOrNull
+ seen += Seen(
+ method,
+ request.getHeader(McpHttpClient.HEADER_SESSION_ID),
+ request.getHeader(McpHttpClient.HEADER_PROTOCOL_VERSION),
+ request.getHeader("Authorization"),
+ request.headers.toMap()
+ )
+ if (requiredAuth != null && request.getHeader("Authorization") != requiredAuth) {
+ return MockResponse().setResponseCode(401).setBody("bad token")
+ }
+ if (method == "initialize") {
+ currentSession = "s-${++session}"
+ return reply(
+ id,
+ """{"protocolVersion":"2025-06-18","serverInfo":{"name":"Docs","version":"2.1"},"capabilities":{"tools":{}}}"""
+ )
+ .setHeader(McpHttpClient.HEADER_SESSION_ID, currentSession!!)
+ }
+ if (request.getHeader(McpHttpClient.HEADER_SESSION_ID) != currentSession) {
+ return MockResponse().setResponseCode(404).setBody("session not found")
+ }
+ return when (method) {
+ "notifications/initialized" -> MockResponse().setResponseCode(202)
+ "tools/list" -> {
+ val start = body["params"]?.jsonObject?.get("cursor")?.jsonPrimitive?.contentOrNull?.toInt() ?: 0
+ val page = tools.drop(start).take(2)
+ val next = if (start + 2 < tools.size) ""","nextCursor":"${start + 2}"""" else ""
+ reply(id, """{"tools":[${page.joinToString(",")}]$next}""")
+ }
+ "tools/call" -> callError?.let {
+ MockResponse().setBody("""{"jsonrpc":"2.0","id":$id,"error":{"code":-32602,"message":"$it"}}""")
+ } ?: reply(id, callResult)
+ else -> MockResponse().setBody(
+ """{"jsonrpc":"2.0","id":$id,"error":{"code":-32601,"message":"Method not found"}}"""
+ )
+ }
+ }
+
+ private fun reply(id: Long?, result: String): MockResponse {
+ val message = """{"jsonrpc":"2.0","id":$id,"result":$result}"""
+ if (!sse) return MockResponse().setHeader("Content-Type", "application/json").setBody(message)
+ // A progress notification and a server request before the response, as a real stream may carry.
+ val stream = buildString {
+ append(
+ "event: message\ndata: {\"jsonrpc\":\"2.0\",\"method\":\"notifications/progress\",\"params\":{}}\n\n"
+ )
+ append("data: {\"jsonrpc\":\"2.0\",\"id\":99,\"method\":\"ping\"}\n\n")
+ append("event: message\ndata: ").append(message).append("\n\n")
+ }
+ return MockResponse().setHeader("Content-Type", "text/event-stream").setBody(stream)
+ }
+}
diff --git a/app/src/test/java/com/gotcha/connectors/mcp/McpHttpClientTest.kt b/app/src/test/java/com/gotcha/connectors/mcp/McpHttpClientTest.kt
new file mode 100644
index 0000000..9495b2a
--- /dev/null
+++ b/app/src/test/java/com/gotcha/connectors/mcp/McpHttpClientTest.kt
@@ -0,0 +1,231 @@
+package com.gotcha.connectors.mcp
+
+import kotlinx.coroutines.test.runTest
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.put
+import okhttp3.OkHttpClient
+import okhttp3.mockwebserver.Dispatcher
+import okhttp3.mockwebserver.MockResponse
+import okhttp3.mockwebserver.MockWebServer
+import okhttp3.mockwebserver.RecordedRequest
+import org.junit.After
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Assert.fail
+import org.junit.Before
+import org.junit.Test
+import java.util.concurrent.TimeUnit
+
+/** The Streamable HTTP client for user-added MCP servers (issue #130). */
+class McpHttpClientTest {
+
+ private val server = MockWebServer()
+ private val fake = FakeMcpServer()
+ private val client = McpHttpClient()
+
+ @Before
+ fun setUp() {
+ server.dispatcher = fake
+ server.start()
+ }
+
+ @After
+ fun tearDown() = server.shutdown()
+
+ private fun endpoint(headers: Map<String, String> = emptyMap()) =
+ McpEndpoint(server.url("/mcp").toString(), headers)
+
+ private suspend fun failureOf(block: suspend () -> Unit): McpException {
+ try {
+ block()
+ } catch (e: McpException) {
+ return e
+ }
+ fail("expected an McpException")
+ error("unreachable")
+ }
+
+ @Test
+ fun `initialize sends initialized, then the session id and protocol version on every request`() = runTest {
+ val session = client.session(endpoint())
+
+ val info = session.initialize()
+ session.listTools()
+
+ assertEquals(McpServerInfo("Docs", "2.1", "2025-06-18"), info)
+ assertEquals(
+ listOf("initialize", "notifications/initialized", "tools/list", "tools/list"),
+ fake.seen.map { it.method }
+ )
+ val first = fake.seen.first()
+ assertEquals(null, first.sessionId)
+ assertEquals(null, first.protocolVersion)
+ fake.seen.drop(1).forEach {
+ assertEquals("s-1", it.sessionId)
+ assertEquals("2025-06-18", it.protocolVersion)
+ }
+ }
+
+ @Test
+ fun `tools come from every page, with read-only from the server's annotation`() = runTest {
+ val tools = client.session(endpoint()).listTools()
+
+ assertEquals(listOf("search", "create_page", "delete_page"), tools.map { it.name })
+ assertEquals(listOf(true, false, false), tools.map { it.readOnly })
+ assertEquals("Search the docs", tools.first().description)
+ }
+
+ @Test
+ fun `a first call initialises on its own`() = runTest {
+ val out = client.session(endpoint()).callTool("search", buildJsonObject { put("q", "x") })
+
+ assertEquals(McpToolOutput(isError = false, text = "found 3 pages"), out)
+ assertEquals("initialize", fake.seen.first().method)
+ }
+
+ @Test
+ fun `a dropped session is re-initialised once and the request retried`() = runTest {
+ val session = client.session(endpoint())
+ session.initialize()
+ fake.expireSession()
+
+ val out = session.callTool("search", buildJsonObject {})
+
+ assertEquals("found 3 pages", out.text)
+ assertEquals(
+ listOf(
+ "initialize",
+ "notifications/initialized",
+ "tools/call",
+ "initialize",
+ "notifications/initialized",
+ "tools/call"
+ ),
+ fake.seen.map { it.method }
+ )
+ assertEquals("s-2", fake.seen.last().sessionId)
+ }
+
+ @Test
+ fun `event-stream replies skip notifications and server requests`() = runTest {
+ fake.sse = true
+
+ val tools = client.session(endpoint()).listTools()
+
+ assertEquals(3, tools.size)
+ }
+
+ @Test
+ fun `auth and custom headers go on every request, and a refusal is AUTH`() = runTest {
+ fake.requiredAuth = "Bearer right"
+ val ok = client.session(endpoint(mapOf("Authorization" to "Bearer right", "X-Api-Key" to "k")))
+ ok.listTools()
+ assertTrue(fake.seen.all { it.auth == "Bearer right" && it.headers["X-Api-Key"] == "k" })
+
+ val e = failureOf { client.session(endpoint(mapOf("Authorization" to "Bearer wrong"))).initialize() }
+ assertEquals(McpFailure.AUTH, e.kind)
+ assertEquals(401, e.httpCode)
+ }
+
+ @Test
+ fun `tool output flattens content and keeps the error flag`() = runTest {
+ fake.callResult = """{"isError":true,"content":[{"type":"text","text":"no such page"},""" +
+ """{"type":"image","mimeType":"image/png","data":"AAAA"},""" +
+ """{"type":"resource","resource":{"uri":"file:///a","text":"body"}}]}"""
+
+ val out = client.session(endpoint()).callTool("create_page", buildJsonObject {})
+
+ assertTrue(out.isError)
+ assertEquals("no such page\n[image image/png not shown]\nbody", out.text)
+ }
+
+ @Test
+ fun `structured content stands in when there is no text`() = runTest {
+ fake.callResult = """{"content":[],"structuredContent":{"count":3}}"""
+
+ assertEquals("""{"count":3}""", client.session(endpoint()).callTool("search", buildJsonObject {}).text)
+ }
+
+ @Test
+ fun `a JSON-RPC error is RPC with the server's message`() = runTest {
+ fake.callError = "Unknown tool: nope"
+
+ val e = failureOf { client.session(endpoint()).callTool("nope", buildJsonObject {}) }
+
+ assertEquals(McpFailure.RPC, e.kind)
+ assertEquals("Unknown tool: nope", e.detail)
+ }
+
+ @Test
+ fun `a reply that stalls half-way is NETWORK, not a crash`() = runTest {
+ val stalled = MockWebServer().apply {
+ dispatcher = object : Dispatcher() {
+ override fun dispatch(request: RecordedRequest) = MockResponse()
+ .setHeader("Content-Type", "text/event-stream")
+ .setBody("data: {\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{}}\n\n")
+ .throttleBody(4, 5, TimeUnit.SECONDS)
+ }
+ start()
+ }
+ val impatient = McpHttpClient(OkHttpClient.Builder().readTimeout(300, TimeUnit.MILLISECONDS).build())
+ try {
+ val e = failureOf { impatient.session(McpEndpoint(stalled.url("/mcp").toString())).initialize() }
+ assertEquals(McpFailure.NETWORK, e.kind)
+ } finally {
+ stalled.shutdown()
+ }
+ }
+
+ @Test
+ fun `nothing at the URL is NOT_FOUND, an old SSE server is OLD_TRANSPORT`() = runTest {
+ val plain = MockWebServer().apply {
+ dispatcher = object : Dispatcher() {
+ override fun dispatch(request: RecordedRequest) = MockResponse().setResponseCode(404)
+ }
+ start()
+ }
+ val old = MockWebServer().apply {
+ dispatcher = object : Dispatcher() {
+ override fun dispatch(request: RecordedRequest) = if (request.method == "GET") {
+ MockResponse().setHeader("Content-Type", "text/event-stream")
+ .setBody("event: endpoint\ndata: /messages?session=1\n\n")
+ } else {
+ MockResponse().setResponseCode(405)
+ }
+ }
+ start()
+ }
+ try {
+ val notFound = failureOf { client.session(McpEndpoint(plain.url("/mcp").toString())).initialize() }
+ assertEquals(McpFailure.NOT_FOUND, notFound.kind)
+ val oldTransport = failureOf { client.session(McpEndpoint(old.url("/sse").toString())).initialize() }
+ assertEquals(McpFailure.OLD_TRANSPORT, oldTransport.kind)
+ } finally {
+ plain.shutdown()
+ old.shutdown()
+ }
+ }
+
+ @Test
+ fun `a server that is not MCP is NOT_MCP, and an unreachable one is NETWORK`() = runTest {
+ val html = MockWebServer().apply {
+ dispatcher = object : Dispatcher() {
+ override fun dispatch(request: RecordedRequest) =
+ MockResponse().setHeader("Content-Type", "text/html").setBody("<html>hello</html>")
+ }
+ start()
+ }
+ try {
+ assertEquals(
+ McpFailure.NOT_MCP,
+ failureOf { client.session(McpEndpoint(html.url("/").toString())).initialize() }.kind
+ )
+ } finally {
+ html.shutdown()
+ }
+ val closed = MockWebServer().apply { start() }
+ val url = closed.url("/mcp").toString()
+ closed.shutdown()
+ assertEquals(McpFailure.NETWORK, failureOf { client.session(McpEndpoint(url)).initialize() }.kind)
+ }
+}
diff --git a/app/src/test/java/com/gotcha/connectors/mcp/McpServersConnectorTest.kt b/app/src/test/java/com/gotcha/connectors/mcp/McpServersConnectorTest.kt
new file mode 100644
index 0000000..5bafcfc
--- /dev/null
+++ b/app/src/test/java/com/gotcha/connectors/mcp/McpServersConnectorTest.kt
@@ -0,0 +1,194 @@
+package com.gotcha.connectors.mcp
+
+import android.content.Context
+import androidx.test.core.app.ApplicationProvider
+import com.gotcha.connectors.ConnectorRegistry
+import com.gotcha.connectors.CredentialStore
+import com.gotcha.i18n.stringLookup
+import com.gotcha.tools.AgentMode
+import com.gotcha.tools.ToolRegistry
+import kotlinx.coroutines.test.runTest
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.put
+import okhttp3.mockwebserver.MockWebServer
+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 org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+
+private class MemoryStore : CredentialStore {
+ val map = mutableMapOf<String, String>()
+ override fun loadRaw(connectorId: String): String? = map[connectorId]
+ override fun saveRaw(connectorId: String, blob: String) {
+ map[connectorId] = blob
+ }
+
+ override fun clear(connectorId: String) {
+ map.remove(connectorId)
+ }
+}
+
+/** The MCP servers connector: storing servers and offering their tools (issue #130). */
+@RunWith(RobolectricTestRunner::class)
+class McpServersConnectorTest {
+
+ /** Messages are string resources; Robolectric reads the English ones. */
+ private val strings = ApplicationProvider.getApplicationContext<Context>().stringLookup()
+
+ private val server = MockWebServer()
+ private val fake = FakeMcpServer()
+ private val store = MemoryStore()
+ private lateinit var connector: McpServersConnector
+
+ @Before
+ fun setUp() {
+ ToolRegistry.clearAllDynamicTools()
+ server.dispatcher = fake
+ server.start()
+ connector = McpServersConnector(store)
+ }
+
+ @After
+ fun tearDown() {
+ server.shutdown()
+ ToolRegistry.clearAllDynamicTools()
+ }
+
+ private fun url() = server.url("/mcp").toString()
+
+ private suspend fun add(name: String = "Docs", token: String = ""): McpServerConfig {
+ val (saved, message) = connector.save(null, name, url(), token, emptyMap(), strings)
+ assertTrue(message, saved)
+ return connector.servers().last()
+ }
+
+ @Test
+ fun `saving a server stores it and offers its tools, read-only ones to Monitor too`() = runTest {
+ val (saved, message) = connector.save(null, "Docs", url(), "", emptyMap(), strings)
+
+ assertTrue(saved)
+ assertEquals("Connected to Docs: 3 tools.", message)
+ assertEquals(setOf("mcp_docs__search", "mcp_docs__create_page", "mcp_docs__delete_page"), connector.toolNames)
+ assertEquals(connector.toolNames, ToolRegistry.dynamicToolsByOwner["mcp"])
+ assertTrue(ToolRegistry.isAllowedForAgent("mcp_docs__search", AgentMode.MONITOR))
+ assertFalse(ToolRegistry.isAllowedForAgent("mcp_docs__create_page", AgentMode.MONITOR))
+ assertTrue(ToolRegistry.isAllowedForAgent("mcp_docs__create_page", AgentMode.OPERATOR))
+ assertTrue(
+ ToolRegistry.definition("mcp_docs__search")!!.function.description.startsWith("[MCP server \"Docs\"]")
+ )
+ assertTrue(store.map.containsKey("mcp"))
+ }
+
+ @Test
+ fun `a server that cannot be reached is not saved, and says why`() = runTest {
+ fake.requiredAuth = "Bearer right"
+
+ val (saved, message) = connector.save(null, "Docs", url(), "wrong", emptyMap(), strings)
+
+ assertFalse(saved)
+ assertEquals("The server refused the token or headers (HTTP 401). Check them and try again.", message)
+ assertTrue(connector.servers().isEmpty())
+ assertTrue(ToolRegistry.dynamicTools.isEmpty())
+ }
+
+ @Test
+ fun `invalid input is refused before anything is sent`() = runTest {
+ assertEquals(
+ "Enter a full URL that starts with https:// (or http:// on your local network).",
+ connector.save(null, "Docs", "not a url", "", emptyMap(), strings).second
+ )
+ assertEquals("Enter a name for the server.", connector.save(null, " ", url(), "", emptyMap(), strings).second)
+ assertEquals(0, server.requestCount)
+ }
+
+ @Test
+ fun `a tool call reaches its server under the server's own name`() = runTest {
+ add()
+
+ val result = connector.callTool("mcp_docs__search", buildJsonObject { put("q", "x") })
+
+ assertTrue(result.success)
+ assertEquals("found 3 pages", result.message)
+ assertEquals("tools/call", fake.seen.last().method)
+ }
+
+ @Test
+ fun `switching a server off withholds its tools, and on brings them back`() = runTest {
+ val docs = add()
+
+ connector.setServerEnabled(docs.id, false)
+ assertTrue(connector.toolNames.isEmpty())
+ assertNull(ToolRegistry.dynamicToolsByOwner["mcp"])
+ assertFalse(connector.callTool("mcp_docs__search", buildJsonObject {}).success)
+
+ connector.setServerEnabled(docs.id, true)
+ assertEquals(3, connector.toolNames.size)
+ }
+
+ @Test
+ fun `removing a server removes its tools and its stored entry`() = runTest {
+ val docs = add()
+
+ connector.remove(docs.id)
+
+ assertTrue(connector.toolNames.isEmpty())
+ assertTrue(ToolRegistry.dynamicTools.isEmpty())
+ assertFalse(store.map.containsKey("mcp"))
+ }
+
+ @Test
+ fun `two servers with the same tool names get distinct prefixes`() = runTest {
+ add("Docs")
+ add("Docs")
+
+ assertEquals(6, connector.toolNames.size)
+ assertTrue("mcp_docs2__search" in connector.toolNames)
+ }
+
+ @Test
+ fun `tools come back from the store after a restart, before any network call`() = runTest {
+ add()
+ ToolRegistry.clearAllDynamicTools()
+ val requests = server.requestCount
+
+ val restarted = McpServersConnector(store)
+
+ assertEquals(3, restarted.toolNames.size)
+ assertEquals(restarted.toolNames, ToolRegistry.dynamicTools)
+ assertEquals(requests, server.requestCount)
+ }
+
+ @Test
+ fun `a failed refresh keeps the tools and shows the error`() = runTest {
+ val docs = add()
+ server.shutdown()
+
+ val message = connector.refresh(docs.id, strings)
+
+ assertTrue(message, message.startsWith("Couldn't reach the server"))
+ assertEquals(message, connector.server(docs.id)!!.lastError)
+ assertEquals(3, connector.toolNames.size)
+ }
+
+ @Test
+ fun `the connector switch hides every server's tools`() = runTest {
+ add()
+
+ assertTrue("mcp_docs__search" in ConnectorRegistry.hiddenToolNamesFor(emptySet()))
+ assertFalse("mcp_docs__search" in ConnectorRegistry.hiddenToolNamesFor(setOf("mcp")))
+ }
+
+ @Test
+ fun `status line counts servers that are on and their tools`() = runTest {
+ val docs = add()
+ add("Wiki")
+ connector.setServerEnabled(docs.id, false)
+
+ assertEquals("1 of 2 servers on · 3 tools", connector.statusLine(strings))
+ }
+}
diff --git a/app/src/test/java/com/gotcha/connectors/mcp/McpServersTest.kt b/app/src/test/java/com/gotcha/connectors/mcp/McpServersTest.kt
new file mode 100644
index 0000000..7459e39
--- /dev/null
+++ b/app/src/test/java/com/gotcha/connectors/mcp/McpServersTest.kt
@@ -0,0 +1,114 @@
+package com.gotcha.connectors.mcp
+
+import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.jsonObject
+import kotlinx.serialization.json.put
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** Naming, URL rules and schema clean-up for user-added MCP servers (issue #130). */
+class McpServersTest {
+
+ private val validName = Regex("^[a-zA-Z0-9_-]{1,64}$")
+
+ private fun tool(name: String) = McpTool(name = name, inputSchema = buildJsonObject { put("type", "object") })
+
+ private fun server(id: String, name: String) = McpServerConfig(id = id, name = name, url = "https://x")
+
+ @Test
+ fun `tool names are prefixed by the server and fit the chat APIs`() {
+ val names = McpToolNames.exposedNames("docs", listOf(tool("search"), tool("pages.get"), tool("x".repeat(80))))
+
+ assertEquals(listOf("search", "pages.get", "x".repeat(80)), names.values.toList())
+ assertTrue("mcp_docs__search" in names)
+ assertTrue("mcp_docs__pages_get" in names)
+ names.keys.forEach { assertTrue(it, validName.matches(it)) }
+ }
+
+ @Test
+ fun `names that clash after cleaning stay distinct`() {
+ val names = McpToolNames.exposedNames("docs", listOf(tool("a.b"), tool("a_b"), tool("a b")))
+
+ assertEquals(3, names.size)
+ assertEquals(listOf("a.b", "a_b", "a b"), names.values.toList())
+ names.keys.forEach { assertTrue(it, validName.matches(it)) }
+ }
+
+ @Test
+ fun `server slugs are short, clean and unique`() {
+ assertEquals("my_docs", McpToolNames.slug("My Docs!"))
+ assertEquals("server", McpToolNames.slug("日本"))
+ val slugs = McpToolNames.slugs(listOf(server("1", "Docs"), server("2", "docs"), server("3", "DOCS")))
+ assertEquals(listOf("docs", "docs2", "docs3"), listOf("1", "2", "3").map { slugs.getValue(it) })
+ }
+
+ @Test
+ fun `http is fine locally, or with nothing secret, but not with a token over the internet`() {
+ assertNull(validateMcpServer("https://mcp.example.com/mcp", "t", emptyMap()))
+ assertNull(validateMcpServer("http://192.168.1.20:8080/mcp", "t", emptyMap()))
+ assertNull(validateMcpServer("http://homeassistant.local:8123/mcp", "t", emptyMap()))
+ assertNull(validateMcpServer("http://mcp.example.com/mcp", "", emptyMap()))
+ assertEquals(
+ McpConfigProblem.CLEARTEXT_WITH_SECRET,
+ validateMcpServer("http://mcp.example.com/mcp", "t", emptyMap())
+ )
+ assertEquals(
+ McpConfigProblem.CLEARTEXT_WITH_SECRET,
+ validateMcpServer("http://8.8.8.8/mcp", "", mapOf("X-Api-Key" to "k"))
+ )
+ assertEquals(McpConfigProblem.BAD_URL, validateMcpServer("mcp.example.com", "", emptyMap()))
+ assertEquals(McpConfigProblem.BAD_URL, validateMcpServer("ftp://mcp.example.com", "", emptyMap()))
+ assertEquals(McpConfigProblem.BAD_HEADER, validateMcpServer("https://x.com", "", mapOf("Bad Name" to "v")))
+ assertEquals(McpConfigProblem.BAD_TOKEN, validateMcpServer("https://x.com", "tökén", emptyMap()))
+ assertEquals(McpConfigProblem.BAD_TOKEN, validateMcpServer("https://x.com", "", mapOf("X-A" to "a\nb")))
+ }
+
+ @Test
+ fun `local hosts are recognised without resolving names`() {
+ listOf(
+ "localhost", "10.0.0.2", "172.20.1.1", "192.168.0.9", "127.0.0.1",
+ "100.101.102.103", "box.lan", "[fd12::1]", "[::1]", "fe80::1"
+ ).forEach { assertTrue(it, isLocalHost(it)) }
+ listOf("8.8.8.8", "172.32.0.1", "100.128.0.1", "example.com", "local.example.com", "[2001:db8::1]")
+ .forEach { assertFalse(it, isLocalHost(it)) }
+ }
+
+ @Test
+ fun `header lines parse and format back`() {
+ val parsed = parseHeaderLines("X-Api-Key: abc\n\n X-Team : core ")
+ assertEquals(mapOf("X-Api-Key" to "abc", "X-Team" to "core"), parsed)
+ assertEquals("X-Api-Key: abc\nX-Team: core", formatHeaderLines(parsed!!))
+ assertNull(parseHeaderLines("no colon here"))
+ assertEquals(emptyMap<String, String>(), parseHeaderLines(" "))
+ }
+
+ @Test
+ fun `schemas become object schemas with properties, and non-objects are refused`() {
+ val bare = normalizedInputSchema(buildJsonObject {})!!
+ assertEquals("\"object\"", bare["type"].toString())
+ assertTrue("properties" in bare)
+ val full = Json.parseToJsonElement(
+ """{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}"""
+ ).jsonObject
+ assertEquals(full, normalizedInputSchema(full))
+ assertTrue("properties" in normalizedInputSchema(buildJsonObject { put("type", "object") })!!)
+ assertNull(normalizedInputSchema(buildJsonObject { put("type", "string") }))
+ }
+
+ @Test
+ fun `the endpoint carries the bearer token beside the custom headers`() {
+ val config = McpServerConfig(
+ id = "1",
+ name = "n",
+ url = "https://x",
+ token = " t ",
+ headers = mapOf("X-A" to "b")
+ )
+ assertEquals(mapOf("X-A" to "b", "Authorization" to "Bearer t"), config.endpoint().headers)
+ assertEquals(emptyMap<String, String>(), config.copy(token = "", headers = emptyMap()).endpoint().headers)
+ }
+}
diff --git a/docs/mcp-servers.md b/docs/mcp-servers.md
new file mode 100644
index 0000000..df0074c
--- /dev/null
+++ b/docs/mcp-servers.md
@@ -0,0 +1,71 @@
+# MCP servers
+
+Gotcha can use the tools of any [Model Context Protocol](https://modelcontextprotocol.io)
+server you add, as long as the server speaks the **Streamable HTTP** transport. You add a
+server with its URL and, if it needs one, a token; Gotcha lists the server's tools and the
+assistant can call them while that server is switched on.
+
+## Add a server
+
+**Drawer menu → Connectors → MCP servers → Add server**, then fill in:
+
+| Field | What to put |
+|---|---|
+| Name | Anything. It labels the server's tools for the assistant (`mcp_<name>__<tool>`). |
+| Server URL | The server's Streamable HTTP endpoint, often ending in `/mcp`. |
+| Bearer token | Optional. Sent as `Authorization: Bearer <token>`. |
+| Extra headers | Optional, one per line as `Name: value`, for servers that want an API-key header instead. |
+
+**Test connection** contacts the server and shows its name and how many tools it offers, or
+why it failed. **Save** tests again and stores the server only if it answers. The token and
+headers are kept in Gotcha's encrypted connector store on the phone.
+
+Plain `http://` works for servers on your own network: `localhost`, `.local` and `.lan`
+names, and private, link-local and Tailscale (100.64.0.0/10) addresses. A token or header
+sent over `http://` to anywhere else could be read on the way, so Gotcha asks for `https://`
+there.
+
+## What the assistant gets
+
+- Each tool appears as `mcp_<server>__<tool>`, with its description prefixed by the server's
+ name. Two servers with the same tool names do not clash.
+- Tools the server marks `readOnlyHint` can be used in **Monitor**. Every other tool is
+ **Operator** only, because MCP gives no other way to tell what a tool does.
+- At most 64 tools per server are offered, so one large server cannot fill the prompt.
+- Images and audio in a tool's result are named, not passed on; text, embedded text
+ resources and structured content are.
+
+**Trust:** a server's tool descriptions and results reach the assistant as they are, and can
+steer what it does next. Add only servers you trust, and prefer read-only tools in Monitor
+when you are unsure.
+
+## Switching off and removing
+
+Each server has its own switch: off, its tools are withheld from the assistant but the server
+stays saved. The **MCP servers** switch at the top turns all of them off at once.
+**Remove** (tap twice) deletes the server and its stored token.
+
+**Refresh tools** asks the server for its tool list again. The Connectors page's auto-sync
+and **Refresh all** do the same for every server that is on. A failed refresh keeps the last
+known tools and shows the error under the server.
+
+## Not supported yet
+
+- Servers started as local processes (stdio). Android can't run them for Gotcha.
+- The older HTTP+SSE transport (MCP 2024-11-05). Gotcha recognises it and says so; use the
+ server's Streamable HTTP endpoint if it has one.
+- OAuth sign-in. Use a token or header the server issues instead.
+- Resources, prompts and sampling: only tools are used.
+
+## Errors you may see
+
+| Message | What to check |
+|---|---|
+| The server refused the token or headers (HTTP 401/403) | The token, or the header name and value. |
+| Nothing answered at this URL (HTTP 404) | The path: many servers serve MCP at `/mcp`. |
+| This server uses the older HTTP+SSE transport | Look for a Streamable HTTP endpoint in the server's docs. |
+| The server answered, but not as an MCP server | The URL points at a web page or another API. |
+| Couldn't reach the server | The address, the network, and whether the server is running. |
+
+Home Assistant has its own connector card, which needs no URL path and adds Home Assistant's
+own hints; it uses the same tool gating.