Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ UI 修改流程见 [.agents/skills/mbrain-style/SKILL.md](.agents/skills/mbrain-
- 工具列表只显示名称与来源;完整说明进入工具详情。搜索同时匹配中文名称、原始名称和描述。
- Token 默认隐藏,复制有反馈。运行记录在独立页,最多 40 条。
- 各主页面和详情保存滚动位置;编辑草稿与导航在 Activity 重建时恢复。
- 设置中的内网穿透独立管理多条隧道和证书。详情区分服务器连接、隧道注册和本地端口状态;代理类型与客户端插件分别选择。证书显示有效期,导入使用系统文件选择器。
- 设置中的内网穿透只配置一台服务器,点击服务器行直接进入完整编辑页,不展示服务器列表、单独的编辑按钮或顶部说明。服务器仅填写名称、地址、端口和 Token;隧道共用服务器,只配置本地目标、TCP 映射端口与可选 HTTP 公网地址。没有 HTTPS、TLS、插件和证书入口。

## 实现入口

Expand All @@ -69,3 +69,5 @@ UI 修改流程见 [.agents/skills/mbrain-style/SKILL.md](.agents/skills/mbrain-
- OverviewScreens.kt:首页、能力、设置、记录。
- ConnectionScreens.kt:MCP 列表、详情、完整编辑页。
- DetailScreens.kt:工具、凭据。

- 隧道详情默认只显示启用状态、已填写的访问地址和编辑入口;编辑入口合并本地目标与映射端口摘要。连接诊断、访问凭据、重连和删除放入“更多”,诊断与运行记录默认收起;错误直接显示。
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ MBrain 是运行在 Android 上的 MCP 网关。它把手机自身的能力和
| **执行命令与操作文件** | 通过 Root 或 Shizuku 执行命令,浏览、读取、写入、复制和移动文件 |
| **接入其他 MCP 服务** | 添加手机本机的 HTTP MCP 服务,或由 MBrain 启动和管理 stdio MCP 进程 |
| **统一管理与连接** | 一个 MCP 地址提供工具目录,支持搜索工具、查看说明、复制连接信息和查看近期运行记录 |
| **内网穿透** | 内置 frpc,多条 TCP / HTTPS 隧道,可公开 MBrain 或手机其他服务,支持证书和 TLS 插件 |
| **内网穿透** | 内置 frpc,统一配置一台服务器,多条基础 TCP 隧道转发 MBrain 或手机其他服务 |

- **按需启用**:Root 和 Shizuku 各用一个开关,打开时自动检查并申请权限。
- **随时停止**:首页右下角一键启停,也可从前台通知停止网关。
Expand Down Expand Up @@ -105,7 +105,7 @@ adb forward tcp:8765 tcp:8765

默认端口被占用时,网关会自动使用空闲端口。请以“连接地址与凭据”中的实际地址及“使用说明”中的 ADB 命令为准。Token 加密保存在设备上,重启后保持不变;可在凭据页重置。

**远程客户端**可在“设置 → 远程访问”添加自建 frps 隧道。支持多个隧道同时启用,各自启停和重试,网关停止时全部断开。公网 HTTPS 入口需在服务器配置,具体见[远程访问](docs/remote-access.md)。
**远程客户端**可在“设置 → 内网穿透”配置一台自建 frps,再添加 TCP 隧道。每条隧道独立启停与重试;MCP 隧道跟随网关,自定义服务隧道独立运行。具体见[内网穿透指南](docs/remote-access.md)。

连接后可以先让 Agent 执行一个简单的只读请求:

Expand All @@ -115,7 +115,7 @@ adb forward tcp:8765 tcp:8765

## 接入 MCP 服务

需要从公网连接时,可进入 **设置 → 内网穿透**,配置自己的 frps。支持 TCP、HTTPS 透传、`https2http` 和 `tls2raw`,自定义服务隧道独立于 MCP 网关运行。证书导入、服务器示例与运行规则见[内网穿透指南](docs/remote-access.md)。
需要从公网连接时,可进入 **设置 → 内网穿透 → 配置服务器** 填写 frps 地址、端口和 Token。当前仅支持基础 TCP 转发,所有隧道共用一台服务器。配置示例与运行规则见[内网穿透指南](docs/remote-access.md)。

进入 **MCP → 添加服务**,选择连接方式:

Expand All @@ -140,7 +140,7 @@ HTTP 服务目前只支持回环地址。托管进程所需的程序和运行环
<details>
<summary><strong>为什么客户端连接不上?</strong></summary>

先确认首页显示“运行中”,并使用凭据页中的 Token。电脑连接时还需确认实际端口的 ADB 转发成功。网关仅监听手机回环地址;远程访问通过已配置的 frp 隧道和服务器 HTTPS 入口连接。
先确认首页显示“运行中”,并使用凭据页中的 Token。电脑连接时还需确认实际端口的 ADB 转发成功。网关仅监听手机回环地址;远程访问通过已配置的 TCP 隧道连接。

</details>

Expand Down
4 changes: 2 additions & 2 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ android {
applicationId = "com.powercess.mbrain"
minSdk = libs.versions.minSdk.get().toInt()
targetSdk = libs.versions.targetSdk.get().toInt()
versionCode = 3
versionName = "0.1.0"
versionCode = 4
versionName = "0.2.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
buildFeatures { compose = true; buildConfig = true }
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.powercess.mbrain.remote

import android.content.Intent
import android.util.Base64
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.powercess.mbrain.gateway.GatewayRuntime
Expand All @@ -13,84 +12,65 @@ import org.junit.runner.RunWith
import java.net.InetAddress
import java.net.ServerSocket
import java.net.Socket
import java.security.KeyFactory
import java.security.KeyStore
import java.security.spec.PKCS8EncodedKeySpec
import javax.net.ssl.*
import kotlin.concurrent.thread

/** Run with scripts/smoke-frpc.py: a real frps is reached through adb reverse. */
@RunWith(AndroidJUnit4::class)
class FrpcDeviceTest {
@Test fun realFrpcSupportsAllModesAndIndependentLifecycles() {
@Test fun realTcpFrpcSupportsSharedServerAndIndependentLifecycles() {
val instrumentation = InstrumentationRegistry.getInstrumentation()
val args = InstrumentationRegistry.getArguments()
assumeTrue("Use scripts/smoke-frpc.py to provide the local frps fixture", args.containsKey("certificate"))
assumeTrue("Use scripts/smoke-frpc.py to provide the local frps fixture", args.containsKey("controlPort"))
val context = instrumentation.targetContext
val cert = TunnelCertificate(name = "integration CA", pem = String(Base64.decode(args.getString("certificate"), Base64.DEFAULT)),
keyPem = String(Base64.decode(args.getString("privateKey"), Base64.DEFAULT)))
cert.validate()
val serviceCert = cert.copy(id = newId(), name = "integration service")
val tls = tlsContext(cert)
val backend = ServerSocket(0, 16, InetAddress.getByName("127.0.0.1"))
val secureBackend = tls.serverSocketFactory.createServerSocket(0, 16, InetAddress.getByName("127.0.0.1"))
serve(backend); serve(secureBackend)
val controlPort = args.getString("controlPort")!!.toInt()
serve(backend)
val tcpPort = args.getString("tcpPort")!!.toInt()
val rawPort = args.getString("rawPort")!!.toInt()
val httpsPort = args.getString("httpsPort")!!.toInt()
val base = TunnelConfig(name = "integration tcp", server = "127.0.0.1", serverPort = controlPort,
token = args.getString("frpToken")!!, target = TunnelTarget.CUSTOM, localPort = backend.localPort,
remotePort = tcpPort, tlsCaId = cert.id, tlsClientCertificateId = cert.id, tlsServerName = "phone.example.test")
val raw = base.copy(id = newId(), name = "integration tls2raw", remotePort = rawPort, plugin = TunnelPlugin.TLS2RAW, certificateId = serviceCert.id)
val https = base.copy(id = newId(), name = "integration MCP", target = TunnelTarget.MCP, type = ProxyType.HTTPS,
domains = listOf("phone.example.test"), plugin = TunnelPlugin.HTTPS2HTTP, certificateId = serviceCert.id)
val passthrough = base.copy(id = newId(), name = "integration passthrough", type = ProxyType.HTTPS,
domains = listOf("passthrough.example.test"), localPort = secureBackend.localPort)
val tunnels = listOf(base, raw, https, passthrough)
val mcpPort = args.getString("mcpPort")!!.toInt()
val server = TunnelServer(name = "integration", host = "127.0.0.1",
port = args.getString("controlPort")!!.toInt(), token = args.getString("frpToken")!!)
val base = TunnelConfig(name = "integration tcp", serverId = server.id,
target = TunnelTarget.CUSTOM, localPort = backend.localPort, remotePort = tcpPort)
val mcp = base.copy(id = newId(), name = "integration MCP", target = TunnelTarget.MCP, remotePort = mcpPort)
val tunnels = listOf(base, mcp)
fun main(block: () -> Unit) = instrumentation.runOnMainSync(block)
try {
main {
GatewayRuntime.initialize(context)
RemoteRuntime.initialize(context)
RemoteRuntime.saveCertificate(cert); RemoteRuntime.saveCertificate(serviceCert)
RemoteRuntime.saveServer(server)
tunnels.forEach(RemoteRuntime::saveTunnel)
tunnels.forEach { RemoteRuntime.enableTunnel(it.id, true) }
}
await { RemoteRuntime.status.value[https.id]?.phase == TunnelPhase.WAITING }
await { listOf(base, raw, passthrough).all { RemoteRuntime.status.value[it.id]?.phase == TunnelPhase.CONNECTED } }
await { RemoteRuntime.status.value[mcp.id]?.phase == TunnelPhase.WAITING }
await { RemoteRuntime.status.value[base.id]?.phase == TunnelPhase.CONNECTED }
assertTrue(request(tcpPort).contains("frpc-device-ok"))
assertTrue(request(rawPort, tls, "phone.example.test").contains("frpc-device-ok"))
assertTrue(request(httpsPort, tls, "passthrough.example.test").contains("frpc-device-ok"))
main { context.startForegroundService(Intent(context, MBrainService::class.java)) }
await { GatewayRuntime.status.value.running && RemoteRuntime.status.value[https.id]?.phase == TunnelPhase.CONNECTED }
val unauthenticated = request(httpsPort, tls, "phone.example.test", "/mcp", "invalid-test-token")
assertTrue("MCP authentication survives HTTPS forwarding", unauthenticated.contains("401"))
val initialized = request(httpsPort, tls, "phone.example.test", "/mcp", GatewayRuntime.status.value.token)
assertTrue("MCP initialize works through https2http", initialized.contains("200") && initialized.contains("protocolVersion"))
await { GatewayRuntime.status.value.running && RemoteRuntime.status.value[mcp.id]?.phase == TunnelPhase.CONNECTED }
assertTrue(request(mcpPort, "/mcp", "invalid-test-token").contains("401"))
val initialized = request(mcpPort, "/mcp", GatewayRuntime.status.value.token)
assertTrue(initialized.contains("200") && initialized.contains("protocolVersion"))
main { context.stopService(Intent(context, MBrainService::class.java)) }
await { RemoteRuntime.status.value[https.id]?.phase == TunnelPhase.WAITING }
await { RemoteRuntime.status.value[mcp.id]?.phase == TunnelPhase.WAITING }
assertTrue(request(tcpPort).contains("frpc-device-ok"))
assertTrue(request(rawPort, tls, "phone.example.test").contains("frpc-device-ok"))
assertStreaming(tcpPort)
main {
RemoteRuntime.enableTunnel(https.id, false)
RemoteRuntime.saveTunnel(https.copy(target = TunnelTarget.CUSTOM, localPort = backend.localPort))
RemoteRuntime.enableTunnel(https.id, true)
RemoteRuntime.enableTunnel(mcp.id, false)
RemoteRuntime.saveTunnel(mcp.copy(target = TunnelTarget.CUSTOM, localPort = backend.localPort))
RemoteRuntime.enableTunnel(mcp.id, true)
}
await { RemoteRuntime.status.value[https.id]?.phase == TunnelPhase.CONNECTED }
assertStreaming(tls, httpsPort)
await { RemoteRuntime.status.value[mcp.id]?.phase == TunnelPhase.CONNECTED }
main { RemoteRuntime.enableTunnel(base.id, false) }
assertTrue(request(rawPort, tls, "phone.example.test").contains("frpc-device-ok"))
assertTrue(request(mcpPort).contains("frpc-device-ok"))
main { RemoteRuntime.stopAll() }
await { RemoteRuntime.status.value.values.all { it.phase == TunnelPhase.OFF } }
await { java.io.File(context.noBackupFilesDir, "frpc-runtime").listFiles().orEmpty().isEmpty() }
} finally {
main {
RemoteRuntime.stopAll(); context.stopService(Intent(context, MBrainService::class.java))
tunnels.forEach { RemoteRuntime.removeTunnel(it.id) }
RemoteRuntime.removeCertificate(serviceCert.id); RemoteRuntime.removeCertificate(cert.id)
RemoteRuntime.removeServer(server.id)
}
backend.close(); secureBackend.close()
backend.close()
}
}

Expand All @@ -112,14 +92,9 @@ class FrpcDeviceTest {
}
}

private fun assertStreaming(tls: SSLContext, port: Int) {
val tcp = Socket("127.0.0.1", port)
(tls.socketFactory.createSocket(tcp, "phone.example.test", port, true) as SSLSocket).use { socket ->
private fun assertStreaming(port: Int) {
Socket("127.0.0.1", port).use { socket ->
socket.soTimeout = 2500
socket.sslParameters = socket.sslParameters.apply {
serverNames = listOf(SNIHostName("phone.example.test")); endpointIdentificationAlgorithm = "HTTPS"
}
socket.startHandshake()
socket.outputStream.write("GET /events HTTP/1.1\r\nHost: phone.example.test\r\nAccept: text/event-stream\r\nConnection: close\r\n\r\n".toByteArray())
val reader = socket.inputStream.bufferedReader()
var line = reader.readLine()
Expand All @@ -129,32 +104,16 @@ class FrpcDeviceTest {
}
}

private fun request(port: Int, tls: SSLContext? = null, hostname: String = "localhost", path: String = "/", token: String? = null): String {
val tcp = Socket("127.0.0.1", port).apply { soTimeout = 10000 }
val socket = if (tls == null) tcp else (tls.socketFactory.createSocket(tcp, hostname, port, true) as SSLSocket).apply {
sslParameters = sslParameters.apply { serverNames = listOf(SNIHostName(hostname)); endpointIdentificationAlgorithm = "HTTPS" }
startHandshake()
}
return socket.use {
private fun request(port: Int, path: String = "/", token: String? = null): String {
return Socket("127.0.0.1", port).apply { soTimeout = 10000 }.use {
val body = "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2025-03-26\",\"capabilities\":{},\"clientInfo\":{\"name\":\"frpc-test\",\"version\":\"1\"}}}"
val headers = if (token == null) "GET $path HTTP/1.1\r\n" else
"POST $path HTTP/1.1\r\nAuthorization: Bearer $token\r\nContent-Type: application/json\r\nAccept: application/json, text/event-stream\r\nContent-Length: ${body.toByteArray().size}\r\n"
it.outputStream.write((headers + "Host: $hostname\r\nConnection: close\r\n\r\n" + if (token == null) "" else body).toByteArray())
it.outputStream.write((headers + "Host: localhost\r\nConnection: close\r\n\r\n" + if (token == null) "" else body).toByteArray())
it.inputStream.bufferedReader().readText()
}
}

private fun tlsContext(cert: TunnelCertificate): SSLContext {
val bytes = Base64.decode(cert.keyPem.lines().filterNot { it.startsWith("-----") }.joinToString(""), Base64.DEFAULT)
val key = KeyFactory.getInstance("RSA").generatePrivate(PKCS8EncodedKeySpec(bytes))
val store = KeyStore.getInstance(KeyStore.getDefaultType()).apply {
load(null); setKeyEntry("test", key, CharArray(0), cert.chain().toTypedArray()); setCertificateEntry("ca", cert.chain().first())
}
val km = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()).apply { init(store, CharArray(0)) }
val tm = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()).apply { init(store) }
return SSLContext.getInstance("TLS").apply { init(km.keyManagers, tm.trustManagers, null) }
}

private fun await(check: () -> Boolean) {
val deadline = System.nanoTime() + 30_000_000_000
while (!check() && System.nanoTime() < deadline) Thread.sleep(100)
Expand Down
Loading
Loading