@sealgate/android-adb-mcp 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +15 -0
- package/README.md +80 -0
- package/dist/adb.js +241 -0
- package/dist/config.js +24 -0
- package/dist/index.js +160 -0
- package/package.json +52 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
Initial release.
|
|
6
|
+
|
|
7
|
+
- Stdio MCP server exposing `adb` for a locally-connected Android device or
|
|
8
|
+
emulator, with five tools: `get_packages`, `execute_adb_command`,
|
|
9
|
+
`get_uilayout`, `get_screenshot`, and `get_package_action_intents`.
|
|
10
|
+
- Automatic single-device detection; multi-device selection via `--serial` or
|
|
11
|
+
`ANDROID_ADB_SERIAL`.
|
|
12
|
+
- Faithful TypeScript re-implementation of
|
|
13
|
+
[minhalvp/android-mcp-server](https://github.com/minhalvp/android-mcp-server)
|
|
14
|
+
(MIT), packaged for one-command `npx` distribution through the SealGate
|
|
15
|
+
marketplace.
|
package/README.md
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
# @sealgate/android-adb-mcp
|
|
2
|
+
|
|
3
|
+
A thin stdio [MCP](https://modelcontextprotocol.io) server that exposes the
|
|
4
|
+
Android Debug Bridge (`adb`) for a locally-connected device or emulator. It is a
|
|
5
|
+
faithful TypeScript re-implementation of
|
|
6
|
+
[minhalvp/android-mcp-server](https://github.com/minhalvp/android-mcp-server)
|
|
7
|
+
(MIT), packaged and pinned for distribution through the SealGate marketplace so
|
|
8
|
+
it runs with a single `npx` command and no clone.
|
|
9
|
+
|
|
10
|
+
SealGate itself does the security work (per-tool Access Control Levels, policy
|
|
11
|
+
enforcement, taint analysis). This server is deliberately a plain, full-access
|
|
12
|
+
adb passthrough, the gateway in front is what governs it.
|
|
13
|
+
|
|
14
|
+
## Tools
|
|
15
|
+
|
|
16
|
+
| Tool | Arguments | Description |
|
|
17
|
+
| ---------------------------- | -------------- | -------------------------------------------------------------------------------------------------------------------------- |
|
|
18
|
+
| `get_packages` | – | List all installed packages on the device. |
|
|
19
|
+
| `execute_adb_command` | `command` | Run an arbitrary adb command (everything after `adb`) and return its output. |
|
|
20
|
+
| `get_uilayout` | – | Dump the current screen and return clickable/labelled elements with text, description, bounds, and centre tap coordinates. |
|
|
21
|
+
| `get_screenshot` | – | Capture a PNG screenshot of the device screen. |
|
|
22
|
+
| `get_package_action_intents` | `package_name` | List the non-data intent actions a package advertises in its Activity Resolver Table. |
|
|
23
|
+
|
|
24
|
+
## Prerequisites
|
|
25
|
+
|
|
26
|
+
- **Android Platform Tools** (`adb`) on `PATH`. Set `ADB_PATH` to point at a
|
|
27
|
+
non-standard `adb` binary.
|
|
28
|
+
- A connected device or a running emulator (`adb devices` shows it as `device`).
|
|
29
|
+
|
|
30
|
+
## Usage
|
|
31
|
+
|
|
32
|
+
```jsonc
|
|
33
|
+
{
|
|
34
|
+
"mcpServers": {
|
|
35
|
+
"android-adb": {
|
|
36
|
+
"command": "npx",
|
|
37
|
+
"args": ["-y", "@sealgate/android-adb-mcp"]
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
### Selecting a device
|
|
44
|
+
|
|
45
|
+
With one device connected it is auto-detected. On a multi-device host, pick one
|
|
46
|
+
with a launch flag or an env var:
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
npx -y @sealgate/android-adb-mcp --serial emulator-5554
|
|
50
|
+
# or
|
|
51
|
+
ANDROID_ADB_SERIAL=emulator-5554 npx -y @sealgate/android-adb-mcp
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
If multiple devices are connected and none is chosen, every tool returns an
|
|
55
|
+
error listing the connected serials rather than guessing.
|
|
56
|
+
|
|
57
|
+
## Security note
|
|
58
|
+
|
|
59
|
+
`execute_adb_command` is effectively arbitrary `adb shell`: it can read app
|
|
60
|
+
data, dump databases, and move files off the device. Behind SealGate it should
|
|
61
|
+
be classified `SECRET` and gated. The catalog entry ships that classification;
|
|
62
|
+
see `tools_configurations` in the marketplace `servers/android-adb-mcp.json`.
|
|
63
|
+
|
|
64
|
+
## Development
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
npm run build # tsc -> dist/
|
|
68
|
+
npm run typecheck # tsc --noEmit
|
|
69
|
+
npm run test # vitest (pure-parser unit tests, no device needed)
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## Credit
|
|
73
|
+
|
|
74
|
+
Tool surface and behaviour are based on
|
|
75
|
+
[minhalvp/android-mcp-server](https://github.com/minhalvp/android-mcp-server)
|
|
76
|
+
by Minhal Vohra, MIT-licensed.
|
|
77
|
+
|
|
78
|
+
## License
|
|
79
|
+
|
|
80
|
+
MIT
|
package/dist/adb.js
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Android Debug Bridge helpers for the SealGate android-adb-mcp server.
|
|
3
|
+
*
|
|
4
|
+
* The pure functions (`parsePackages`, `parseUiLayout`, `parseActionIntents`,
|
|
5
|
+
* `resolveDeviceArgs`, `tokenizeCommand`, ...) hold all the parsing/decision
|
|
6
|
+
* logic and are unit-tested without a device. The `run*` wrappers are thin
|
|
7
|
+
* shells over `child_process.spawn` that shell out to the real `adb` binary on
|
|
8
|
+
* the user's machine.
|
|
9
|
+
*/
|
|
10
|
+
import { spawn } from 'node:child_process';
|
|
11
|
+
/** The `adb` executable. Overridable for tests / non-standard installs. */
|
|
12
|
+
export const ADB_BIN = process.env.ADB_PATH || 'adb';
|
|
13
|
+
/**
|
|
14
|
+
* Parse `adb shell pm list packages` output into a sorted list of package names.
|
|
15
|
+
* Each line looks like `package:com.example.app`; blank lines and any line
|
|
16
|
+
* without the `package:` prefix are ignored.
|
|
17
|
+
*/
|
|
18
|
+
export function parsePackages(raw) {
|
|
19
|
+
const pkgs = raw
|
|
20
|
+
.split('\n')
|
|
21
|
+
.map((l) => l.trim())
|
|
22
|
+
.filter((l) => l.startsWith('package:'))
|
|
23
|
+
.map((l) => l.slice('package:'.length).trim())
|
|
24
|
+
.filter(Boolean);
|
|
25
|
+
return [...new Set(pkgs)].sort();
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Parse a `uiautomator` bounds string `[x1,y1][x2,y2]` into its centre point.
|
|
29
|
+
* Returns null when the string is malformed, so a single bad node never throws.
|
|
30
|
+
*/
|
|
31
|
+
export function parseBounds(bounds) {
|
|
32
|
+
const m = bounds.match(/\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]/);
|
|
33
|
+
if (!m)
|
|
34
|
+
return null;
|
|
35
|
+
const x1 = Number(m[1]);
|
|
36
|
+
const y1 = Number(m[2]);
|
|
37
|
+
const x2 = Number(m[3]);
|
|
38
|
+
const y2 = Number(m[4]);
|
|
39
|
+
if (![x1, y1, x2, y2].every(Number.isFinite))
|
|
40
|
+
return null;
|
|
41
|
+
return { x: Math.round((x1 + x2) / 2), y: Math.round((y1 + y2) / 2) };
|
|
42
|
+
}
|
|
43
|
+
/** Decode the handful of XML entities `uiautomator` emits in attribute values. */
|
|
44
|
+
function decodeXmlEntities(s) {
|
|
45
|
+
return s
|
|
46
|
+
.replace(/&/g, '&')
|
|
47
|
+
.replace(/</g, '<')
|
|
48
|
+
.replace(/>/g, '>')
|
|
49
|
+
.replace(/"/g, '"')
|
|
50
|
+
.replace(/'/g, "'");
|
|
51
|
+
}
|
|
52
|
+
function attr(node, name) {
|
|
53
|
+
const m = node.match(new RegExp(`${name}="([^"]*)"`));
|
|
54
|
+
return m ? decodeXmlEntities(m[1] ?? '') : '';
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Parse a `uiautomator dump` XML document into the interesting elements: those
|
|
58
|
+
* marked `clickable="true"` or carrying visible `text` / `content-desc`. Uses a
|
|
59
|
+
* tolerant `<node .../>` scan rather than a full XML parser so a slightly
|
|
60
|
+
* malformed dump (common from `uiautomator`) still yields what it can instead of
|
|
61
|
+
* failing whole. Nodes without parseable bounds are skipped (no tap target).
|
|
62
|
+
*/
|
|
63
|
+
export function parseUiLayout(xml) {
|
|
64
|
+
const elements = [];
|
|
65
|
+
for (const m of xml.matchAll(/<node\b[^>]*?\/?>/g)) {
|
|
66
|
+
const node = m[0];
|
|
67
|
+
const text = attr(node, 'text');
|
|
68
|
+
const description = attr(node, 'content-desc');
|
|
69
|
+
const clickable = attr(node, 'clickable') === 'true';
|
|
70
|
+
if (!clickable && !text && !description)
|
|
71
|
+
continue;
|
|
72
|
+
const bounds = attr(node, 'bounds');
|
|
73
|
+
const center = parseBounds(bounds);
|
|
74
|
+
if (!center)
|
|
75
|
+
continue;
|
|
76
|
+
elements.push({
|
|
77
|
+
text,
|
|
78
|
+
description,
|
|
79
|
+
className: attr(node, 'class'),
|
|
80
|
+
bounds,
|
|
81
|
+
center
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
return elements;
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Extract the action names from the "Non-Data Actions" section of
|
|
88
|
+
* `adb shell dumpsys package <pkg>` output (the Activity Resolver Table). These
|
|
89
|
+
* are the intent actions a package can be launched with. Action lines look like
|
|
90
|
+
* ` android.intent.action.MAIN:` and are followed by indented component
|
|
91
|
+
* rows (`<pkg>/<activity> ...`), which we skip. Deduped and sorted.
|
|
92
|
+
*/
|
|
93
|
+
export function parseActionIntents(dumpsys) {
|
|
94
|
+
const lines = dumpsys.split('\n');
|
|
95
|
+
const actions = new Set();
|
|
96
|
+
let inActions = false;
|
|
97
|
+
for (const raw of lines) {
|
|
98
|
+
const line = raw.trimEnd();
|
|
99
|
+
const trimmed = line.trim();
|
|
100
|
+
if (/Non-Data Actions:/.test(trimmed)) {
|
|
101
|
+
inActions = true;
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
if (!inActions)
|
|
105
|
+
continue;
|
|
106
|
+
// The section ends at the next non-indented / differently-headed block.
|
|
107
|
+
if (trimmed === '' || /^[A-Z][A-Za-z ]+:$/.test(trimmed)) {
|
|
108
|
+
if (trimmed !== '' && !/Non-Data Actions:/.test(trimmed))
|
|
109
|
+
break;
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
// An action header ends in ':' and contains no component separator '/'.
|
|
113
|
+
const m = trimmed.match(/^([A-Za-z0-9_.]+):$/);
|
|
114
|
+
if (m && m[1] && m[1].includes('.') && !m[1].includes('/')) {
|
|
115
|
+
actions.add(m[1]);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return [...actions].sort();
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Decide which device an adb command should target, from `adb devices` output
|
|
122
|
+
* and an optional requested serial (a `--serial` launch flag or the
|
|
123
|
+
* `ANDROID_ADB_SERIAL` env var). Precedence:
|
|
124
|
+
* - requested serial present and online -> use it
|
|
125
|
+
* - requested serial not found -> error listing what's connected
|
|
126
|
+
* - no request, exactly one device -> use it
|
|
127
|
+
* - no request, multiple devices -> error asking for a serial
|
|
128
|
+
* - no devices -> error
|
|
129
|
+
* Only `device`-state entries count; `offline` / `unauthorized` are surfaced in
|
|
130
|
+
* the error rather than silently targeted.
|
|
131
|
+
*/
|
|
132
|
+
export function resolveDeviceArgs(devicesRaw, requested) {
|
|
133
|
+
const online = [];
|
|
134
|
+
const other = [];
|
|
135
|
+
for (const raw of devicesRaw.split('\n')) {
|
|
136
|
+
const line = raw.trim();
|
|
137
|
+
if (!line || /^List of devices attached/.test(line))
|
|
138
|
+
continue;
|
|
139
|
+
const [serial, state] = line.split(/\s+/);
|
|
140
|
+
if (!serial)
|
|
141
|
+
continue;
|
|
142
|
+
if (state === 'device')
|
|
143
|
+
online.push(serial);
|
|
144
|
+
else
|
|
145
|
+
other.push(`${serial} (${state ?? 'unknown'})`);
|
|
146
|
+
}
|
|
147
|
+
const want = requested?.trim();
|
|
148
|
+
if (want) {
|
|
149
|
+
if (online.includes(want))
|
|
150
|
+
return { serial: want };
|
|
151
|
+
const seen = [...online, ...other].join(', ') || 'none';
|
|
152
|
+
return { error: `Requested device '${want}' is not connected/online. Devices seen: ${seen}.` };
|
|
153
|
+
}
|
|
154
|
+
if (online.length === 1)
|
|
155
|
+
return { serial: online[0] };
|
|
156
|
+
if (online.length === 0) {
|
|
157
|
+
const extra = other.length ? ` (not usable: ${other.join(', ')})` : '';
|
|
158
|
+
return {
|
|
159
|
+
error: `No online Android devices found${extra}. Connect a device or start an emulator.`
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
return {
|
|
163
|
+
error: `Multiple devices connected (${online.join(', ')}). ` +
|
|
164
|
+
`Set ANDROID_ADB_SERIAL or pass --serial <serial> at launch to pick one.`
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Split a raw `execute_adb_command` string into argv the way a POSIX-ish shell
|
|
169
|
+
* would for the simple cases adb needs: whitespace-separated, with single and
|
|
170
|
+
* double quotes grouping tokens (quotes are stripped). This is NOT a full shell
|
|
171
|
+
* (no expansion, no escaping rules beyond quotes) - it just lets callers write
|
|
172
|
+
* `shell "pm list packages"` without the wrapper mangling the quoted argument.
|
|
173
|
+
*/
|
|
174
|
+
export function tokenizeCommand(command) {
|
|
175
|
+
const tokens = [];
|
|
176
|
+
const re = /"([^"]*)"|'([^']*)'|(\S+)/g;
|
|
177
|
+
let m;
|
|
178
|
+
while ((m = re.exec(command)) !== null) {
|
|
179
|
+
tokens.push(m[1] ?? m[2] ?? m[3] ?? '');
|
|
180
|
+
}
|
|
181
|
+
return tokens;
|
|
182
|
+
}
|
|
183
|
+
/** Prefix `-s <serial>` onto an adb argv when a serial was resolved. */
|
|
184
|
+
export function withSerial(serial, args) {
|
|
185
|
+
return serial ? ['-s', serial, ...args] : args;
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* The single spawn/timeout/error/close implementation. Collects stdout as raw
|
|
189
|
+
* bytes (the text wrapper decodes it) plus stderr as UTF-8, kills the process on
|
|
190
|
+
* timeout and reports it as `code: null` with a stderr suffix. Both public
|
|
191
|
+
* wrappers below are thin typed faces over this, so the tricky process/timeout
|
|
192
|
+
* logic lives in exactly one place.
|
|
193
|
+
*/
|
|
194
|
+
function spawnAdb(args, timeoutMs) {
|
|
195
|
+
return new Promise((resolve, reject) => {
|
|
196
|
+
const child = spawn(ADB_BIN, args, { stdio: ['ignore', 'pipe', 'pipe'] });
|
|
197
|
+
const chunks = [];
|
|
198
|
+
let stderr = '';
|
|
199
|
+
let timedOut = false;
|
|
200
|
+
const timer = setTimeout(() => {
|
|
201
|
+
timedOut = true;
|
|
202
|
+
child.kill('SIGKILL');
|
|
203
|
+
}, timeoutMs);
|
|
204
|
+
timer.unref();
|
|
205
|
+
child.stdout.on('data', (d) => chunks.push(d));
|
|
206
|
+
child.stderr.on('data', (d) => (stderr += d.toString('utf8')));
|
|
207
|
+
child.on('error', (err) => {
|
|
208
|
+
clearTimeout(timer);
|
|
209
|
+
reject(err);
|
|
210
|
+
});
|
|
211
|
+
child.on('close', (code) => {
|
|
212
|
+
clearTimeout(timer);
|
|
213
|
+
resolve({
|
|
214
|
+
data: Buffer.concat(chunks),
|
|
215
|
+
stderr: timedOut ? `${stderr}\n(adb timed out after ${timeoutMs}ms)` : stderr,
|
|
216
|
+
code: timedOut ? null : code
|
|
217
|
+
});
|
|
218
|
+
});
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
/** Spawn adb and collect stdout/stderr as UTF-8 text. */
|
|
222
|
+
export async function runAdb(args, timeoutMs = 60_000) {
|
|
223
|
+
const { data, stderr, code } = await spawnAdb(args, timeoutMs);
|
|
224
|
+
return { stdout: data.toString('utf8'), stderr, code };
|
|
225
|
+
}
|
|
226
|
+
/** Spawn adb and collect stdout as raw bytes (for `exec-out screencap -p`). */
|
|
227
|
+
export function runAdbBinary(args, timeoutMs = 60_000) {
|
|
228
|
+
return spawnAdb(args, timeoutMs);
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* Resolve the device serial to target once, from `adb devices` plus the launch
|
|
232
|
+
* config. Throws with a helpful message when no single device can be chosen, so
|
|
233
|
+
* every tool surfaces the same guidance instead of a raw adb error.
|
|
234
|
+
*/
|
|
235
|
+
export async function resolveSerial(requested) {
|
|
236
|
+
const devices = await runAdb(['devices']);
|
|
237
|
+
const selection = resolveDeviceArgs(devices.stdout, requested);
|
|
238
|
+
if ('error' in selection)
|
|
239
|
+
throw new Error(selection.error);
|
|
240
|
+
return selection.serial;
|
|
241
|
+
}
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Launch-time configuration for the android-adb-mcp server. Kept in its own
|
|
3
|
+
* side-effect-free module so tests can import it without running `index.ts`
|
|
4
|
+
* (which opens a stdio transport on import).
|
|
5
|
+
*/
|
|
6
|
+
/** Parse `--serial <x>` / `--serial=x` from argv, falling back to the env var. */
|
|
7
|
+
export function parseServerConfig(argv) {
|
|
8
|
+
const config = {};
|
|
9
|
+
for (let i = 0; i < argv.length; i++) {
|
|
10
|
+
const arg = argv[i];
|
|
11
|
+
if (arg === undefined)
|
|
12
|
+
continue;
|
|
13
|
+
if (arg === '--serial')
|
|
14
|
+
config.serial = argv[++i];
|
|
15
|
+
else if (arg.startsWith('--serial='))
|
|
16
|
+
config.serial = arg.slice('--serial='.length);
|
|
17
|
+
}
|
|
18
|
+
if (!config.serial && process.env.ANDROID_ADB_SERIAL) {
|
|
19
|
+
config.serial = process.env.ANDROID_ADB_SERIAL;
|
|
20
|
+
}
|
|
21
|
+
if (config.serial !== undefined && config.serial.trim() === '')
|
|
22
|
+
delete config.serial;
|
|
23
|
+
return config;
|
|
24
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* SealGate android-adb-mcp: a thin stdio MCP server that exposes Android Debug
|
|
4
|
+
* Bridge (adb) for a locally-connected device or emulator.
|
|
5
|
+
*
|
|
6
|
+
* Tools (a faithful TypeScript re-implementation of minhalvp/android-mcp-server,
|
|
7
|
+
* MIT, https://github.com/minhalvp/android-mcp-server):
|
|
8
|
+
* - get_packages
|
|
9
|
+
* - execute_adb_command
|
|
10
|
+
* - get_uilayout
|
|
11
|
+
* - get_screenshot
|
|
12
|
+
* - get_package_action_intents
|
|
13
|
+
*
|
|
14
|
+
* Launched on the user's machine by the SealGate daemon over a stdio tunnel,
|
|
15
|
+
* e.g. `npx -y @sealgate/android-adb-mcp`. Pick a device on a multi-device host
|
|
16
|
+
* with `--serial <serial>` or the `ANDROID_ADB_SERIAL` env var.
|
|
17
|
+
*/
|
|
18
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
19
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
20
|
+
import { z } from 'zod';
|
|
21
|
+
import { parseActionIntents, parsePackages, parseUiLayout, resolveSerial, runAdb, runAdbBinary, tokenizeCommand, withSerial } from './adb.js';
|
|
22
|
+
import { parseServerConfig } from './config.js';
|
|
23
|
+
const VERSION = '0.1.0';
|
|
24
|
+
/** A validated Android package name (also guards the dumpsys shell argument). */
|
|
25
|
+
const PACKAGE_NAME = /^[A-Za-z0-9_][A-Za-z0-9_.]*$/;
|
|
26
|
+
/** Where `uiautomator dump` writes on the device before we cat it back. */
|
|
27
|
+
const UI_DUMP_PATH = '/sdcard/window_dump.xml';
|
|
28
|
+
/**
|
|
29
|
+
* Resolve the target serial at most once per process. Cached because it costs an
|
|
30
|
+
* `adb devices` round-trip and the connected device does not change mid-session;
|
|
31
|
+
* a failed resolution is not cached so replugging a device recovers.
|
|
32
|
+
*/
|
|
33
|
+
function makeSerialResolver(config) {
|
|
34
|
+
let cached;
|
|
35
|
+
return async () => {
|
|
36
|
+
if (cached)
|
|
37
|
+
return cached;
|
|
38
|
+
cached = await resolveSerial(config.serial);
|
|
39
|
+
return cached;
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
function textResult(text, isError = false) {
|
|
43
|
+
return { content: [{ type: 'text', text }], isError };
|
|
44
|
+
}
|
|
45
|
+
/** Render a failed adb invocation into a single human-readable error string. */
|
|
46
|
+
function adbFailure(action, stderr, code) {
|
|
47
|
+
const detail = stderr.trim() || '(no stderr)';
|
|
48
|
+
return `${action} failed (adb exit ${code ?? 'null'}):\n${detail}`;
|
|
49
|
+
}
|
|
50
|
+
function registerTools(server, resolve) {
|
|
51
|
+
server.registerTool('get_packages', {
|
|
52
|
+
title: 'List installed packages',
|
|
53
|
+
description: 'List all packages installed on the connected Android device.',
|
|
54
|
+
inputSchema: {}
|
|
55
|
+
}, async () => {
|
|
56
|
+
const serial = await resolve();
|
|
57
|
+
const res = await runAdb(withSerial(serial, ['shell', 'pm', 'list', 'packages']));
|
|
58
|
+
if (res.code !== 0)
|
|
59
|
+
return textResult(adbFailure('get_packages', res.stderr, res.code), true);
|
|
60
|
+
const packages = parsePackages(res.stdout);
|
|
61
|
+
return textResult(JSON.stringify({ count: packages.length, packages }, null, 2));
|
|
62
|
+
});
|
|
63
|
+
server.registerTool('execute_adb_command', {
|
|
64
|
+
title: 'Execute an adb command',
|
|
65
|
+
description: 'Run an arbitrary adb command against the connected device and return its output. ' +
|
|
66
|
+
'The command is everything after `adb` (e.g. "shell ls /sdcard", "pm list packages", ' +
|
|
67
|
+
'"logcat -d"). The target device is selected automatically.',
|
|
68
|
+
inputSchema: {
|
|
69
|
+
command: z
|
|
70
|
+
.string()
|
|
71
|
+
.min(1)
|
|
72
|
+
.describe('The adb command to run, without the leading `adb` (e.g. "shell ls /sdcard").')
|
|
73
|
+
}
|
|
74
|
+
}, async ({ command }) => {
|
|
75
|
+
const args = tokenizeCommand(command);
|
|
76
|
+
if (args.length === 0)
|
|
77
|
+
return textResult('execute_adb_command: empty command', true);
|
|
78
|
+
const serial = await resolve();
|
|
79
|
+
const res = await runAdb(withSerial(serial, args));
|
|
80
|
+
const out = res.stdout.trim();
|
|
81
|
+
const err = res.stderr.trim();
|
|
82
|
+
if (res.code !== 0) {
|
|
83
|
+
const parts = [`adb exited with code ${res.code ?? 'null'}.`];
|
|
84
|
+
if (out)
|
|
85
|
+
parts.push(`--- stdout ---\n${out}`);
|
|
86
|
+
if (err)
|
|
87
|
+
parts.push(`--- stderr ---\n${err}`);
|
|
88
|
+
return textResult(parts.join('\n\n'), true);
|
|
89
|
+
}
|
|
90
|
+
return textResult(out || err || '(no output)');
|
|
91
|
+
});
|
|
92
|
+
server.registerTool('get_uilayout', {
|
|
93
|
+
title: 'Get UI layout',
|
|
94
|
+
description: 'Dump the current screen UI hierarchy and return the clickable/labelled elements with ' +
|
|
95
|
+
'their text, content description, class, bounds, and centre tap coordinates.',
|
|
96
|
+
inputSchema: {}
|
|
97
|
+
}, async () => {
|
|
98
|
+
const serial = await resolve();
|
|
99
|
+
const dump = await runAdb(withSerial(serial, ['shell', 'uiautomator', 'dump', UI_DUMP_PATH]));
|
|
100
|
+
// `uiautomator dump` prints its status to stdout and a non-zero exit only on
|
|
101
|
+
// hard failure; tolerate the status line and rely on the cat below.
|
|
102
|
+
if (dump.code !== 0 && !/dumped to/i.test(dump.stdout + dump.stderr)) {
|
|
103
|
+
return textResult(adbFailure('get_uilayout (dump)', dump.stderr || dump.stdout, dump.code), true);
|
|
104
|
+
}
|
|
105
|
+
const cat = await runAdb(withSerial(serial, ['shell', 'cat', UI_DUMP_PATH]));
|
|
106
|
+
if (cat.code !== 0)
|
|
107
|
+
return textResult(adbFailure('get_uilayout (read)', cat.stderr, cat.code), true);
|
|
108
|
+
const elements = parseUiLayout(cat.stdout);
|
|
109
|
+
return textResult(JSON.stringify({ count: elements.length, elements }, null, 2));
|
|
110
|
+
});
|
|
111
|
+
server.registerTool('get_screenshot', {
|
|
112
|
+
title: 'Take a screenshot',
|
|
113
|
+
description: 'Capture a PNG screenshot of the connected device screen.',
|
|
114
|
+
inputSchema: {}
|
|
115
|
+
}, async () => {
|
|
116
|
+
const serial = await resolve();
|
|
117
|
+
const res = await runAdbBinary(withSerial(serial, ['exec-out', 'screencap', '-p']));
|
|
118
|
+
if (res.code !== 0 || res.data.length === 0) {
|
|
119
|
+
return textResult(adbFailure('get_screenshot', res.stderr, res.code), true);
|
|
120
|
+
}
|
|
121
|
+
return {
|
|
122
|
+
content: [
|
|
123
|
+
{ type: 'image', data: res.data.toString('base64'), mimeType: 'image/png' }
|
|
124
|
+
]
|
|
125
|
+
};
|
|
126
|
+
});
|
|
127
|
+
server.registerTool('get_package_action_intents', {
|
|
128
|
+
title: 'Get package action intents',
|
|
129
|
+
description: 'List the non-data intent actions a package advertises in its Activity Resolver Table ' +
|
|
130
|
+
'(useful for launching specific screens of an app).',
|
|
131
|
+
inputSchema: {
|
|
132
|
+
package_name: z
|
|
133
|
+
.string()
|
|
134
|
+
.min(1)
|
|
135
|
+
.describe('The package name to inspect, e.g. "com.android.settings".')
|
|
136
|
+
}
|
|
137
|
+
}, async ({ package_name }) => {
|
|
138
|
+
if (!PACKAGE_NAME.test(package_name)) {
|
|
139
|
+
return textResult(`Invalid package name: ${JSON.stringify(package_name)}`, true);
|
|
140
|
+
}
|
|
141
|
+
const serial = await resolve();
|
|
142
|
+
const res = await runAdb(withSerial(serial, ['shell', 'dumpsys', 'package', package_name]));
|
|
143
|
+
if (res.code !== 0) {
|
|
144
|
+
return textResult(adbFailure('get_package_action_intents', res.stderr, res.code), true);
|
|
145
|
+
}
|
|
146
|
+
const actions = parseActionIntents(res.stdout);
|
|
147
|
+
return textResult(JSON.stringify({ package: package_name, count: actions.length, actions }, null, 2));
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
async function main() {
|
|
151
|
+
const config = parseServerConfig(process.argv.slice(2));
|
|
152
|
+
const server = new McpServer({ name: 'sealgate-android-adb', version: VERSION });
|
|
153
|
+
registerTools(server, makeSerialResolver(config));
|
|
154
|
+
const transport = new StdioServerTransport();
|
|
155
|
+
await server.connect(transport);
|
|
156
|
+
}
|
|
157
|
+
main().catch((err) => {
|
|
158
|
+
process.stderr.write(`fatal: ${err instanceof Error ? (err.stack ?? err.message) : String(err)}\n`);
|
|
159
|
+
process.exit(1);
|
|
160
|
+
});
|
package/package.json
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@sealgate/android-adb-mcp",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "SealGate stdio MCP server that exposes Android Debug Bridge (adb) on the local machine: packages, UI layout, screenshots, action intents, and raw adb commands.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"mcp",
|
|
7
|
+
"modelcontextprotocol",
|
|
8
|
+
"adb",
|
|
9
|
+
"android",
|
|
10
|
+
"android-debug-bridge",
|
|
11
|
+
"sealgate",
|
|
12
|
+
"stdio"
|
|
13
|
+
],
|
|
14
|
+
"license": "MIT",
|
|
15
|
+
"author": "SealGate",
|
|
16
|
+
"homepage": "https://github.com/Edison-Watch/custom-mcps/tree/main/servers/android-adb",
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "https://github.com/Edison-Watch/custom-mcps.git",
|
|
20
|
+
"directory": "servers/android-adb"
|
|
21
|
+
},
|
|
22
|
+
"type": "module",
|
|
23
|
+
"bin": {
|
|
24
|
+
"android-adb-mcp": "dist/index.js"
|
|
25
|
+
},
|
|
26
|
+
"files": [
|
|
27
|
+
"dist",
|
|
28
|
+
"README.md",
|
|
29
|
+
"CHANGELOG.md"
|
|
30
|
+
],
|
|
31
|
+
"engines": {
|
|
32
|
+
"node": ">=18"
|
|
33
|
+
},
|
|
34
|
+
"publishConfig": {
|
|
35
|
+
"access": "public"
|
|
36
|
+
},
|
|
37
|
+
"scripts": {
|
|
38
|
+
"build": "tsc -p tsconfig.json",
|
|
39
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
40
|
+
"test": "vitest run",
|
|
41
|
+
"prepublishOnly": "npm run build"
|
|
42
|
+
},
|
|
43
|
+
"dependencies": {
|
|
44
|
+
"@modelcontextprotocol/sdk": "^1.19.1",
|
|
45
|
+
"zod": "^4.3.6"
|
|
46
|
+
},
|
|
47
|
+
"devDependencies": {
|
|
48
|
+
"@types/node": "^22.10.0",
|
|
49
|
+
"typescript": "^5.9.2",
|
|
50
|
+
"vitest": "^4.0.18"
|
|
51
|
+
}
|
|
52
|
+
}
|