import {exec} from 'child_process';
import {promisify} from 'util';
import {McpServer} from "@modelcontextprotocol/sdk/server/mcp.js";
import {StdioServerTransport} from "@modelcontextprotocol/sdk/server/stdio.js";
import {z} from 'zod';
import * as fs from 'fs/promises';
import * as path from 'path';
const execAsync = promisify(exec);
const server = new McpServer({
name: 'adb-mcp-tools',
version: '1.0.0'
});
// 命令行参数解析
if (process.argv.length < 3) {
console.error('Usage: mcp-server-adb <path for adb>');
process.exit(1);
}
const adbPath = process.argv[2];
// 执行ADB命令的函数
async function executeAdbCommand(command: string, options?: { deviceId?: string, useUsb?: boolean, useEmulator?: boolean }): Promise<string> {
try {
let deviceOption = '';
if (options?.deviceId) {
deviceOption = `-s ${options.deviceId}`;
} else if (options?.useUsb) {
deviceOption = '-d';
} else if (options?.useEmulator) {
deviceOption = '-e';
}
// 使用完整路径执行命令
const cmd = `"${adbPath}" ${deviceOption} ${command}`;
console.log('Executing command:', cmd);
const {stdout, stderr} = await execAsync(cmd);
// 某些 adb 命令会输出到 stderr,但不一定是错误
if (stderr && !stdout) {
throw new Error(stderr);
}
return stdout || stderr;
} catch (error: unknown) {
if (error instanceof Error) {
throw new Error(`ADB Command Error: ${error.message}`);
}
throw new Error('Unknown error occurred while executing ADB command');
}
}
// 获取已连接设备列表的工具
server.tool(
'get-devices',
'Get a list of connected Android devices',
{
showDetails: z.boolean().optional().default(true).describe('Show device details (-l)')
},
async ({ showDetails }) => {
try {
const options = showDetails ? '-l' : '';
const result = await executeAdbCommand(`devices ${options}`);
return {
content: [{type: 'text', text: result}]
};
} catch (error) {
return {
isError: true,
content: [{type: 'text', text: `Failed to get device list: ${error instanceof Error ? error.message : 'Unknown error'}`}]
};
}
}
);
// 更新所有工具的设备选择参数
const deviceSelectionParams = {
deviceId: z.string().optional().describe('Target specific device by ID (takes precedence over useUsb and useEmulator)'),
useUsb: z.boolean().optional().default(false).describe('Target USB connected device (-d)'),
useEmulator: z.boolean().optional().default(false).describe('Target emulator instance (-e)')
};
// 获取已安装应用列表的工具
server.tool(
'list-packages',
'Get a list of installed applications',
{
...deviceSelectionParams,
showPath: z.boolean().optional().default(false).describe('Show the APK file path for each package (-f)'),
showDisabled: z.boolean().optional().default(false).describe('Filter to only show disabled packages (-d)'),
showEnabled: z.boolean().optional().default(false).describe('Filter to only show enabled packages (-e)'),
showSystem: z.boolean().optional().default(false).describe('Filter to only show system packages (-s)'),
showThirdParty: z.boolean().optional().default(false).describe('Filter to only show third party packages (-3)'),
showInstaller: z.boolean().optional().default(false).describe('Show the installer for each package (-i)'),
includeUninstalled: z.boolean().optional().default(false).describe('Include uninstalled packages (-u)')
},
async ({ deviceId, useUsb, useEmulator, showPath, showDisabled, showEnabled, showSystem, showThirdParty, showInstaller, includeUninstalled }) => {
try {
const options = [
showPath ? '-f' : '',
showDisabled ? '-d' : '',
showEnabled ? '-e' : '',
showSystem ? '-s' : '',
showThirdParty ? '-3' : '',
showInstaller ? '-i' : '',
includeUninstalled ? '-u' : ''
].filter(Boolean).join(' ');
const result = await executeAdbCommand(`shell pm list packages ${options}`, { deviceId, useUsb, useEmulator });
return {
content: [{type: 'text', text: result}]
};
} catch (error) {
return {
isError: true,
content: [{type: 'text', text: `Failed to get package list: ${error instanceof Error ? error.message : 'Unknown error'}`}]
};
}
}
);
// 文本输入工具
server.tool(
'input-text',
'Input text to the connected Android device',
{
...deviceSelectionParams,
text: z.string().describe('Text to input to the device')
},
async ({ text, deviceId, useUsb, useEmulator }) => {
try {
const escapedText = `'${text}'`;
const result = await executeAdbCommand(`shell input text ${escapedText}`, { deviceId, useUsb, useEmulator });
return {
content: [{type: 'text', text: 'Text input completed successfully'}]
};
} catch (error) {
return {
isError: true,
content: [{type: 'text', text: `Failed to input text: ${error instanceof Error ? error.message : 'Unknown error'}`}]
};
}
}
);
// 显示ADB帮助信息的工具
server.tool(
'help',
'Show ADB help information',
async () => {
try {
const result = await executeAdbCommand('help');
return {
content: [{type: 'text', text: result}]
};
} catch (error) {
return {
isError: true,
content: [{type: 'text', text: `Failed to get ADB help: ${error instanceof Error ? error.message : 'Unknown error'}`}]
};
}
}
);
// 终止ADB服务器的工具
server.tool(
'kill-server',
'Kill the ADB server process',
async () => {
try {
await executeAdbCommand('kill-server');
return {
content: [{type: 'text', text: 'ADB server terminated successfully'}]
};
} catch (error) {
return {
isError: true,
content: [{type: 'text', text: `Failed to kill ADB server: ${error instanceof Error ? error.message : 'Unknown error'}`}]
};
}
}
);
// 启动ADB服务器的工具
server.tool(
'start-server',
'Start the ADB server process',
async () => {
try {
await executeAdbCommand('start-server');
return {
content: [{type: 'text', text: 'ADB server has been started successfully'}]
};
} catch (error) {
return {
isError: true,
content: [{type: 'text', text: `Failed to start ADB server: ${error instanceof Error ? error.message : 'Unknown error'}`}]
};
}
}
);
// 安装APK文件的工具
server.tool(
'install-apk',
'Install an APK file to the device',
{
...deviceSelectionParams,
apkPath: z.string().describe('Path to the APK file'),
grantPermissions: z.boolean().optional().default(false).describe('Grant all permissions (-g)'),
allowReinstall: z.boolean().optional().default(true).describe('Allow reinstalling an existing app (-r)'),
allowDowngrade: z.boolean().optional().default(true).describe('Allow version code downgrade (-d)'),
allowTestPackages: z.boolean().optional().default(true).describe('Allow test packages (-t)')
},
async ({ deviceId, useUsb, useEmulator, apkPath, grantPermissions, allowReinstall, allowDowngrade, allowTestPackages }) => {
try {
const options = [
grantPermissions ? '-g' : '',
allowReinstall ? '-r' : '',
allowDowngrade ? '-d' : '',
allowTestPackages ? '-t' : ''
].filter(Boolean).join(' ');
const result = await executeAdbCommand(`install ${options} "${apkPath}"`, { deviceId, useUsb, useEmulator });
return {
content: [{type: 'text', text: result}]
};
} catch (error) {
return {
isError: true,
content: [{type: 'text', text: `Failed to install APK: ${error instanceof Error ? error.message : 'Unknown error'}`}]
};
}
}
);
// 卸载应用的工具
server.tool(
'uninstall-apk',
'Uninstall an application from the device',
{
...deviceSelectionParams,
packageName: z.string().describe('Package name of the application'),
keepData: z.boolean().optional().default(false).describe('Keep the app data and cache directories (-k)')
},
async ({ deviceId, useUsb, useEmulator, packageName, keepData }) => {
try {
const options = keepData ? '-k' : '';
const result = await executeAdbCommand(`uninstall ${options} ${packageName}`, { deviceId, useUsb, useEmulator });
return {
content: [{type: 'text', text: result}]
};
} catch (error) {
return {
isError: true,
content: [{type: 'text', text: `Failed to uninstall application: ${error instanceof Error ? error.message : 'Unknown error'}`}]
};
}
}
);
// 截图工具
server.tool(
'screencap',
'Take a screenshot of the device display',
{
...deviceSelectionParams,
remotePath: z.string().describe('Path on device where to save the screenshot (e.g., /sdcard/screenshot.png)'),
usePng: z.boolean().optional().default(true).describe('Save as PNG format (-p)')
},
async ({ deviceId, useUsb, useEmulator, remotePath, usePng }) => {
try {
const options = usePng ? '-p' : '';
await executeAdbCommand(`shell screencap ${options} ${remotePath}`, { deviceId, useUsb, useEmulator });
return {
content: [{type: 'text', text: `Screenshot saved to ${remotePath} on device`}]
};
} catch (error) {
return {
isError: true,
content: [{type: 'text', text: `Failed to take screenshot: ${error instanceof Error ? error.message : 'Unknown error'}`}]
};
}
}
);
// 清除应用数据的工具
server.tool(
'clear-app-data',
'Clear application data for a specific package',
{
...deviceSelectionParams,
packageName: z.string().describe('Package name of the application')
},
async ({ deviceId, useUsb, useEmulator, packageName }) => {
try {
const result = await executeAdbCommand(`shell pm clear ${packageName}`, { deviceId, useUsb, useEmulator });
return {
content: [{type: 'text', text: result}]
};
} catch (error) {
return {
isError: true,
content: [{type: 'text', text: `Failed to clear app data: ${error instanceof Error ? error.message : 'Unknown error'}`}]
};
}
}
);
// 授予权限的工具
server.tool(
'grant-permission',
'Grant a specific permission to an app',
{
...deviceSelectionParams,
packageName: z.string().describe('Package name of the application'),
permission: z.string().describe('Permission to grant (e.g., android.permission.CAMERA)')
},
async ({ deviceId, useUsb, useEmulator, packageName, permission }) => {
try {
const result = await executeAdbCommand(`shell pm grant ${packageName} ${permission}`, { deviceId, useUsb, useEmulator });
return {
content: [{type: 'text', text: result || `Permission ${permission} granted to ${packageName}`}]
};
} catch (error) {
return {
isError: true,
content: [{type: 'text', text: `Failed to grant permission: ${error instanceof Error ? error.message : 'Unknown error'}`}]
};
}
}
);
// 撤销权限的工具
server.tool(
'revoke-permission',
'Revoke a specific permission from an app',
{
...deviceSelectionParams,
packageName: z.string().describe('Package name of the application'),
permission: z.string().describe('Permission to revoke (e.g., android.permission.CAMERA)')
},
async ({ deviceId, useUsb, useEmulator, packageName, permission }) => {
try {
const result = await executeAdbCommand(`shell pm revoke ${packageName} ${permission}`, { deviceId, useUsb, useEmulator });
return {
content: [{type: 'text', text: result || `Permission ${permission} revoked from ${packageName}`}]
};
} catch (error) {
return {
isError: true,
content: [{type: 'text', text: `Failed to revoke permission: ${error instanceof Error ? error.message : 'Unknown error'}`}]
};
}
}
);
// 重置所有权限的工具
server.tool(
'reset-permissions',
'Reset all permissions for a specific package',
{
...deviceSelectionParams,
packageName: z.string().describe('Package name of the application')
},
async ({ deviceId, useUsb, useEmulator, packageName }) => {
try {
const result = await executeAdbCommand(`shell pm reset-permissions ${packageName}`, { deviceId, useUsb, useEmulator });
return {
content: [{type: 'text', text: result || `All permissions reset for ${packageName}`}]
};
} catch (error) {
return {
isError: true,
content: [{type: 'text', text: `Failed to reset permissions: ${error instanceof Error ? error.message : 'Unknown error'}`}]
};
}
}
);
// 推送文件到设备的工具
server.tool(
'push',
'Push a file from the local machine to the Android device',
{
...deviceSelectionParams,
localPath: z.string().describe('Path to the local file'),
remotePath: z.string().describe('Destination path on the device')
},
async ({ deviceId, useUsb, useEmulator, localPath, remotePath }) => {
try {
const result = await executeAdbCommand(`push "${localPath}" "${remotePath}"`, { deviceId, useUsb, useEmulator });
return {
content: [{type: 'text', text: result}]
};
} catch (error) {
return {
isError: true,
content: [{type: 'text', text: `Failed to push file: ${error instanceof Error ? error.message : 'Unknown error'}`}]
};
}
}
);
// 从设备拉取文件的工具
server.tool(
'pull',
'Pull a file from the Android device to the local machine',
{
...deviceSelectionParams,
remotePath: z.string().describe('Path to the file on the device'),
localPath: z.string().optional().describe('Path where to save the file locally (optional, defaults to current directory)')
},
async ({ deviceId, useUsb, useEmulator, remotePath, localPath }) => {
try {
const localPathOption = localPath ? `"${localPath}"` : '.';
const result = await executeAdbCommand(`pull "${remotePath}" ${localPathOption}`, { deviceId, useUsb, useEmulator });
return {
content: [{type: 'text', text: result}]
};
} catch (error) {
return {
isError: true,
content: [{type: 'text', text: `Failed to pull file: ${error instanceof Error ? error.message : 'Unknown error'}`}]
};
}
}
);
// 删除设备上的文件的工具
server.tool(
'rm',
'Remove a file from the Android device',
{
...deviceSelectionParams,
path: z.string().describe('Path to the file on device to remove'),
recursive: z.boolean().optional().default(false).describe('Recursive removal (-r)'),
force: z.boolean().optional().default(false).describe('Force removal (-f)')
},
async ({ deviceId, useUsb, useEmulator, path, recursive, force }) => {
try {
const options = [
recursive ? '-r' : '',
force ? '-f' : ''
].filter(Boolean).join(' ');
const result = await executeAdbCommand(`shell rm ${options} "${path}"`, { deviceId, useUsb, useEmulator });
return {
content: [{type: 'text', text: result || `File ${path} removed successfully`}]
};
} catch (error) {
return {
isError: true,
content: [{type: 'text', text: `Failed to remove file: ${error instanceof Error ? error.message : 'Unknown error'}`}]
};
}
}
);
// 清除日志缓冲区的工具
server.tool(
'clear-logcat',
'清除设备上的日志缓冲区',
{
...deviceSelectionParams,
buffer: z.string().optional().default('all').describe('要清除的缓冲区 (main, events, radio, crash, all)')
},
async ({ deviceId, useUsb, useEmulator, buffer }) => {
try {
const result = await executeAdbCommand(`logcat -b ${buffer} -c`, { deviceId, useUsb, useEmulator });
return {
content: [{type: 'text', text: result || `已清除 ${buffer} 缓冲区的日志`}]
};
} catch (error) {
return {
isError: true,
content: [{type: 'text', text: `清除日志失败: ${error instanceof Error ? error.message : '未知错误'}`}]
};
}
}
);
// 获取应用崩溃日志的工具
server.tool(
'get-crash-log',
'获取应用崩溃日志,分析错误原因',
{
...deviceSelectionParams,
packageName: z.string().describe('应用包名'),
lines: z.number().optional().default(200).describe('获取日志的行数')
},
async ({ deviceId, useUsb, useEmulator, packageName, lines }) => {
try {
// 先清除日志,以便获取最新的崩溃信息
await executeAdbCommand('logcat -c', { deviceId, useUsb, useEmulator });
// 启动应用,可能会触发崩溃
await executeAdbCommand(`shell monkey -p ${packageName} -c android.intent.category.LAUNCHER 1`, { deviceId, useUsb, useEmulator });
// 等待一段时间,让应用有机会崩溃
await new Promise(resolve => setTimeout(resolve, 2000));
// 获取日志中的崩溃信息
const logResult = await executeAdbCommand(`logcat -d -v threadtime *:E -n ${lines}`, { deviceId, useUsb, useEmulator });
// 分析日志,查找与包名相关的崩溃信息
const logLines = logResult.split('\n');
const crashLines = logLines.filter(line => {
return line.includes(packageName) &&
(line.includes('Exception') || line.includes('Error') || line.includes('FATAL') || line.includes('ANR'));
});
// 如果找到崩溃信息,返回相关上下文
if (crashLines.length > 0) {
// 找到第一个崩溃行的索引
const firstCrashIndex = logLines.findIndex(line =>
line.includes(packageName) &&
(line.includes('Exception') || line.includes('Error') || line.includes('FATAL') || line.includes('ANR'))
);
// 获取崩溃上下文(前5行和后20行)
const startIndex = Math.max(0, firstCrashIndex - 5);
const endIndex = Math.min(logLines.length, firstCrashIndex + 20);
const crashContext = logLines.slice(startIndex, endIndex).join('\n');
return {
content: [
{ type: 'text', text: `找到应用 ${packageName} 的崩溃信息:\n\n${crashContext}` }
]
};
}
return {
content: [{ type: 'text', text: `未发现应用 ${packageName} 的明显崩溃信息。完整日志:\n\n${logResult}` }]
};
} catch (error) {
return {
isError: true,
content: [{
type: 'text',
text: `获取崩溃日志失败: ${error instanceof Error ? error.message : '未知错误'}`
}]
};
}
}
);
// 启动Activity的工具
server.tool(
'start-activity',
'Start an activity using activity manager (am start)',
{
...deviceSelectionParams,
component: z.string().optional().describe('Component name (e.g., com.example/.MainActivity or com.example/com.example.MainActivity)'),
action: z.string().optional().describe('Intent action (e.g., android.intent.action.VIEW)'),
data: z.string().optional().describe('Intent data URI'),
mimeType: z.string().optional().describe('MIME type (e.g., image/png)'),
category: z.array(z.string()).optional().describe('Intent categories (e.g., ["android.intent.category.LAUNCHER"])'),
extras: z.array(z.object({
type: z.enum(['string', 'int', 'long', 'float', 'boolean', 'uri', 'component']),
key: z.string(),
value: z.string()
})).optional().describe('Intent extras (e.g., [{type: "string", key: "key1", value: "value1"}])'),
flags: z.array(z.string()).optional().describe('Intent flags (e.g., ["activity_new_task", "activity_clear_top"])'),
waitForLaunch: z.boolean().optional().default(false).describe('Wait for launch to complete (-W)'),
debuggable: z.boolean().optional().default(false).describe('Debug mode (-D)'),
stopApp: z.boolean().optional().default(false).describe('Force stop target app before starting activity (-S)')
},
async ({ deviceId, useUsb, useEmulator, component, action, data, mimeType, category, extras, flags, waitForLaunch, debuggable, stopApp }) => {
try {
let cmd = 'shell am start';
// 添加选项
if (waitForLaunch) cmd += ' -W';
if (debuggable) cmd += ' -D';
if (stopApp) cmd += ' -S';
// 添加动作
if (action) cmd += ` -a ${action}`;
// 添加数据
if (data) cmd += ` -d "${data}"`;
// 添加MIME类型
if (mimeType) cmd += ` -t "${mimeType}"`;
// 添加类别
if (category && category.length > 0) {
for (const cat of category) {
cmd += ` -c ${cat}`;
}
}
// 添加额外数据
if (extras && extras.length > 0) {
for (const extra of extras) {
cmd += ` --e${extra.type.charAt(0)} ${extra.key} "${extra.value}"`;
}
}
// 添加标志
if (flags && flags.length > 0) {
for (const flag of flags) {
cmd += ` -f ${flag}`;
}
}
// 添加组件
if (component) cmd += ` -n ${component}`;
const result = await executeAdbCommand(cmd, { deviceId, useUsb, useEmulator });
return {
content: [{type: 'text', text: result}]
};
} catch (error) {
return {
isError: true,
content: [{type: 'text', text: `Failed to start activity: ${error instanceof Error ? error.message : 'Unknown error'}`}]
};
}
}
);
// 查看系统窗口层级结构树
server.tool(
'activity-containers',
'展示系统窗口层级结构树',
{
...deviceSelectionParams
},
async ({ deviceId, useUsb, useEmulator }) => {
try {
const result = await executeAdbCommand('shell dumpsys activity containers', { deviceId, useUsb, useEmulator });
return {
content: [{type: 'text', text: result}]
};
} catch (error) {
return {
isError: true,
content: [{type: 'text', text: `获取窗口层级结构失败: ${error instanceof Error ? error.message : '未知错误'}`}]
};
}
}
);
// 查看系统窗口详细信息
server.tool(
'window-info',
'展示系统窗口的详细信息',
{
...deviceSelectionParams
},
async ({ deviceId, useUsb, useEmulator }) => {
try {
const result = await executeAdbCommand('shell dumpsys window windows', { deviceId, useUsb, useEmulator });
return {
content: [{type: 'text', text: result}]
};
} catch (error) {
return {
isError: true,
content: [{type: 'text', text: `获取窗口信息失败: ${error instanceof Error ? error.message : '未知错误'}`}]
};
}
}
);
// 查看SurfaceFlinger信息
server.tool(
'surface-flinger',
'展示当前设备的图层信息',
{
...deviceSelectionParams
},
async ({ deviceId, useUsb, useEmulator }) => {
try {
const result = await executeAdbCommand('shell dumpsys SurfaceFlinger', { deviceId, useUsb, useEmulator });
return {
content: [{type: 'text', text: result}]
};
} catch (error) {
return {
isError: true,
content: [{type: 'text', text: `获取SurfaceFlinger信息失败: ${error instanceof Error ? error.message : '未知错误'}`}]
};
}
}
);
// 查看触摸输入信息
server.tool(
'input-info',
'查看触摸输入事件派发等信息',
{
...deviceSelectionParams
},
async ({ deviceId, useUsb, useEmulator }) => {
try {
const result = await executeAdbCommand('shell dumpsys input', { deviceId, useUsb, useEmulator });
return {
content: [{type: 'text', text: result}]
};
} catch (error) {
return {
isError: true,
content: [{type: 'text', text: `获取输入信息失败: ${error instanceof Error ? error.message : '未知错误'}`}]
};
}
}
);
// 实时查看输入事件
server.tool(
'monitor-events',
'实时查看设备输入事件',
{
...deviceSelectionParams,
timeout: z.number().optional().default(5).describe('监控时间(秒)')
},
async ({ deviceId, useUsb, useEmulator, timeout }) => {
try {
// 使用timeout命令限制执行时间,避免命令一直运行
const result = await executeAdbCommand(`shell timeout ${timeout} getevent -lrt`, { deviceId, useUsb, useEmulator });
return {
content: [{type: 'text', text: result || `没有捕获到输入事件(监控了${timeout}秒)`}]
};
} catch (error) {
return {
isError: true,
content: [{type: 'text', text: `监控输入事件失败: ${error instanceof Error ? error.message : '未知错误'}`}]
};
}
}
);
// 查看显示相关信息
server.tool(
'display-info',
'查看设备显示相关信息',
{
...deviceSelectionParams
},
async ({ deviceId, useUsb, useEmulator }) => {
try {
const result = await executeAdbCommand('shell dumpsys display', { deviceId, useUsb, useEmulator });
return {
content: [{type: 'text', text: result}]
};
} catch (error) {
return {
isError: true,
content: [{type: 'text', text: `获取显示信息失败: ${error instanceof Error ? error.message : '未知错误'}`}]
};
}
}
);
// 查看电池信息
server.tool(
'battery-info',
'查看设备电池状态信息',
{
...deviceSelectionParams
},
async ({ deviceId, useUsb, useEmulator }) => {
try {
const result = await executeAdbCommand('shell dumpsys battery', { deviceId, useUsb, useEmulator });
return {
content: [{type: 'text', text: result}]
};
} catch (error) {
return {
isError: true,
content: [{type: 'text', text: `获取电池信息失败: ${error instanceof Error ? error.message : '未知错误'}`}]
};
}
}
);
// 查看网络状态
server.tool(
'network-info',
'查看设备网络状态信息',
{
...deviceSelectionParams
},
async ({ deviceId, useUsb, useEmulator }) => {
try {
const result = await executeAdbCommand('shell dumpsys connectivity', { deviceId, useUsb, useEmulator });
return {
content: [{type: 'text', text: result}]
};
} catch (error) {
return {
isError: true,
content: [{type: 'text', text: `获取网络状态失败: ${error instanceof Error ? error.message : '未知错误'}`}]
};
}
}
);
// 查看系统服务列表
server.tool(
'list-services',
'列出所有可用的系统服务',
{
...deviceSelectionParams
},
async ({ deviceId, useUsb, useEmulator }) => {
try {
const result = await executeAdbCommand('shell dumpsys -l', { deviceId, useUsb, useEmulator });
return {
content: [{type: 'text', text: result}]
};
} catch (error) {
return {
isError: true,
content: [{type: 'text', text: `获取服务列表失败: ${error instanceof Error ? error.message : '未知错误'}`}]
};
}
}
);
// 查看内存使用情况
server.tool(
'memory-info',
'查看设备内存使用情况',
{
...deviceSelectionParams,
packageName: z.string().optional().describe('应用包名,如果指定则只查看该应用的内存使用情况')
},
async ({ deviceId, useUsb, useEmulator, packageName }) => {
try {
let cmd = 'shell dumpsys meminfo';
if (packageName) {
cmd += ` ${packageName}`;
}
const result = await executeAdbCommand(cmd, { deviceId, useUsb, useEmulator });
return {
content: [{type: 'text', text: result}]
};
} catch (error) {
return {
isError: true,
content: [{type: 'text', text: `获取内存信息失败: ${error instanceof Error ? error.message : '未知错误'}`}]
};
}
}
);
// 查看CPU使用情况
server.tool(
'cpu-info',
'查看设备CPU使用情况',
{
...deviceSelectionParams,
packageName: z.string().optional().describe('应用包名,如果指定则只查看该应用的CPU使用情况')
},
async ({ deviceId, useUsb, useEmulator, packageName }) => {
try {
let cmd = 'shell dumpsys cpuinfo';
if (packageName) {
cmd += ` | grep ${packageName}`;
}
const result = await executeAdbCommand(cmd, { deviceId, useUsb, useEmulator });
return {
content: [{type: 'text', text: result || '没有找到相关CPU信息'}]
};
} catch (error) {
return {
isError: true,
content: [{type: 'text', text: `获取CPU信息失败: ${error instanceof Error ? error.message : '未知错误'}`}]
};
}
}
);
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("ADB MCP Server running on stdio");
}
main().catch((error) => {
console.error("Fatal error in main():", error);
process.exit(1);
});