Menu
Implementation

MSP Project Structure

Project Structure

Understanding MSP's project structure is key to successful implementation and customization. This guide covers the standard directory layout, file organization, and architectural patterns.

Standard MSP Project Structure

msp/                              # Root directory
├── msp.ps1                       # Main entry point
├── msp-config.json               # User configuration
├── package.json                  # Node.js dependencies
├── README.md                     # Project documentation

├── .msp/                         # MSP runtime data (gitignored)
│   ├── state.json               # Current session state
│   ├── cache/                   # Temporary cache files
│   ├── sessions/                # Session history
│   │   ├── 2025-07-15/         # Organized by date
│   │   │   └── *.json          # Individual sessions
│   │   └── 2025-07-16/
│   └── recovery/                # Crash recovery data

├── scripts/                      # PowerShell scripts
│   ├── msp-core.ps1            # Core protocol logic
│   ├── msp-state.ps1           # State management
│   ├── msp-validate.ps1        # Validation logic
│   ├── msp-recovery.ps1        # Recovery procedures
│   ├── setup-neo4j.ps1         # Neo4j setup
│   ├── setup-obsidian.ps1      # Obsidian setup
│   └── setup-linear.ps1        # Linear setup

├── src/                          # Source code
│   ├── core/                    # Core modules
│   │   ├── session-manager.ts  # Session lifecycle
│   │   ├── state-manager.ts    # State persistence
│   │   ├── context-engine.ts   # Context processing
│   │   └── validator.ts        # Data validation
│   │
│   ├── integrations/            # External integrations
│       ├── neo4j/              # Neo4j integration
│       │   ├── client.ts       # Neo4j client
│       │   ├── queries.ts      # Cypher queries
│       │   └── schema.ts       # Graph schema
│       │
│       ├── obsidian/           # Obsidian integration
│       │   ├── vault.ts        # Vault operations
│       │   ├── templates.ts    # Note templates
│       │   └── sync.ts         # Sync logic
│       │
│       └── linear/             # Linear integration
│           ├── client.ts       # GraphQL client
│           ├── mutations.ts    # GraphQL mutations
│           └── queries.ts      # GraphQL queries

├── templates/                    # User templates
│   ├── session-note.md         # Daily note template
│   ├── decision-record.md      # ADR template
│   └── project-setup.md        # Project template

├── tests/                        # Test suites
│   ├── unit/                   # Unit tests
│   ├── integration/            # Integration tests
│   └── e2e/                    # End-to-end tests

├── docs/                         # Documentation
│   ├── api/                    # API documentation
│   ├── guides/                 # User guides
│   └── development/            # Dev docs

└── config/                       # Configuration files
    ├── default.json            # Default settings
    ├── schema.json             # Config schema
    └── examples/               # Example configs

File Organization Patterns

Core Files

msp.ps1 - Entry Point

# Main entry point - delegates to appropriate scripts
param(
    [string]$Command = "help",
    [string]$Param1,
    [string]$Param2
)

# Load core module
. "$PSScriptRoot\scripts\msp-core.ps1"

# Route command
switch ($Command) {
    "start"  { Start-MSPSession @args }
    "update" { Update-MSPSession @args }
    "end"    { End-MSPSession @args }
    default  { Show-MSPHelp }
}

msp-config.json - Configuration

{
  "version": "1.0",
  "user": {
    "name": "Developer Name",
    "email": "dev@example.com"
  },
  "integrations": {
    "neo4j": {
      "enabled": true,
      "uri": "bolt://localhost:7687"
    },
    "obsidian": {
      "enabled": true,
      "vault": "~/Documents/Obsidian"
    },
    "linear": {
      "enabled": false,
      "teamId": ""
    }
  },
  "preferences": {
    "autoRecover": true,
    "progressIncrement": 5,
    "sessionTimeout": 240
  }
}

State Management

.msp/state.json - Active Session State

{
  "version": "1.0",
  "session": {
    "id": "msp-2025-07-16-093042",
    "status": "active",
    "startTime": "2025-07-16T09:30:42Z",
    "project": "my-project",
    "progress": {
      "start": 25,
      "current": 40,
      "target": 50
    },
    "updates": [
      {
        "time": "10:15",
        "message": "Implemented user model",
        "progress": 30
      }
    ]
  },
  "lastSync": {
    "neo4j": "2025-07-16T10:30:00Z",
    "obsidian": "2025-07-16T10:31:00Z",
    "linear": null
  }
}

Session History Structure

.msp/sessions/
├── 2025-07-15/
│   ├── msp-2025-07-15-093000.json
│   ├── msp-2025-07-15-140000.json
│   └── msp-2025-07-15-173000.json
├── 2025-07-16/
│   └── msp-2025-07-16-093042.json
└── index.json                    # Session index for fast lookup

Integration Modules

Neo4j Module Structure

src/integrations/neo4j/
├── client.ts           # Connection management
├── queries.ts          # Cypher query templates
├── schema.ts           # Node/relationship definitions
└── tests/
    └── neo4j.test.ts

Example queries.ts:

export const queries = {
  createSession: `
    CREATE (s:Session {
      id: $id,
      user: $user,
      project: $project,
      startTime: datetime($startTime),
      status: 'active'
    })
    RETURN s
  `,
  
  addUpdate: `
    MATCH (s:Session {id: $sessionId, status: 'active'})
    CREATE (u:Update {
      message: $message,
      timestamp: datetime($timestamp),
      progress: $progress
    })
    CREATE (s)-[:HAS_UPDATE]->(u)
    RETURN u
  `,
  
  findRelatedSessions: `
    MATCH (s1:Session {id: $sessionId})
    MATCH (s1)-[:WORKED_ON]->(e:Entity)<-[:WORKED_ON]-(s2:Session)
    WHERE s1 <> s2
    RETURN DISTINCT s2
    ORDER BY s2.startTime DESC
    LIMIT 5
  `
};

Obsidian Module Structure

src/integrations/obsidian/
├── vault.ts            # Vault operations
├── templates.ts        # Template engine
├── sync.ts            # File sync logic
├── config.ts          # Obsidian-specific config
└── templates/
    ├── daily-note.hbs
    ├── decision.hbs
    └── session.hbs

manifest.json

{
  "name": "code-metrics",
  "version": "1.0.0",
  "description": "Track code metrics in MSP sessions",
  "author": "Your Name",
  "main": "index.js",
  "msp": {
    "minVersion": "1.0.0",
    "maxVersion": "2.0.0"
  },
  "commands": [
    {
      "name": "metrics",
      "description": "Analyze code metrics"
    }
  ],
  "hooks": [
    "session:start",
    "session:end"
  ]
}

Component Architecture

Layered Architecture

┌─────────────────────────────────────┐
│          CLI Interface              │
├─────────────────────────────────────┤
│         Command Parser              │
├─────────────────────────────────────┤
│          Core Engine                │
├──────────┬──────────┬──────────────┤
│  State   │ Context  │  Validator   │
│ Manager  │ Engine   │              │
├──────────┴──────────┴──────────────┤
│      Integration Layer              │
├──────┬──────┬──────┬───────────────┤
│Neo4j │ Obs. │Linear│  Plugins      │
└──────┴──────┴──────┴───────────────┘

Module Dependencies

graph TD
    CLI[CLI] --> Core[Core Engine]
    Core --> State[State Manager]
    Core --> Context[Context Engine]
    Core --> Validator[Validator]
    
    State --> Storage[Storage Layer]
    Storage --> FileSystem[File System]
    Storage --> Cache[Cache]
    
    Core --> Integration[Integration Layer]
    Integration --> Neo4j[Neo4j Module]
    Integration --> Obsidian[Obsidian Module]
    Integration --> Linear[Linear Module]
    
    Core --> Plugins[Plugin Manager]
    Plugins --> Plugin1[Plugin 1]
    Plugins --> Plugin2[Plugin 2]

Configuration Hierarchy

Configuration Loading Order

  1. Default Configuration (config/default.json)
  2. User Configuration (msp-config.json)
  3. Environment Variables (MSP_*)
  4. Command Line Arguments

Environment Variable Mapping

# Neo4j Configuration
MSP_NEO4J_URI=bolt://localhost:7687
MSP_NEO4J_USER=neo4j
MSP_NEO4J_PASSWORD=password

# Obsidian Configuration
MSP_OBSIDIAN_VAULT=/path/to/vault
MSP_OBSIDIAN_DAILY_NOTES=Daily Notes

# Linear Configuration
MSP_LINEAR_API_KEY=lin_api_xxxxx
MSP_LINEAR_TEAM_ID=xxxxx

# General Configuration
MSP_DEBUG=true
MSP_AUTO_SYNC=false

Development Patterns

Adding a New Command

  1. Create command handler in src/cli/commands/
  2. Register in command parser
  3. Add tests
  4. Update documentation

Example:

// src/cli/commands/analyze.ts
export class AnalyzeCommand implements ICommand {
  name = 'analyze';
  description = 'Analyze session patterns';
  
  async execute(args: string[]): Promise<void> {
    const sessions = await this.loadRecentSessions();
    const analysis = await this.performAnalysis(sessions);
    this.displayResults(analysis);
  }
}

Build and Distribution

Build Output Structure

dist/
├── msp.exe              # Windows executable
├── msp-macos           # macOS executable
├── msp-linux           # Linux executable
├── msp.ps1             # PowerShell script
├── config/             # Default configs
├── templates/          # Default templates
└── README.md           # Distribution readme

Package Structure

msp-1.0.0/
├── bin/                # Executables
├── lib/                # Core libraries
├── node_modules/       # Dependencies
├── scripts/            # Setup scripts
└── docs/               # Documentation

Best Practices

1. State Management

  • Always use atomic operations
  • Implement proper locking for concurrent access
  • Regular state validation
  • Automatic backups of state

2. Error Handling

try {
  await operation();
} catch (error) {
  if (error instanceof MSPError) {
    // Handle MSP-specific errors
    this.handleMSPError(error);
  } else {
    // Log unexpected errors
    this.logger.error('Unexpected error', error);
    // Attempt recovery
    await this.recover();
  }
}

3. Performance

  • Lazy load integrations
  • Cache frequently accessed data
  • Batch operations when possible
  • Use streams for large data

4. Security

  • Never store credentials in state files
  • Use environment variables for secrets
  • Implement proper access controls
  • Audit sensitive operations

Extending MSP

Custom Storage Backend

class CustomStorage implements IStorage {
  async save(key: string, data: any): Promise<void> {
    // Custom implementation
  }
  
  async load(key: string): Promise<any> {
    // Custom implementation
  }
}

Custom Command

# Add to scripts/custom-commands.ps1
function Invoke-CustomCommand {
    param([string]$Param)
    
    # Your implementation
    Write-Host "Custom command executed: $Param"
}

# Register command
Register-MSPCommand -Name "custom" -Handler ${function:Invoke-CustomCommand}

Keywords: MSP project structure, MSP file organization, MSP architecture, MSP directory layout, MSP module structure, context engineering project structure

For AI Understanding: This document details the complete project structure of MSP including directory layout, file organization patterns, component architecture, and development patterns. The structure follows a modular design with clear separation between core functionality, integrations, and plugins. Key directories include scripts (PowerShell), src (TypeScript source), integrations (external tools), and .msp (runtime data).


Previous: Implementation Guide | Next: Platform Setup →