xcode-mcp-server
by: r-huijts
MCP Server implementation for Xcode integration
πOverview
Purpose: The Xcode MCP Server serves as a bridge between AI capabilities and the Xcode development environment, facilitating intelligent assistance for code and project management.
Overview: The Xcode MCP Server follows a client-server architecture, enabling Claude to interact securely with local Xcode projects without exposing code to the internet. It allows for seamless integration of AI-driven tools within a secure workflow.
Key Features:
-
Intelligent Project Detection: Automatically connects to active Xcode projects and maintains workspace context, ensuring a smooth user experience.
-
Smart File Operations: Allows for reading and modifying various programming files while providing intelligent listing and search capabilities.
-
Project Management: Grants access to project configurations and schemes, enables analysis of source files, and supports building and testing functionality.
Xcode MCP Server
An MCP (Model Context Protocol) server providing comprehensive Xcode integration for AI assistants. This server enables AI agents to interact with Xcode projects, manage iOS simulators, and perform various Xcode-related tasks with enhanced error handling and support for multiple project types.
Features
Project Management
- Set active projects and get detailed project information
- Create new Xcode projects from templates (iOS, macOS, watchOS, tvOS)
- Add files to Xcode projects with target and group specification
- Parse workspace documents to find associated projects
- List available schemes in projects and workspaces
File Operations
- Read/write files with support for different encodings
- Handle binary files with base64 encoding/decoding
- Search for text content within files using patterns and regex
- Check file existence and get file metadata
- Create directory structures automatically
Build & Testing
- Build projects with customizable options
- Run tests with detailed failure reporting
- Analyze code for potential issues
- Clean build directories
- Archive projects for distribution
CocoaPods Integration
- Initialize CocoaPods in projects
- Install and update pods
- Add and remove pod dependencies
- Execute arbitrary pod commands
Swift Package Manager
- Initialize new Swift packages
- Add and remove package dependencies with various version requirements
- Update packages and resolve dependencies
- Generate documentation for Swift packages using DocC
- Run tests and build Swift packages
iOS Simulator Tools
- List available simulators with detailed information
- Boot and shut down simulators
- Install and launch apps on simulators
- Take screenshots and record videos
- Manage simulator settings and state
Xcode Utilities
- Execute Xcode commands via xcrun
- Compile asset catalogs
- Generate app icon sets from source images
- Trace app performance
- Export and validate archives for App Store submission
- Switch between different Xcode versions
Installation
Prerequisites
- macOS with Xcode 14.0 or higher installed
- Node.js 16 or higher
- npm or yarn
- Swift 5.5+ for Swift Package Manager features
- CocoaPods (optional, for CocoaPods integration)
Setup
Option 1: Automated Setup (Recommended)
Use the included setup script which automates the installation and configuration process:
# Make the script executable
chmod +x setup.sh
# Run the setup script
./setup.sh
The setup script will:
- Verify environment requirements (macOS, Xcode, Node.js, npm, Ruby, CocoaPods)
- Install dependencies (
npm install
) - Build the project (
npm run build
) - Create and configure a
.env
file with your preferences - Optionally configure Claude Desktop integration
Option 2: Manual Setup
Follow these steps for manual installation:
-
Clone the repository:
git clone https://github.com/r-huijts/xcode-mcp-server.git cd xcode-mcp-server
-
Verify prerequisites:
- Xcode and Xcode Command Line Tools
- Node.js v16 or higher
- npm
- Ruby (for CocoaPods support)
- CocoaPods (optional)
-
Install dependencies:
npm install
-
Build the project:
npm run build
-
Create and edit a configuration file
.env
with at least:PROJECTS_BASE_DIR=/path/to/your/projects DEBUG=false
-
(Optional) Configure Claude Desktop integration by editing or creating:
~/Library/Application Support/Claude/claude_desktop_config.json
with appropriate server command.
Setup Troubleshooting
- Ensure correct Node.js version (v16+)
- Reinstall dependencies with
npm install
if needed - Make sure Xcode Command Line Tools are installed (
xcode-select --install
) - Verify permissions for installation directory
- Validate
.env
file contents (paths should exist and be accessible) - Restart Claude Desktop if integration is configured and changes are made
Usage
Starting the Server
npm start
For development mode with automatic restarts:
npm run dev
Configuration Options
Configure via .env
file or command line arguments:
Example .env
:
PROJECTS_BASE_DIR=/path/to/your/projects
DEBUG=true
ALLOWED_PATHS=/path/to/additional/allowed/directory
PORT=8080
Example command line:
npm start -- --projects-dir=/path/to/your/projects --port=8080
Key Configuration Parameters
PROJECTS_BASE_DIR
/--projects-dir
: Base directory for projects (required)ALLOWED_PATHS
/--allowed-paths
: Additional allowed directories (comma-separated)PORT
/--port
: Server port (default: 3000)DEBUG
/--debug
: Enable debug logging (default: false)LOG_LEVEL
/--log-level
: Logging level (default: info)
Connecting to AI Assistants
- Start the Xcode MCP server
- Configure your AI assistant to use the server URL (typically
http://localhost:3000
) - The AI assistant can now access all Xcode tools provided by the server
Tool Documentation
For comprehensive tool documentation and usage examples, refer to the included documentation files in the docs/
directory.
Common Workflows
Setting Up a New Project
// Create a new iOS app project
await tools.create_xcode_project({
name: "MyAwesomeApp",
template: "ios-app",
outputDirectory: "~/Projects",
organizationName: "My Organization",
organizationIdentifier: "com.myorganization",
language: "swift",
includeTests: true,
setAsActive: true
});
// Add a Swift Package dependency
await tools.add_swift_package({
url: "https://github.com/Alamofire/Alamofire.git",
version: "from: 5.0.0"
});
Working with Files
// Read a file with specific encoding
const fileContent = await tools.read_file({
filePath: "MyAwesomeApp/AppDelegate.swift",
encoding: "utf-8"
});
// Write to a file
await tools.write_file({
path: "MyAwesomeApp/NewFile.swift",
content: "import Foundation\n\nclass NewClass {}\n",
createIfMissing: true
});
// Search for text in files
const searchResults = await tools.search_in_files({
directory: "MyAwesomeApp",
pattern: "*.swift",
searchText: "class",
isRegex: false
});
Building and Testing
// Build the project
await tools.build_project({
scheme: "MyAwesomeApp",
configuration: "Debug"
});
// Run tests
await tools.test_project({
scheme: "MyAwesomeApp",
testPlan: "MyAwesomeAppTests"
});
Project Structure
xcode-mcp-server/
βββ src/
β βββ index.ts # Entry point
β βββ server.ts # MCP server implementation
β βββ types/ # Type definitions
β β βββ index.ts # Core type definitions
β βββ utils/ # Utility functions
β β βββ errors.js # Error handling classes
β β βββ pathManager.ts # Path validation and management
β β βββ project.js # Project utilities
β β βββ simulator.js # Simulator utilities
β βββ tools/ # Tool implementations
β βββ project/ # Project management tools
β β βββ index.ts # Project creation, detection, file adding
β βββ file/ # File operation tools
β β βββ index.ts # File reading, writing, searching
β βββ build/ # Build and testing tools
β β βββ index.ts # Building, testing, analyzing
β βββ cocoapods/ # CocoaPods integration
β β βββ index.ts # Pod installation and management
β βββ spm/ # Swift Package Manager tools
β β βββ index.ts # Package management and documentation
β βββ simulator/ # iOS simulator tools
β β βββ index.ts # Simulator control and interaction
β βββ xcode/ # Xcode utilities
β βββ index.ts # Xcode version management, asset tools
βββ docs/ # Documentation
β βββ tools-overview.md # Comprehensive tool documentation
β βββ user-guide.md # Usage examples and best practices
βββ tests/ # Tests
βββ dist/ # Compiled code (generated)
How It Works
The Xcode MCP server uses the Model Context Protocol to provide a standardized interface for AI models to interact with Xcode projects. The server architecture includes:
Core Components
- Server Implementation: Handles tool registration and request processing.
- Path Management: Validates all paths against allowed directories for security.
- Project Management: Detects and manages different Xcode project types:
- Standard Xcode projects (.xcodeproj)
- Workspaces (.xcworkspace)
- Swift Package Manager projects (Package.swift)
- Directory State: Maintains active directory context for relative paths.
- Tool Registry: Organizes tools into categories for Xcode operations.
Request Flow
- AI assistant sends a tool execution request.
- Server validates parameters and permissions.
- Invokes appropriate tool handler.
- Executes requested operation (often native Xcode commands).
- Returns formatted results.
- Provides detailed error handling.
Safety Features
- Path validation restricts file operations to allowed directories.
- Detailed error messages aid troubleshooting.
- Parameter validation uses Zod schemas.
- Secure external process execution.
Project Type Support
- Standard Xcode projects
- Workspaces managing multiple projects
- Swift Package Manager projects
This allows seamless AI-assisted Xcode project management with security and detailed feedback.
Contributing
Contributions are welcome! To contribute:
- Fork the repository
- Create a feature branch
- Commit your changes
- Push the branch
- Open a Pull Request
Development Guidelines
- Follow existing code style and organization
- Add comprehensive error handling
- Write tests for new features
- Update documentation as needed
- Ensure compatibility with all supported project types
Adding New Tools
- Identify the category in
src/tools/
- Implement the tool with Zod schema validation
- Register it in the category's
index.ts
- Add error handling with specific messages
- Document the tool appropriately
Troubleshooting
Common Issues
- Path Access Errors: Verify requested paths are within allowed directories.
- Build Failures: Confirm Xcode command line tools are installed and updated.
- Tool Not Found: Check tool name correctness and registration.
- Parameter Validation Errors: Review parameter types and requirements.
Debugging
- Start server with debug logging:
npm start -- --debug
- Check console and server logs for detailed errors and request info.
- Test Xcode commands manually in terminal if needed.
License
This project is licensed under the MIT License.
Acknowledgments
- Model Context Protocol team for the MCP SDK
- Built with TypeScript and Node.js
- Uses Xcode command line tools and Swift Package Manager
- Thanks to all contributors for improving functionality and robustness