Mobile MCP: let AI agents drive your iOS and Android apps. MCP server for simulators, emulators and real devices. Works with Claude Code, Codex, Cursor and any MCP client.
TypeScript agentandroidandroid-automationappium-alternativeclaude-codecodexcursoremulatoriosios-automationmcpmcp-servermobilemobile-automationmobile-testingreal-devicesimulatorskills
feat: serve Streamable HTTP on --listen /mcp
Gil Megidish5c4d02b201f3
diff --git a/README.ja.md b/README.ja.mdindex f5d628e..b6880d9 100644--- a/README.ja.md+++ b/README.ja.md@@ -387,9 +387,9 @@ npx @mobilenext/mobile-mcp@latestlog in to mobile next cloud and then show me which remote devices are available to me```-### SSE サーバーモード+### Streamable HTTP サーバーモード-Mobile MCP はデフォルトで stdio 上で動作します。代わりに SSE サーバーを起動するには、`--listen` フラグを使用します:+Mobile MCP はデフォルトで stdio 上で動作します。代わりに [Streamable HTTP](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#streamable-http) サーバーを起動するには、`--listen` フラグを使用します:```bashnpx @mobilenext/mobile-mcp@latest --listen 3000@@ -401,17 +401,19 @@ npx @mobilenext/mobile-mcp@latest --listen 3000npx @mobilenext/mobile-mcp@latest --listen 0.0.0.0:3000```-その後、MCP クライアントが `http://<host>:3000/mcp` に接続するよう設定します。+その後、MCP クライアントが `http://<host>:3000/mcp`(TLS 配下なら `https://…/mcp`)に接続するよう設定します。エンドポイントは Streamable HTTP(`/mcp` への `POST`/`GET`/`DELETE`)を受け付けます。リモートモードは **ステートレス** です(セッション親和性不要)。++> **移行メモ:** 以前の `--listen` は非推奨の HTTP+SSE を `/mcp` で提供していました。クライアントは `http(s)://host:port/mcp` に対して Streamable HTTP を使う必要があります。 [#98](https://github.com/mobile-next/mobile-mcp/issues/98)#### 認可-SSE サーバーで Bearer トークンによる認可を要求するには、環境変数 `MOBILEMCP_AUTH` を設定します:+HTTP サーバーで Bearer トークンによる認可を要求するには、環境変数 `MOBILEMCP_AUTH` を設定します:```bashMOBILEMCP_AUTH=my-secret-token npx @mobilenext/mobile-mcp@latest --listen 3000```-設定すると、すべてのリクエストにヘッダー `Authorization: Bearer my-secret-token` を含める必要があります。+設定すると、すべてのリクエストにヘッダー `Authorization: Bearer my-secret-token` を含める必要があります。未設定の場合は認証なしで受け付け、警告を出力します。### 🛠️ 使い方@@ -484,7 +486,7 @@ Gmail to contacts "[email protected]".| 変数 | 説明 | 例 ||---|---|---|-| `MOBILEMCP_AUTH` | SSE サーバーで Bearer トークンを必須にします。設定すると、すべてのリクエストが `Authorization: Bearer <token>` を送信する必要があります。 | `MOBILEMCP_AUTH=my-secret-token` |+| `MOBILEMCP_AUTH` | Streamable HTTP サーバー(`--listen`)で Bearer トークンを必須にします。設定すると、すべてのリクエストが `Authorization: Bearer <token>` を送信する必要があります。 | `MOBILEMCP_AUTH=my-secret-token` || `MOBILEMCP_DISABLE_TELEMETRY` | 匿名の利用テレメトリを無効にします。 | `MOBILEMCP_DISABLE_TELEMETRY=1` || `MOBILEMCP_ALLOW_UNSAFE_URLS` | `mobile_open_url` が標準外の URL スキームを開くことを許可します(デフォルトではブロックされます)。 | `MOBILEMCP_ALLOW_UNSAFE_URLS=1` || `MOBILEMCP_LEGACY_ROBOT` | Android デバイスおよび iOS 実機に対して、従来のプラットフォーム固有のロボットを使用します。iOS シミュレーターは引き続き `mobilecli` を使用します。 | `MOBILEMCP_LEGACY_ROBOT=1` |diff --git a/README.md b/README.mdindex beec531..a0f0117 100644--- a/README.md+++ b/README.md@@ -388,9 +388,9 @@ In your Agent, prompt:log in to mobile next cloud and then show me which remote devices are available to me```-### SSE Server Mode+### Streamable HTTP Server Mode-By default, Mobile MCP runs over stdio. To start an SSE server instead, use the `--listen` flag:+By default, Mobile MCP runs over stdio. To start a [Streamable HTTP](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#streamable-http) server instead, use the `--listen` flag:```bashnpx @mobilenext/mobile-mcp@latest --listen 3000@@ -402,17 +402,21 @@ This binds to `localhost:3000`. To bind to a specific interface:npx @mobilenext/mobile-mcp@latest --listen 0.0.0.0:3000```-Then configure your MCP client to connect to `http://<host>:3000/mcp`.+Then configure your MCP client to connect to `http://<host>:3000/mcp` (or `https://…/mcp` behind TLS). The endpoint accepts Streamable HTTP (`POST`/`GET`/`DELETE` on `/mcp`); remote mode is **stateless** (no session affinity required), which works well with Smithery and other horizontal hosts.++> **Migration note:** `--listen` previously served the deprecated HTTP+SSE transport on `/mcp`. Clients must use Streamable HTTP against `http(s)://host:port/mcp`. The old pure-SSE flow on `/mcp` is no longer available. See [#98](https://github.com/mobile-next/mobile-mcp/issues/98).++When binding to localhost, Host-header DNS rebinding protection is enabled automatically.#### Authorization-To require Bearer token authorization on the SSE server, set the `MOBILEMCP_AUTH` environment variable:+To require Bearer token authorization on the HTTP server, set the `MOBILEMCP_AUTH` environment variable:```bashMOBILEMCP_AUTH=my-secret-token npx @mobilenext/mobile-mcp@latest --listen 3000```-When set, all requests must include the header `Authorization: Bearer my-secret-token`.+When set, all requests must include the header `Authorization: Bearer my-secret-token`. When unset, the server accepts unauthenticated connections and logs a warning.### 🛠️ How to Use@@ -485,7 +489,7 @@ Gmail to contacts "[email protected]".| Variable | Description | Example ||---|---|---|-| `MOBILEMCP_AUTH` | Require a Bearer token on the SSE server — every request must then send `Authorization: Bearer <token>`. | `MOBILEMCP_AUTH=my-secret-token` |+| `MOBILEMCP_AUTH` | Require a Bearer token on the Streamable HTTP server (`--listen`) — every request must then send `Authorization: Bearer <token>`. | `MOBILEMCP_AUTH=my-secret-token` || `MOBILEMCP_DISABLE_TELEMETRY` | Disable anonymous usage telemetry. | `MOBILEMCP_DISABLE_TELEMETRY=1` || `MOBILEMCP_ALLOW_UNSAFE_URLS` | Allow `mobile_open_url` to open non-standard URL schemes (blocked by default). | `MOBILEMCP_ALLOW_UNSAFE_URLS=1` || `MOBILEMCP_LEGACY_ROBOT` | Use the legacy platform-specific robots for Android devices and physical iOS devices. iOS simulators continue to use `mobilecli`. | `MOBILEMCP_LEGACY_ROBOT=1` |diff --git a/README.zh-CN.md b/README.zh-CN.mdindex 13be08b..dc24d71 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -387,9 +387,9 @@ npx @mobilenext/mobile-mcp@latestlog in to mobile next cloud and then show me which remote devices are available to me```-### SSE 服务器模式+### Streamable HTTP 服务器模式-Mobile MCP 默认通过 stdio 运行。若要改为启动 SSE 服务器,请使用 `--listen` 参数:+Mobile MCP 默认通过 stdio 运行。若要改为启动 [Streamable HTTP](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#streamable-http) 服务器,请使用 `--listen` 参数:```bashnpx @mobilenext/mobile-mcp@latest --listen 3000@@ -401,17 +401,19 @@ npx @mobilenext/mobile-mcp@latest --listen 3000npx @mobilenext/mobile-mcp@latest --listen 0.0.0.0:3000```-然后将你的 MCP 客户端配置为连接 `http://<host>:3000/mcp`。+然后将你的 MCP 客户端配置为连接 `http://<host>:3000/mcp`(TLS 后可用 `https://…/mcp`)。该端点接受 Streamable HTTP(对 `/mcp` 的 `POST`/`GET`/`DELETE`);远程模式为 **无状态**(无需会话亲和性)。++> **迁移说明:** 此前 `--listen` 在 `/mcp` 上提供已弃用的 HTTP+SSE。客户端需对 `http(s)://host:port/mcp` 使用 Streamable HTTP。见 [#98](https://github.com/mobile-next/mobile-mcp/issues/98)。#### 认证授权-若要在 SSE 服务器上强制使用 Bearer token 授权,请设置环境变量 `MOBILEMCP_AUTH`:+若要在 HTTP 服务器上强制使用 Bearer token 授权,请设置环境变量 `MOBILEMCP_AUTH`:```bashMOBILEMCP_AUTH=my-secret-token npx @mobilenext/mobile-mcp@latest --listen 3000```-设置之后,所有请求都必须包含请求头 `Authorization: Bearer my-secret-token`。+设置之后,所有请求都必须包含请求头 `Authorization: Bearer my-secret-token`。未设置时接受未认证连接并输出警告。### 🛠️ 如何使用@@ -484,7 +486,7 @@ Gmail to contacts "[email protected]".| 变量 | 说明 | 示例 ||---|---|---|-| `MOBILEMCP_AUTH` | 要求 SSE 服务器使用 Bearer token —— 设置后每个请求都必须发送 `Authorization: Bearer <token>`。 | `MOBILEMCP_AUTH=my-secret-token` |+| `MOBILEMCP_AUTH` | 要求 Streamable HTTP 服务器(`--listen`)使用 Bearer token —— 设置后每个请求都必须发送 `Authorization: Bearer <token>`。 | `MOBILEMCP_AUTH=my-secret-token` || `MOBILEMCP_DISABLE_TELEMETRY` | 关闭匿名使用情况遥测。 | `MOBILEMCP_DISABLE_TELEMETRY=1` || `MOBILEMCP_ALLOW_UNSAFE_URLS` | 允许 `mobile_open_url` 打开非标准的 URL scheme(默认被阻止)。 | `MOBILEMCP_ALLOW_UNSAFE_URLS=1` || `MOBILEMCP_LEGACY_ROBOT` | 对 Android 设备和 iOS 真机使用旧版的平台专用 robot。iOS 模拟器仍然使用 `mobilecli`。 | `MOBILEMCP_LEGACY_ROBOT=1` |diff --git a/ROADMAP.md b/ROADMAP.mdindex 4bc8755..64b527b 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -7,7 +7,6 @@ This is a living document of planned and in-progress features. Items are roughly| **Background daemon for speedup** | A long-lived background process that keeps device connections, agents and tunnels warm between tool calls, so each call skips discovery and setup and returns in milliseconds instead of seconds. | In Progress || **Element refs in UI dump** | Every element in the UI dump gets a stable `@ref` id that can be passed to tap, type, etc., so agents act on elements without coordinates. | In Progress || **Embed Android Device Kit in the binary** | Ship the Android agent as a dex embedded in the executable and run it via `app_process`, so nothing gets installed on the device and the Device Kit APK goes away. | In Progress |-| **Streamable HTTP support** | Support the newer MCP Streamable HTTP transport, alongside the existing SSE and stdio transports. | Planned || **File system tools** | List, push, and pull files on the device or within an app container. | Planned || **Better screenshot handling** | Native cropping and scaling, removing the dependency on `sips` and ImageMagick. | Planned || **App launch options** | Launch an app with custom arguments. | Planned |@@ -21,6 +20,7 @@ Shipped in 2026, most recent first.| Feature | Description | Date ||---|---|---|+| **Streamable HTTP support** | `--listen` serves MCP Streamable HTTP on `/mcp` (stateless). Replaces deprecated SSE on `/mcp`. Closes [#98](https://github.com/mobile-next/mobile-mcp/issues/98). | 2026-09-11 || **iOS on Device Kit** | Replaced WebDriverAgent with our own Device Kit on real iOS devices too. | 2026-09-04 || **Remove go-ios dependency** | Dropped the external `go-ios` dependency entirely. | 2026-09-04 || **iOS Device Kit on Simulator** | Replaced WebDriverAgent with our own Device Kit for iOS Simulator automation. | 2026-05-01 |diff --git a/package-lock.json b/package-lock.jsonindex b73c17b..69a60d0 100644--- a/package-lock.json+++ b/package-lock.json@@ -9,7 +9,7 @@"version": "0.0.1","license": "Apache-2.0","dependencies": {- "@modelcontextprotocol/sdk": "1.26.0",+ "@modelcontextprotocol/sdk": "1.30.0","ajv": "^8.18.0","commander": "14.0.0","express": "5.1.0",@@ -1057,12 +1057,11 @@}},"node_modules/@modelcontextprotocol/sdk": {- "version": "1.26.0",- "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.26.0.tgz",- "integrity": "sha512-Y5RmPncpiDtTXDbLKswIJzTqu2hyBKxTNsgKqKclDbhIgg1wgtf1fRuvxgTnRfcnxtvvgbIEcqUOzZrJ6iSReg==",- "license": "MIT",+ "version": "1.30.0",+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.30.0.tgz",+ "integrity": "sha512-xKd8OIzlqNzcqcNumGAa6g+PW2kjD5vrpcKOnfldAUPP3j7lnqMPwlTXQm8gF+UwH72z0lqaRbjr9hqGz0eITA==","dependencies": {- "@hono/node-server": "^1.19.9",+ "@hono/node-server": "^1.19.9 || ^2.0.5","ajv": "^8.17.1","ajv-formats": "^3.0.1","content-type": "^1.0.5",diff --git a/package.json b/package.jsonindex 4f9e0f1..9b20b3d 100644--- a/package.json+++ b/package.json@@ -24,7 +24,7 @@"lib"],"dependencies": {- "@modelcontextprotocol/sdk": "1.26.0",+ "@modelcontextprotocol/sdk": "1.30.0","ajv": "^8.18.0","commander": "14.0.0","express": "5.1.0",diff --git a/scripts/verify-streamable-http.mjs b/scripts/verify-streamable-http.mjsnew file mode 100755index 0000000..34cc9e3--- /dev/null+++ b/scripts/verify-streamable-http.mjs@@ -0,0 +1,96 @@+#!/usr/bin/env node+/**+ * Smoke-verify Streamable HTTP on --listen:+ * spawn the server, initialize via StreamableHTTPClientTransport, tools/list.+ */+import { spawn } from "node:child_process";+import { createServer } from "node:net";+import { fileURLToPath } from "node:url";+import path from "node:path";+import { Client } from "@modelcontextprotocol/sdk/client/index.js";+import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";++const __dirname = path.dirname(fileURLToPath(import.meta.url));+const root = path.resolve(__dirname, "..");+const serverEntry = path.join(root, "lib", "index.js");++function freePort() {+ return new Promise((resolve, reject) => {+ const s = createServer();+ s.listen(0, "127.0.0.1", () => {+ const { port } = s.address();+ s.close(err => (err ? reject(err) : resolve(port)));+ });+ s.on("error", reject);+ });+}++function waitForListen(child, timeoutMs = 15000) {+ return new Promise((resolve, reject) => {+ const timer = setTimeout(() => reject(new Error("Timed out waiting for server listen")), timeoutMs);+ const onData = chunk => {+ const text = chunk.toString();+ if (text.includes("streamable http server listening")) {+ clearTimeout(timer);+ child.stderr?.off("data", onData);+ child.stdout?.off("data", onData);+ resolve();+ }+ };+ child.stderr?.on("data", onData);+ child.stdout?.on("data", onData);+ child.on("exit", code => {+ clearTimeout(timer);+ reject(new Error(`Server exited early with code ${code}`));+ });+ });+}++async function main() {+ const port = await freePort();+ const auth = process.env.MOBILEMCP_AUTH_VERIFY || "verify-token";+ const child = spawn(process.execPath, [serverEntry, "--listen", `127.0.0.1:${port}`], {+ cwd: root,+ env: { ...process.env, MOBILEMCP_AUTH: auth, MOBILEMCP_DISABLE_TELEMETRY: "1" },+ stdio: ["ignore", "pipe", "pipe"],+ });++ let serverLog = "";+ child.stderr?.on("data", c => { serverLog += c.toString(); });+ child.stdout?.on("data", c => { serverLog += c.toString(); });++ try {+ await waitForListen(child);+ const url = `http://127.0.0.1:${port}/mcp`;+ const transport = new StreamableHTTPClientTransport(new URL(url), {+ requestInit: {+ headers: {+ Authorization: `Bearer ${auth}`,+ },+ },+ });+ const client = new Client({ name: "verify-streamable-http", version: "0.0.0" });+ await client.connect(transport);+ const tools = await client.listTools();+ const names = tools.tools.map(t => t.name);+ console.log("OK initialize + tools/list");+ console.log(`tools (${names.length}): ${names.slice(0, 8).join(", ")}${names.length > 8 ? ", ..." : ""}`);+ if (!names.includes("mobile_list_available_devices")) {+ console.warn("warning: mobile_list_available_devices not in tools/list");+ }+ await client.close();+ process.exitCode = 0;+ } catch (err) {+ console.error("VERIFY FAILED:", err);+ console.error("--- server log ---\n" + serverLog);+ process.exitCode = 1;+ } finally {+ child.kill("SIGTERM");+ await new Promise(r => setTimeout(r, 300));+ if (!child.killed) {+ child.kill("SIGKILL");+ }+ }+}++main();diff --git a/src/index.ts b/src/index.tsindex d851fdf..29a1e81 100644--- a/src/index.ts+++ b/src/index.ts@@ -1,18 +1,19 @@#!/usr/bin/env node-import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";+import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";+import { createMcpExpressApp } from "@modelcontextprotocol/sdk/server/express.js";import { createMcpServer, getAgentVersion } from "./server";import { error } from "./logger";-import express from "express";+import { Request, Response } from "express";import { program } from "commander";-const startSseServer = async (host: string, port: number) => {- const app = express();- const server = createMcpServer();-+const startHttpServer = async (host: string, port: number) => {+ // createMcpExpressApp applies express.json() and Host-header DNS rebinding+ // protection automatically when binding to localhost / 127.0.0.1 / ::1.+ const app = createMcpExpressApp({ host });const authToken = process.env.MOBILEMCP_AUTH;if (!authToken) {- error("WARNING: MOBILEMCP_AUTH is not set. The SSE server will accept unauthenticated connections. Set MOBILEMCP_AUTH to require Bearer token authentication.");+ error("WARNING: MOBILEMCP_AUTH is not set. The HTTP server will accept unauthenticated connections. Set MOBILEMCP_AUTH to require Bearer token authentication.");}if (authToken) {@@ -26,46 +27,55 @@ const startSseServer = async (host: string, port: number) => {});}- // Block cross-origin requests — MCP clients are not browsers- app.use((req, res, next) => {- if (req.headers.origin) {- res.status(403).json({ error: "Cross-origin requests are not allowed" });- return;- }-- if (req.method === "OPTIONS") {- res.status(403).end();- return;- }-- next();- });-- let transport: SSEServerTransport | null = null;-- app.post("/mcp", (req, res) => {- if (transport) {- transport.handlePostMessage(req, res);- }- });-- app.get("/mcp", (req, res) => {- if (transport) {- res.status(409).json({ error: "Another client is already connected. Disconnect the existing client first." });- return;+ const handleMcpRequest = async (req: Request, res: Response) => {+ // Stateless Streamable HTTP: fresh server + transport per request+ // (Smithery / horizontal-host friendly; no session affinity).+ const server = createMcpServer();+ try {+ const transport = new StreamableHTTPServerTransport({+ sessionIdGenerator: undefined,+ });+ await server.connect(transport);+ await transport.handleRequest(req, res, req.body);+ res.on("close", () => {+ transport.close();+ server.close();+ });+ } catch (err: unknown) {+ error("Error handling MCP request: " + (err instanceof Error ? err.stack : String(err)));+ if (!res.headersSent) {+ res.status(500).json({+ jsonrpc: "2.0",+ error: {+ code: -32603,+ message: "Internal server error",+ },+ id: null,+ });+ }}+ };++ app.post("/mcp", handleMcpRequest);++ // Stateless mode has no long-lived sessions; GET (SSE stream) and DELETE+ // (session teardown) are not applicable. Return 405 per SDK guidance.+ const methodNotAllowed = (_req: Request, res: Response) => {+ res.status(405).json({+ jsonrpc: "2.0",+ error: {+ code: -32000,+ message: "Method not allowed.",+ },+ id: null,+ });+ };- transport = new SSEServerTransport("/mcp", res);-- transport.onclose = () => {- transport = null;- };-- server.connect(transport);- });+ app.get("/mcp", methodNotAllowed);+ app.delete("/mcp", methodNotAllowed);app.listen(port, host, () => {- error(`mobile-mcp ${getAgentVersion()} sse server listening on http://${host}:${port}/mcp`);+ error(`mobile-mcp ${getAgentVersion()} streamable http server listening on http://${host}:${port}/mcp`);});};@@ -98,7 +108,7 @@ const startStdioServer = async () => {const main = async () => {program.version(getAgentVersion())- .option("--listen <listen>", "Start SSE server on [host:]port")+ .option("--listen <listen>", "Start Streamable HTTP server on [host:]port").option("--stdio", "Start stdio server (default)").parse(process.argv);@@ -123,7 +133,7 @@ const main = async () => {process.exit(1);}- await startSseServer(host, port);+ await startHttpServer(host, port);} else {await startStdioServer();}