# MCP-MAC ARCHITECTURE
**Created**: September 11, 2025
**Last Updated**: September 11, 2025 (21:46)
**Purpose**: System design and technical implementation overview
---
## **SYSTEM OVERVIEW**
MCP-Mac is a Model Context Protocol (MCP) server that provides AI agents with controlled access to macOS applications through AppleScript automation.
### **High-Level Architecture**
```
AI Agent (Q CLI, etc.)
↓ MCP Protocol
MCP-Mac Server (Node.js/TypeScript)
↓ AppleScript Commands
macOS Applications (Finder, Mail, Contacts)
↓ User Data Access
Local macOS System
```
## **TECHNICAL IMPLEMENTATION**
### Project Structure Standards
```
mcp-mac/
├── package.json # Project dependencies and scripts
├── tsconfig.json # TypeScript configuration
├── src/
│ └── index.ts # MCP server entry point
├── tests/ # Automated test scripts
├── dist/ # Compiled JavaScript output
└── docs/ # Project documentation
```
### **TypeScript Configuration Requirements**
- **Target**: ES2022 for modern Node.js compatibility
- **Module**: ESNext with Node.js resolution
- **Strict Mode**: Enabled for type safety
- **Source Maps**: Required for debugging
### **MCP Server Implementation Standards**
- **Transport**: StdioServerTransport for CLI integration
- **Error Handling**: Proper null checking for MCP request arguments (`args?.property`)
- **Tool Registration**: All tools must be registered in ListToolsRequestSchema handler
- **Response Format**: Use MCP content array format with type/text structure
### **Build/Test Verification Process**
- [ ] **Build Verification**: `npm run build` must complete without TypeScript errors
- [ ] **Server Startup Test**: `npm start` must initialize without runtime errors
- [ ] **Tool Registration Test**: Server must list all implemented tools
- [ ] **Individual Tool Test**: Each tool must execute without errors
### **Buffer Management Standards**
- **Selective Property Retrieval**: Maximum 5-10 properties per AppleScript query
- **Multi-line Scripts**: Use variable assignment for complex property access
- **Output Size Limits**: Test tools with extensive data to verify buffer compliance
- **Chunked Operations**: Design multiple focused tools rather than single comprehensive tool
## **CORE COMPONENTS**
### **MCP Server (src/index.ts)**
- **Transport**: StdioServerTransport for CLI integration
- **Protocol**: Implements MCP standard for tool registration and execution
- **Error Handling**: Proper null checking and error propagation
- **Tool Registry**: Dynamic tool registration with parameter validation
### **AppleScript Execution Layer**
- **Command Execution**: Uses Node.js `child_process.exec` to run AppleScript
- **Output Processing**: Converts AppleScript results to user-friendly formats
- **Error Management**: Handles AppleScript errors and timeouts
- **Buffer Management**: Prevents stdout overflow with selective property retrieval
### **Application Interfaces**
#### **Finder Interface**
- **Selection Access**: Gets currently selected files/folders
- **Path Processing**: Converts AppleScript aliases to POSIX paths
- **UI Compatibility**: Removes system artifacts (`.localized` suffixes)
- **Type Detection**: Handles files vs directories differently
#### **Mail Interface**
- **Account Management**: Lists all configured email accounts
- **Inbox Monitoring**: Real-time unread message counts
- **Multi-Account Support**: Aggregates data across all accounts
- **State Synchronization**: No caching issues, always current
#### **Contacts Interface**
- **Search Functionality**: Substring-based contact search
- **Data Retrieval**: Selective property access to prevent buffer overflow
- **Duplicate Handling**: Returns "first match" for duplicate names
- **Field Management**: Handles missing/empty contact fields
## **DATA FLOW**
### **Tool Execution Flow**
1. **AI Request** → MCP server receives tool call with parameters
2. **Validation** → Parameter validation and permission checking
3. **AppleScript Generation** → Dynamic script creation based on tool and parameters
4. **Execution** → AppleScript runs against target macOS application
5. **Processing** → Raw output converted to user-friendly format
6. **Response** → Formatted result returned to AI agent
### **Error Handling Flow**
1. **AppleScript Errors** → Captured and categorized
2. **Buffer Overflow** → Prevented through selective property retrieval
3. **Application State** → Verified against UI when possible
4. **User Feedback** → Meaningful error messages for troubleshooting
## **TECHNICAL STANDARDS**
### **TypeScript Configuration**
- **Target**: ES2022 for modern Node.js compatibility
- **Module**: ESNext with Node.js resolution
- **Strict Mode**: Enabled for type safety
- **Source Maps**: Required for debugging
### **AppleScript Patterns**
#### **Simple Queries**
```applescript
tell application "Mail" to get unread count of inbox
```
#### **Complex Queries (Buffer-Safe)**
```applescript
tell application "Contacts"
set targetPerson to first person whose name contains "John"
set personName to name of targetPerson
set personOrg to organization of targetPerson
return personName & " | " & personOrg
end tell
```
### **Output Processing Standards**
- **UI-Friendly Names**: Remove system artifacts and technical details
- **Consistent Formatting**: Standardized output formats across tools
- **Error Clarity**: Meaningful messages for both AI and human users
- **Data Validation**: Verify results against application UI when possible
## **SECURITY CONSIDERATIONS**
### **Data Access**
- **Local Only**: All processing happens on user's machine
- **No Network**: No external data transmission
- **Standard APIs**: Uses official AppleScript interfaces
- **User Control**: AI requests require user approval through MCP client
### **Permission Model**
- **Application Access**: Requires macOS accessibility permissions
- **Data Scope**: Limited to what AppleScript can access
- **User Awareness**: All actions visible in target applications
- **Audit Trail**: All commands logged through MCP protocol
## **PERFORMANCE CHARACTERISTICS**
### **Response Times**
- **Simple Queries**: < 100ms (inbox count, account list)
- **Search Operations**: 100-500ms (contact search, file selection)
- **Complex Retrieval**: 500ms-2s (detailed contact info)
### **Resource Usage**
- **Memory**: Minimal, no data caching
- **CPU**: Low, primarily I/O bound
- **Disk**: No persistent storage beyond logs
### **Scalability Limits**
- **Concurrent Requests**: Single-threaded, sequential processing
- **Data Volume**: Limited by AppleScript buffer sizes
- **Application State**: Dependent on target application responsiveness
## **KNOWN LIMITATIONS**
### **AppleScript Constraints**
- **Buffer Overflow**: Large property queries can exceed stdout limits
- **UI Mismatch**: AppleScript object models don't always match UI terminology
- **Application Dependency**: Requires target applications to be available
- **Error Handling**: Limited error detail from AppleScript layer
### **Platform Dependencies**
- **macOS Only**: No cross-platform compatibility
- **Version Sensitivity**: AppleScript APIs can change between macOS versions
- **Application Updates**: Target app updates may break functionality
- **Accessibility Requirements**: Needs system accessibility permissions
## **FUTURE ARCHITECTURE CONSIDERATIONS**
### **Potential Improvements**
- **Caching Layer**: For frequently accessed data
- **Batch Operations**: Multiple commands in single AppleScript execution
- **Error Recovery**: Automatic retry mechanisms
- **Performance Monitoring**: Response time tracking and optimization
### **Expansion Areas**
- **Additional Applications**: Safari, Messages, Reminders, etc.
- **Advanced Workflows**: Multi-step automation sequences
- **Configuration Management**: User preferences and customization
- **Plugin Architecture**: Third-party tool development
---
*This architecture enables reliable AI-driven macOS automation while maintaining security and user control.*