iOS Automation
Автоматизируйте сложные рабочие процессы разработки iOS с помощью iOS Automation. Дайте AI-ассистентам возможность управлять симуляторами, управлять приложениями, автоматизировать UI и проводить всестороннее тестирование доступности на устройствах iOS.
Инструмент iOS Automation предоставляет надёжное решение на основе Python, предназначенное для предоставления ИИ-ассистентам программного контроля над симуляторами iOS. Он оптимизирует разработку, тестирование и автоматизацию iOS, позволяя ИИ управлять состояниями симуляторов, устанавливать и запускать приложения, взаимодействовать с элементами UI, выполнять тестирование доступности и делать скриншоты. Построенный на устойчивой многоуровневой архитектуре, он обеспечивает надёжность, расширяемость и эффективную интеграцию с нативными инструментами macOS, такими как simctl и AppleScript, что способствует продвижению сложных рабочих процессов iOS на основе ИИ.
Ключевые возможности
Варианты использования
A comprehensive Model Context Protocol (MCP) server for iOS development automation. This Python implementation enables AI assistants to interact with iOS simulators, perform accessibility testing, manage apps, and automate complex iOS workflows.
graph TB
subgraph "Claude Desktop Environment"
CD[Claude Desktop]
CDConfig[claude_desktop_config.json<br/>User Configuration]
CDLogs[~/Library/Logs/Claude/]
end
subgraph "MCP Server Layer"
MCPServer[iOS MCP Server<br/>ios_mcp_server.py]
VEnv[Python Virtual Environment<br/>ios_mcp_env/]
MCPTools[13 iOS Automation Tools]
end
subgraph "iOS Simulator Layer"
Simulator[iOS Simulator<br/>Any iPhone/iPad Model]
TestApps[Test Applications<br/>User Apps & System Apps]
SimulatorTools[simctl Commands]
end
subgraph "macOS System Layer"
AppleScript[AppleScript<br/>UI Automation]
Accessibility[Accessibility Permissions<br/>Terminal.app]
Screenshots[Screenshot Storage<br/>/tmp/]
end
subgraph "Tool Categories"
SimMgmt[Simulator Management<br/>• list_simulators<br/>• boot_simulator<br/>• shutdown_simulator<br/>• get_simulator_state]
AppMgmt[App Management<br/>• launch_app<br/>• terminate_app<br/>• install_app<br/>• list_installed_apps]
UIAuto[UI Automation<br/>• tap_coordinate<br/>• tap_element<br/>• type_text<br/>• get_accessibility_tree]
Capture[Screen Capture<br/>• take_screenshot]
end
%% Connections
CD --> MCPServer
CDConfig -.-> CD
MCPServer --> VEnv
MCPServer --> MCPTools
MCPServer --> CDLogs
MCPTools --> SimMgmt
MCPTools --> AppMgmt
MCPTools --> UIAuto
MCPTools --> Capture
SimMgmt --> SimulatorTools
AppMgmt --> SimulatorTools
UIAuto --> AppleScript
Capture --> SimulatorTools
SimulatorTools --> Simulator
AppleScript --> Accessibility
AppleScript --> Simulator
Simulator --> TestApps
Capture --> Screenshots
- Claude Desktop → MCP Server (JSON-RPC over stdio)
- MCP Server → simctl/AppleScript (Command execution)
- System Tools → iOS Simulator (Direct automation)
- Results/Screenshots → Claude Desktop (Response data)
The iOS MCP Server follows a layered architecture designed for:
- Reliability: Robust error handling and graceful failure recovery
- Extensibility: Modular tool design for easy feature additions
- Performance: Asynchronous operations and efficient resource usage
- Security: Sandboxed execution with controlled system access
┌─────────────────────────────────────────────────────────┐
│ Claude Desktop │
│ ┌─────────────────────────────────────────────────┐ │
│ │ AI Assistant │ │
│ │ • Natural language processing │ │
│ │ • Intent recognition │ │
│ │ • Context management │ │
│ └─────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────┘
│
JSON-RPC over stdio
│
┌───────────────────────────────────���─────────────────────┐
│ MCP Server │
│ ┌─────────────────────────────────────────────────┐ │
│ │ Protocol Handler │ │
│ │ • JSON-RPC message parsing │ │
│ │ • Tool discovery & registration │ │
│ │ • Resource management │ │
│ │ • Error handling & logging │ │
│ └─────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────┐
│ Tool Manager │
│ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Simulator │ │ App │ │ UI │ │
│ │ Management │ │ Management │ │ Automation │ │
│ │ Tools │ │ Tools │ │ Tools │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────┐ │
│ │ Screen Capture Tools │ │
│ └─────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────┐
│ System Adapters │
│ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ simctl │ │ AppleScript │ │ File System │ │
│ │ Command │ │ Automation │ │ Operations │ │
│ │ Executor │ │ Engine │ │ │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
└─────────────────────────────────────────────────────────┘
│
Native macOS APIs
│
┌───────────────────────────────────────���─────────────────┐
│ iOS Simulator │
│ ┌─────────────────────────────────────────────────┐ │
│ │ Target Applications │ │
│ │ • User apps under test │ │
│ │ • System apps and services │ │
│ │ • UI accessibility hierarchy │ │
│ └─────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────┘
Each tool implements the command pattern for:
- Encapsulation: Tool logic is self-contained
- Undo/Redo: Future support for operation reversal
- Logging: Comprehensive audit trail
- Error Recovery: Graceful handling of failures
# Abstract interface for all system operations
class SystemAdapter:
async def execute_command(self, command: str) -> Result
# Concrete implementations
class SimctlAdapter(SystemAdapter):
# Handles iOS Simulator operations
class AppleScriptAdapter(SystemAdapter):
# Handles UI automation via AppleScriptclass ToolFactory:
def create_tool(self, tool_type: str) -> Tool:
# Dynamic tool instantiation based on type┌─────────────────────────────────────────────────────────┐
│ Error Handling │
│ │
│ Client Error │ Server Error │ System Error │
│ ┌─────────────┐ │ ┌─────────────┐ │ ┌─────────────┐ │
│ │ Validation │ │ │ Internal │ │ │ macOS │ │
│ │ Errors │ │ │ Processing │ │ │ System API │ │
│ │ │ │ │ Errors │ │ │ Errors │ │
│ └─────────────┘ │ └─────────────┘ │ └─────────────┘ │
│ │ │ │ │ │ │
│ └──────────┼────────┼──────────┼────────┘ │
│ │ │ │ │
│ ┌───────────────��─────────────────────────────────────┐ │
│ │ Centralized Error Handler │ │
│ │ • Categorization and severity assessment │ │
│ │ • Structured logging with context │ │
│ │ • User-friendly error messages │ │
│ │ • Automatic retry for transient failures │ │
│ └─────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────┘
- Structured logging: JSON format with contextual metadata
- Performance metrics: Execution time tracking for each tool
- Audit trail: Complete record of all operations
- Debug information: Detailed system state capture
- Connection pooling: Efficient use of system resources
- Memory management: Automatic cleanup of temporary files
- Concurrent execution: Thread-safe operations where applicable
- Rate limiting: Protection against excessive API calls
┌─────────────────────────────────────────────────────────┐
│ Security Boundaries │
│ │
│ MCP Server Sandbox │
│ ┌─────────────────────────────────────────────────┐ │
│ │ • Limited file system access │ │
│ │ • Controlled subprocess execution │ │
│ │ • No network access (stdio only) │ │
│ │ • Isolated virtual environment │ │
│ └─────────────────────────────────────────────────┘ │
│ │ │
│ Controlled Escalation │
│ │ │
│ macOS System Permissions │
│ ┌─────────────────────────────────────────────────┐ │
│ │ • Accessibility API access │ │
│ │ • iOS Simulator control │ │
│ │ • Screen capture permissions │ │
│ │ • AppleScript execution rights │ │
│ └─────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────┘
- Multiple simulator support: Concurrent operations across simulators
- Load balancing: Distribution of operations across available resources
- Session management: Isolated contexts for different automation tasks
- Async operations: Non-blocking I/O for improved throughput
- Resource optimization: Efficient memory and CPU usage
- Caching: Intelligent caching of expensive operations
The architecture supports extension through:
- Custom Tool Development: Plugin-style tool addition
- Protocol Extensions: Additional MCP resource types
- System Adapters: Support for additional automation backends
- Output Formats: Customizable response formatting
- Integration Hooks: CI/CD and external system integration
The following sequence diagram shows the detailed interaction flow for a typical iOS automation workflow:
This diagram illustrates:
- MCP Communication: JSON-RPC protocol between Claude Desktop and the iOS MCP Server
- Tool Execution: How iOS automation commands are processed and executed
- System Integration: Interaction with iOS Simulator via simctl and AppleScript
- Response Flow: How results and screenshots are returned to the AI assistant
See the iOS MCP Server in action:
Demo showing Claude Desktop automatically controlling iOS Simulator: launching apps, taking screenshots, tapping UI elements, and typing text through natural language commands.
🎥 Watch on YouTube | 📥 Download Original (43MB)
- ✅ List all available iOS simulators
- ✅ Boot/shutdown simulators programmatically
- ✅ Take screenshots of simulator screens
- ✅ Tap at specific coordinates
- ✅ Get real-time simulator state
- ✅ Install apps on simulators
- ✅ Launch apps with bundle identifiers
- ✅ Monitor app lifecycle
- ✅ Extract accessibility tree from running apps
- ✅ Parse UI hierarchy for automated testing
- ✅ Enable AI-driven UI interaction
- ✅ Access simulator system logs
- ✅ Real-time resource monitoring
- ✅ Comprehensive error handling
- macOS 13.0+
- Python 3.8+
- Xcode (for iOS Simulator)
- iOS Simulator (included with Xcode)
git clone <your-repo-url>
cd mcp-server-demo-proj
# Run the automated setup script
python3 automated_setup.pyThe automated setup will:
- ✅ Create and configure virtual environment
- ✅ Install all dependencies
- ✅ Configure Claude Desktop automatically
- ✅ Check for Cursor IDE compatibility
- ✅ Create launcher scripts
- ✅ Run comprehensive tests
Then just restart Claude Desktop and you're ready to go!
git clone <your-repo-url>
cd mcp-server-demo-proj
python3 -m venv ios_mcp_env
source ios_mcp_env/bin/activate
pip install -r requirements.txt# Test server imports correctly
python3 -c "import ios_mcp_server; print('✅ Server ready!')"
# Run diagnostic script
python3 debug_mcp_setup.py- Copy the example configuration:
cp claude_desktop_config.example.json claude_desktop_config.json- Update the paths in
claude_desktop_config.jsonto match your project location:
{
"mcpServers": {
"ios-automation": {
"command": "/YOUR/PROJECT/PATH/ios_mcp_env/bin/python3",
"args": ["/YOUR/PROJECT/PATH/ios_mcp_server.py"],
"env": {
"PYTHONPATH": "/YOUR/PROJECT/PATH"
}
}
}
}- Copy to Claude Desktop config location:
cp claude_desktop_config.json "$HOME/Library/Application Support/Claude/claude_desktop_config.json"- Restart Claude Desktop
- Claude Desktop - Full native MCP support
- Manual CLI - Direct server execution for testing
- Cursor IDE - No native MCP support yet (as of 2024)
- Continue.dev - VS Code extension with potential MCP integration
- Zed Editor - May add MCP support in future versions
While Cursor doesn't natively support MCP yet, you can:
- Use the automated setup to configure everything
- Use Claude Desktop alongside Cursor for AI assistance
- Run the MCP server manually for testing:
./start_mcp_server.sh
# Start server manually for testing
./start_mcp_server.sh
# In another terminal, test specific tools
python3 -c "
import asyncio
import sys
sys.path.insert(0, '.')
import ios_mcp_server
# Test your tools here
"If the server starts but Claude Desktop doesn't recognize it:
# Verify the config file exists
ls -la "$HOME/Library/Application Support/Claude/claude_desktop_config.json"
# Check the content
cat "$HOME/Library/Application Support/Claude/claude_desktop_config.json"Make sure all paths in your config are absolute paths and actually exist:
# Check if Python executable exists
ls -la /YOUR/PROJECT/PATH/ios_mcp_env/bin/python3
# Check if the script exists
ls -la /YOUR/PROJECT/PATH/ios_mcp_server.py
# Check if the project directory exists
ls -la /YOUR/PROJECT/PATH/# Run the automated diagnostic to check your setup
python3 debug_mcp_setup.py# Test if the server can import without errors
cd /YOUR/PROJECT/PATH
source ios_mcp_env/bin/activate
python3 -c "import ios_mcp_server; print('✅ Server imports successfully')"# View Claude Desktop logs for MCP errors
tail -f ~/Library/Logs/Claude/mcp*.log-
"Connected to Claude Desktop" but tools don't appear
- Restart Claude Desktop completely (quit and reopen)
- Clear Claude Desktop cache:
rm -rf ~/Library/Caches/Claude
-
Permission denied errors
- Make sure Python executable is executable:
chmod +x ios_mcp_env/bin/python3 - Check if Terminal has accessibility permissions (System Preferences → Security & Privacy → Accessibility)
- Make sure Python executable is executable:
-
Path not found errors
- Use absolute paths only (no
~or relative paths) - Verify paths exist and are accessible
- Use absolute paths only (no
-
ImportError for mcp module
- Reinstall in virtual environment:
pip install --upgrade mcp - Check virtual environment activation:
which python3should show your venv path
- Reinstall in virtual environment:
-
Server imports but tools don't appear
- Run the diagnostic script:
python3 debug_mcp_setup.py - Check Claude Desktop logs for errors
- Run the diagnostic script:
Replace with your actual paths:
{
"mcpServers": {
"ios-automation": {
"command": "/Users/yourusername/projects/mcp-server-demo-proj/ios_mcp_env/bin/python3",
"args": ["/Users/yourusername/projects/mcp-server-demo-proj/ios_mcp_server.py"],
"env": {
"PYTHONPATH": "/Users/yourusername/projects/mcp-server-demo-proj"
}
}
}
}| Tool | Description | Parameters |
|---|---|---|
list_simulators |
List all iOS simulators | None |
boot_simulator |
Boot a simulator | device_id |
shutdown_simulator |
Shutdown a simulator | device_id |
get_simulator_state |
Get real-time simulator status | device_id (optional) |
| Tool | Description | Parameters |
|---|---|---|
launch_app |
Launch app by bundle ID | bundle_id, device_id (optional) |
terminate_app |
Terminate running app | bundle_id, device_id (optional) |
install_app |
Install app on simulator | app_path, device_id (optional) |
list_installed_apps |
List all installed apps | device_id (optional) |
| Tool | Description | Parameters |
|---|---|---|
tap_coordinate |
Tap at specific coordinates | x, y, device_id (optional) |
tap_element |
Tap UI element by identifier | identifier, device_id (optional) |
type_text |
Type text into focused field | text, device_id (optional) |
get_accessibility_tree |
Get UI hierarchy | device_id (optional), format (optional) |
| Tool | Description | Parameters |
|---|---|---|
take_screenshot |
Capture simulator screen | save_path (optional) |
| Resource | Description | URI |
|---|---|---|
| Simulator State | Current simulator status | simulator://current-state |
| Accessibility Tree | Live UI hierarchy | accessibility://hierarchy |
| Simulator Logs | System and app logs | logs://simulator |
"List all available iOS simulators and boot an iPhone 15 Pro"
"Install my app from ~/MyApp.app, launch it, take a screenshot, and show me the accessibility tree"
"Boot iPhone 14 simulator, take a screenshot, tap the center of the screen, wait 2 seconds, then take another screenshot to see what changed"
"Show me the current simulator logs and tell me if there are any crash reports in the last hour"
mcp-server-demo-proj/
├── ios_mcp_server.py # Main Python MCP server
├── debug_mcp_setup.py # Setup diagnostic script
├── requirements.txt # Python dependencies
├── claude_desktop_config.example.json # Configuration template
├── ios_mcp_env/ # Virtual environment
├── test_doc_retrival_agent.py # Test automation script
├── test_ios_mcp.sh # Shell test script
├── mobile_mcp.mov # Demo video (43MB)
├── sequence_.png # Sequence diagram
├── README.md # This file
└── LICENSE # Project license
- MCP Python SDK - Official MCP implementation
- Apple's
simctl- iOS Simulator command line tools AppleScript- macOS UI automationasyncio- Asynchronous Python execution
# Setup virtual environment
python3 -m venv ios_mcp_env
source ios_mcp_env/bin/activate
# Install dependencies
pip install -r requirements.txt
# Test server
python3 -c "import ios_mcp_server; print('✅ Server ready!')"
# Run diagnostic
python3 debug_mcp_setup.pyAdd new tools by extending the handle_call_tool function:
elif name == "your_custom_tool":
# Your implementation here
return [types.TextContent(type="text", text="Tool executed!")]This server can be integrated into your CI/CD pipeline for automated iOS testing:
# GitHub Actions example
- name: Setup iOS MCP Server
run: |
python3 -m venv ios_mcp_env
source ios_mcp_env/bin/activate
pip install -r requirements.txt
- name: Run iOS Automation Tests
run: |
source ios_mcp_env/bin/activate
python3 test_doc_retrival_agent.pyThis project can be extended with:
- Additional iOS automation tools
- Physical device support (requires additional setup)
- Advanced accessibility analysis
- Integration with TestFlight
- Custom UI testing frameworks
Built with ❤️ for iOS development automation using the Model Context Protocol.
- MCP Community for the Python SDK
- mobile-next/mobile-mcp for inspiration
- Apple's iOS Simulator and development tools
Ready to automate your iOS development workflow? Let's build something amazing! 🚀
iOS Automation MCP Server
Сервер для автоматизации iOS-симуляторов через протокол MCP (Model Context Protocol). Позволяет AI-ассистентам (например, Claude Desktop) управлять симуляторами, запускать приложения, выполнять UI-тесты и делать скриншоты — всё через естественно-языковые команды.
Требования
- macOS 13.0+
- Python 3.8+
- Xcode (включает iOS Simulator)
Быстрый старт
Автоматическая установка (рекомендуется)
git clone <url-репозитория>
cd mcp-server-demo-proj
python3 automated_setup.py
Скрипт создаст виртуальное окружение, установит зависимости, настроит Claude Desktop и проверит совместимость.
Ручная установка
- Клонируйте репозиторий и создайте виртуальное окружение:
git clone <url-репозитория>
cd mcp-server-demo-proj
python3 -m venv ios_mcp_env
source ios_mcp_env/bin/activate
pip install -r requirements.txt
- Проверьте, что сервер импортируется корректно:
python3 -c "import ios_mcp_server; print('Сервер готов!')"
- Настройте Claude Desktop (см. ниже).
Конфигурация для Claude Desktop
Скопируйте пример конфигурации:
cp claude_desktop_config.example.json claude_desktop_config.json
Отредактируйте claude_desktop_config.json, указав абсолютные пути к вашему проекту:
{
"mcpServers": {
"ios-automation": {
"command": "/ПОЛНЫЙ/ПУТЬ/ios_mcp_env/bin/python3",
"args": ["/ПОЛНЫЙ/ПУТЬ/ios_mcp_server.py"],
"env": {
"PYTHONPATH": "/ПОЛНЫЙ/ПУТЬ"
}
}
}
}
Скопируйте файл в директорию Claude Desktop:
cp claude_desktop_config.json "$HOME/Library/Application Support/Claude/claude_desktop_config.json"
Перезапустите Claude Desktop.
Возможности
Управление симуляторами
list_simulators— список доступных симуляторовboot_simulator— запуск симулятораshutdown_simulator— остановка симулятораget_simulator_state— состояние симулятора
Управление приложениями
launch_app— запуск приложения по bundle IDterminate_app— завершение приложенияinstall_app— установка приложенияlist_installed_apps— список установленных приложений
UI-автоматизация
tap_coordinate— тап по координатамtap_element— тап по элементу (по accessibility-идентификатору)type_text— ввод текстаget_accessibility_tree— получение дерева доступности (для анализа UI)
Скриншоты
take_screenshot— снимок экрана симулятора
Архитектура
Сервер написан на Python и общается с AI-ассистентом по протоколу JSON-RPC через stdio. Для взаимодействия с iOS Simulator используются:
simctl— команды управления симулятором и приложениями- AppleScript — автоматизация UI (тапы, ввод текста)
Реализована асинхронная обработка команд, централизованная обработка ошибок и структурированное логирование. Каждый инструмент изолирован и следует паттерну «Команда».
Безопасность
Сервер работает в изолированном виртуальном окружении с ограниченным доступом к файловой системе. Для работы с UI симулятора требуется разрешение Accessibility API для Terminal.app (выдаётся в системных настройках macOS).
Совместимость с MCP-клиентами
- Claude Desktop — полная поддержка
- Ручной CLI — для отладки и тестирования
- Cursor IDE — нативная поддержка MCP отсутствует (по состоянию на 2024)
- Continue.dev, Zed Editor — возможна интеграция в будущем
Демо
Видео работы сервера: YouTube | Исходный файл (43MB)
Каковы ключевые преимущества использования iOS Automation?
Ключевые преимущества включают оптимизацию iOS-разработки, ускорение циклов тестирования, реализацию продвинутых сценариев автоматизации на базе ИИ, повышение надежности за счет надежной обработки ошибок и обеспечение безопасной работы в изолированной среде.
Что такое iOS Automation?
iOS Automation — это полнофункциональный сервер протокола Model Context Protocol (MCP), который позволяет ИИ-ассистентам автоматизировать сложные рабочие процессы iOS-разработки и тестирования за счет прямого взаимодействия с iOS-симуляторами.
Как он использует ИИ для автоматизации?
Он выступает в роли моста, позволяя ИИ-ассистентам (например, Claude Desktop) отправлять команды и получать данные от iOS-симуляторов. Это позволяет ИИ выполнять такие задачи, как взаимодействие с UI, управление приложениями и программное извлечение данных.
Какие конкретные задачи может автоматизировать iOS Automation?
Он автоматизирует широкий спектр задач, включая запуск/остановку симуляторов, установку/запуск/завершение приложений, выполнение AI-управляемых взаимодействий с UI (нажатие, ввод текста), извлечение деревьев доступности и создание снимков экрана в реальном времени.
Можно ли использовать этот инструмент для тестирования доступности?
Да, ключевая функциональность iOS Automation — это возможность упростить тестирование доступности. ИИ-ассистенты могут использовать инструмент для извлечения деревьев доступности и взаимодействия с элементами UI, делая комплексные проверки доступности более эффективными.
Комментарии
Комментариев пока нет. Будьте первым.