xcode-mcp-server

repository·master·Indexed 18 days ago

https://github.com/r-huijts/xcode-mcp-server

An MCP (Model Context Protocol) server version 1.0.3 that provides AI assistants with integration into the Xcode ecosystem. It enables project management, file operations, builds, testing, and simulator control for .xcodeproj, .xcworkspace, and Swift Package Manager projects. The server includes a secure path management system and a tool registry for interacting with Xcode via native commands.

Tokens
22.8K
Snippets
91
Records
132
Agent score
61%

What's inside xcode-mcp-server

  1. Overview of Xcode MCP Server Modules

    master

    The Xcode MCP Server is organized into several functional modules that allow an AI agent or developer to interact with Xcode environments. The core modules include:

    • Project Management: Navigating and managing .xcodeproj, .xcworkspace, and Swift Package Manager projects.
    • File Operations: Securely reading, writing, and managing files within allowed directories.
    • Build & Testing: Compiling projects and running tests using xcodebuild.
    • CocoaPods Integration: Managing dependencies via the CocoaPods CLI.
    • Swift Package Manager: Managing SPM dependencies and executing SPM commands.
    • Simulator Tools: Interacting with iOS simulators via simctl.
    • Xcode Utilities: Running Xcode-specific tools via xcrun.
    • Path Management: A security layer for validating file access and directory navigation.
  2. Manage Project Paths and Directories

    master

    You can navigate the project file system using path management tools. This includes changing the active directory, pushing/popping directories onto a stack (to return to a previous location), resolving relative paths to absolute paths, and expanding tilde (~) notation for home directory paths.

    // Change directory to a specific project folder
    Change directory to the project's Source directory.
    
    // Push/Pop directory stack
    Push directory to the Tests directory. I'll want to come back to where I am now later.
    Pop directory to return to where I was before.
    
    // Resolve paths
    Resolve the path ../Resources/images
    Resolve the path ~/XcodeMCPTests/TestApp
  3. How to safely run external commands

    master

    To prevent OS Command Injection (CWE-78), all subprocess invocations must use runExecFile from src/utils/execFile.js with an argument array.

    Key Rules:

    • Never use child_process.exec() or interpolate user-controlled/path-derived strings into a shell command string.
    • Always pass arguments as a literal array. This ensures arguments are passed directly to the process without being parsed by a shell.
    • Avoid using cd "${dir}" && ... to change directories. Instead, use the options.cwd property in the runExecFile options object.

    Comparison:

    • Safe: runExecFile("xcrun", ["lldb", "-o", userCommand, "-b"])
    • Unsafe: exec("xcrun lldb ${userArgs}")
    // Safe pattern
    runExecFile("xcrun", ["lldb", "-o", userCommand, "-b"]);
    
    // Safe directory management
    runExecFile("command", ["arg1"], { cwd: "/path/to/dir" });
  4. Understand Security Boundaries and PathAccessError

    master

    The system enforces strict security boundaries to prevent unauthorized filesystem access. If an operation attempts to access a path outside these boundaries, a PathAccessError is thrown.

    Permitted Boundaries:

    1. Project Base Directory: The root configured for all project operations.
    2. Active Project Directory: The directory of the currently active project.
    3. Server Directory: Read operations (but not write) may be allowed within the server's own directory.

    Error Types:

    • PathAccessError: Path is outside permitted boundaries.
    • FileOperationError: A file operation failed.
    • ProjectNotFoundError: No active project is set.
  5. Perform File Operations

    master

    The server allows for standard file system operations within the context of an active project. Supported operations include reading, writing, copying, moving, deleting, creating directories, listing directory contents (including hidden files), and searching for files based on patterns.

    // Read a file
    Show me the contents of AppDelegate.swift.
    
    // Write/Create a file
    Can you create a new file called TestModel.swift with a basic class structure?
    
    // Move/Copy/Delete
    Copy AppDelegate.swift to AppDelegateCopy.swift
    Move TestModel.swift into a directory called 'Models'
    Delete the file AppDelegateCopy.swift
    
    // List and Find
    List files in the current directory with detailed information and include hidden files.
    Find all Swift files containing "View" in their name.
  6. Manage Swift Package Manager (SPM) Dependencies

    master

    The server supports Swift Package Manager workflows, including initializing new packages, adding dependencies with specific version ranges, updating packages, building, testing (with suite filtering), and inspecting the dependency graph.

    // Initialize
    Initialize a new Swift Package called "TestTool" as an executable with XCTest support.
    
    // Add/Update dependencies
    Add the Swift package at https://github.com/apple/swift-log.git with version range: 1.0.0 to 1.5.0
    Update the swift-log package to the latest version.
    
    // Build and Test
    Build the Swift package in release configuration.
    Run Swift package tests filtering for the "LoggingTests" test suite.
    
    // Inspect
    Show me the dependencies of this Swift package as a graph.
    Dump the Package.swift manifest as JSON.
  7. Use Xcode Utilities

    master

    The server includes several low-level Xcode utilities, such as running xcrun commands, compiling asset catalogs, attaching LLDB to a process, capturing performance traces, and generating app icons from source images.

    // System and Assets
    Run xcrun simctl list.
    Compile the Assets.xcassets catalog in my project.
    Generate app icons from my source image icon.png.
    
    // Debugging
    Attach LLDB to the process named "TestApp".
    Capture a 5-second performance trace of my app.
  8. How the Path Management System works

    master

    The path management system is a centralized architecture designed to handle file paths securely and consistently. It uses three core components to manage the lifecycle of a path operation:

    1. PathManager: The engine that handles normalization, expansion (like ~ or environment variables), security boundary enforcement, and validation.
    2. SafeFileOperations: A layer built on PathManager that executes actual file system actions (read, write, list) while ensuring every operation is validated against security rules.
    3. ProjectDirectoryState: A state manager that tracks the current active directory and maintains a directory stack to allow for intuitive navigation (push/pop).

    When a path is requested, the system follows a specific workflow: Input $\rightarrow$ Expansion (e.g., ~/docs to /home/user/docs) $\rightarrow$ Normalization (removing ../ or ./) $\rightarrow$ Resolution (resolving relative paths against the active directory) $\rightarrow$ Validation (checking security boundaries) $\rightarrow$ Operation.

    // Conceptual workflow overview
    const pathManager = new PathManager(config);
    const fileOps = new SafeFileOperations(pathManager);
    const dirState = new ProjectDirectoryState(pathManager);
  9. Manage Xcode Projects

    master

    The server provides tools to manage the lifecycle and context of Xcode projects, workspaces, and Swift Package Manager (SPM) projects. You can set a base directory for all projects, find existing projects, and switch between active projects. The server can also detect the project currently in focus in the Xcode UI.

    // Set projects base directory
    Can you set my Xcode projects directory to ~/XcodeMCPTests?
    
    // Find projects
    Find all Xcode projects in my projects directory, including workspaces and Swift Package Manager projects.
    
    // Set active project and open in Xcode
    Set my active project to ~/XcodeMCPTests/TestApp/TestApp.xcodeproj and open it in Xcode.
    
    // Detect active project from Xcode UI
    Can you detect which Xcode project I'm currently working on?
  10. How the Xcode MCP Server works

    master

    The Xcode MCP server provides a standardized interface for AI models to interact with Xcode projects using the Model Context Protocol. It uses a structured architecture to manage project types, file access, and tool execution.

    Core Components

    • Server Implementation: Handles tool registration and request processing.
    • Path Management: Validates all paths against allowed directories to ensure secure file access.
    • Project Management: Detects and manages .xcodeproj (Standard), .xcworkspace (Workspaces), and Package.swift (Swift Package Manager) projects.
    • Directory State: Maintains the active directory context for resolving relative paths.
    • Tool Registry: Organizes tools into logical categories (e.g., Project Management, File Operations, Build & Testing).

    Request Flow

    1. An AI assistant sends a tool execution request.
    2. The server validates parameters and permissions.
    3. The appropriate tool handler is invoked.
    4. The tool executes the operation (often via native Xcode commands).
    5. Results are formatted and returned to the assistant.

    Safety and Validation

    • Path Validation: Restricts file operations to allowed directories.
    • Parameter Validation: Uses Zod schemas to validate all input parameters.
    • Process Management: Executes external processes safely with error handling.
  11. Install the Xcode MCP Server manually

    master

    If you prefer explicit control or are setting up in a CI/CD environment, follow these manual steps:

    1. Clone the repository:
      git clone https://github.com/r-huijts/xcode-mcp-server.git
      cd xcode-mcp-server
    2. Install dependencies:
      npm install
    3. Build the project:
      npm run build
    4. Configure the environment by creating a .env file (see Configuration section).
    git clone https://github.com/r-huijts/xcode-mcp-server.git
    cd xcode-mcp-server
    npm install
    npm run build
  12. Best Practices for working with Xcode MCP Server

    master

    To get the most out of the Xcode MCP Server when working with an AI assistant, follow these guidelines:

    • Be Specific: Provide exact file names and clear requirements when requesting changes.
    • Use Directory Navigation: Leverage the provided tools to move through your project structure efficiently.
    • Verify Changes: Always review AI-generated changes before committing to production.
    • Incremental Changes: Request small, manageable updates rather than large, monolithic changes.
    • Provide Project Context: At the start of a session, give the AI an overview of your project's architecture.
    • Follow Up: Use clarifications if the AI's first attempt is incorrect.
    • Use Relative Paths: Refer to files using relative paths based on your current working directory.