MCP HubMCP Hub
r-huijts

xcode-mcp-server

by: r-huijts

MCP Server implementation for Xcode integration

158created 16/01/2025
Visit
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:

  1. Clone the repository:

    git clone https://github.com/r-huijts/xcode-mcp-server.git
    cd xcode-mcp-server
    
  2. Verify prerequisites:

    • Xcode and Xcode Command Line Tools
    • Node.js v16 or higher
    • npm
    • Ruby (for CocoaPods support)
    • CocoaPods (optional)
  3. Install dependencies:

    npm install
    
  4. Build the project:

    npm run build
    
  5. Create and edit a configuration file .env with at least:

    PROJECTS_BASE_DIR=/path/to/your/projects
    DEBUG=false
    
  6. (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

  1. Start the Xcode MCP server
  2. Configure your AI assistant to use the server URL (typically http://localhost:3000)
  3. 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

  1. Server Implementation: Handles tool registration and request processing.
  2. Path Management: Validates all paths against allowed directories for security.
  3. Project Management: Detects and manages different Xcode project types:
    • Standard Xcode projects (.xcodeproj)
    • Workspaces (.xcworkspace)
    • Swift Package Manager projects (Package.swift)
  4. Directory State: Maintains active directory context for relative paths.
  5. Tool Registry: Organizes tools into categories for Xcode operations.

Request Flow

  1. AI assistant sends a tool execution request.
  2. Server validates parameters and permissions.
  3. Invokes appropriate tool handler.
  4. Executes requested operation (often native Xcode commands).
  5. Returns formatted results.
  6. 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:

  1. Fork the repository
  2. Create a feature branch
  3. Commit your changes
  4. Push the branch
  5. 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

  1. Identify the category in src/tools/
  2. Implement the tool with Zod schema validation
  3. Register it in the category's index.ts
  4. Add error handling with specific messages
  5. 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

  1. Start server with debug logging: npm start -- --debug
  2. Check console and server logs for detailed errors and request info.
  3. 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