# Task ID: 2

**Title:** Design and Implement Database Schema

**Status:** pending

**Dependencies:** 1

**Priority:** high

**Description:** Create the database schema for storing MCP server configurations, projects, profiles, user sessions, and audit logs. Use PostgreSQL for production readiness.

**Details:**

Design PostgreSQL schema using Prisma ORM:

```prisma
model User {
  id        String   @id @default(uuid())
  email     String   @unique
  name      String?
  sessions  Session[]
  auditLogs AuditLog[]
  createdAt DateTime @default(now())
}

model McpServer {
  id          String   @id @default(uuid())
  name        String   @unique
  type        String   // e.g., 'slack', 'jira', 'terraform'
  command     String   // npx command or docker image
  args        Json     // command arguments
  envTemplate Json     // required env vars template
  setupGuide  String?  // markdown guide for setup
  profiles    McpProfile[]
  instances   McpInstance[]
}

model McpProfile {
  id           String   @id @default(uuid())
  name         String
  serverId     String
  server       McpServer @relation(fields: [serverId], references: [id])
  config       Json     // profile-specific config (read-only, limited endpoints, etc.)
  filterRules  Json?    // pre-filtering rules
  projects     ProjectMcpProfile[]
}

model Project {
  id          String   @id @default(uuid())
  name        String   @unique
  description String?
  profiles    ProjectMcpProfile[]
  createdAt   DateTime @default(now())
}

model ProjectMcpProfile {
  projectId String
  profileId String
  project   Project    @relation(fields: [projectId], references: [id])
  profile   McpProfile @relation(fields: [profileId], references: [id])
  @@id([projectId, profileId])
}

model McpInstance {
  id          String   @id @default(uuid())
  serverId    String
  server      McpServer @relation(fields: [serverId], references: [id])
  containerId String?
  status      String   // running, stopped, error
  config      Json
  createdAt   DateTime @default(now())
}

model AuditLog {
  id        String   @id @default(uuid())
  userId    String?
  user      User?    @relation(fields: [userId], references: [id])
  action    String
  resource  String
  details   Json
  timestamp DateTime @default(now())
}

model Session {
  id        String   @id @default(uuid())
  userId    String
  user      User     @relation(fields: [userId], references: [id])
  token     String   @unique
  expiresAt DateTime
}
```

Create migrations and seed data for common MCP servers (slack, jira, github, terraform).

**Test Strategy:**

Run Prisma migrations against test database. Verify all relations work correctly with seed data. Test CRUD operations for each model using Prisma client.

## Subtasks

### 2.1. Set up Prisma ORM and PostgreSQL test infrastructure with docker-compose

**Status:** pending  
**Dependencies:** None  

Initialize Prisma in the db package with PostgreSQL configuration, create docker-compose.yml for local development with separate test database, and set up test database setup/teardown scripts.

**Details:**

Create src/db/prisma directory structure. Install Prisma dependencies (@prisma/client, prisma as devDependency). Configure deploy/docker-compose.yml with two PostgreSQL services: mcpctl-postgres (port 5432) for development and mcpctl-postgres-test (port 5433) for testing. Create src/db/src/test-utils.ts with setupTestDb() and teardownTestDb() functions that handle database connection, schema push, and cleanup. Create .env and .env.test with DATABASE_URL pointing to respective databases. Initialize prisma/schema.prisma with PostgreSQL provider and basic generator config. Write Vitest tests for test utilities to verify they can connect, push schema, and cleanup correctly.

### 2.2. Write TDD tests for all Prisma models before implementing schema

**Status:** pending  
**Dependencies:** 2.1  

Create comprehensive Vitest test suites for all 8 models (User, McpServer, McpProfile, Project, ProjectMcpProfile, McpInstance, AuditLog, Session) testing CRUD operations, relations, constraints, and edge cases.

**Details:**

Create src/db/tests/models directory with separate test files: user.test.ts, mcp-server.test.ts, mcp-profile.test.ts, project.test.ts, mcp-instance.test.ts, audit-log.test.ts, session.test.ts. Each test file should include: (1) CRUD operations (create, read, update, delete), (2) Unique constraint violations (email for User, name for McpServer/Project), (3) Relation tests (User->Sessions, McpServer->McpProfile->Projects, etc.), (4) Cascade delete behavior, (5) JSON field validation for args, envTemplate, config, filterRules, details fields, (6) Default value tests (uuid, timestamps), (7) Edge cases like null optional fields. Tests will initially fail (TDD red phase) until schema is implemented.

### 2.3. Implement Prisma schema with all models and security considerations

**Status:** pending  
**Dependencies:** 2.2  

Create the complete Prisma schema with all 8 models, proper relations, indexes for audit queries, and security-conscious field design for credentials encryption at rest.

**Details:**

Implement src/db/prisma/schema.prisma with: User (id uuid, email unique, name optional, createdAt, relations to Session and AuditLog), McpServer (id uuid, name unique, type, command, args Json, envTemplate Json with @@map for encrypted storage notes, setupGuide optional, relations), McpProfile (id uuid, name, serverId FK, config Json, filterRules Json optional, relation to server and projects), Project (id uuid, name unique, description optional, createdAt, relation to profiles), ProjectMcpProfile (composite PK projectId+profileId, relations), McpInstance (id uuid, serverId FK, containerId optional, status enum-like string, config Json, metadata Json for future K8s support, createdAt, updatedAt), AuditLog (id uuid, userId optional FK, action, resource, details Json, timestamp, indexes on userId, timestamp, action for query performance), Session (id uuid, userId FK, token unique with index, expiresAt, createdAt). Add @@index annotations for frequently queried fields. Document in comments that envTemplate and config containing secrets must be encrypted at application layer.

### 2.4. Create seed data functions with unit tests for common MCP servers

**Status:** pending  
**Dependencies:** 2.3  

Implement seed functions for common MCP server configurations (Slack, Jira, GitHub, Terraform) with comprehensive unit tests for each seed function.

**Details:**

Create src/db/seed directory with: index.ts (main seed runner), mcp-servers.ts (server definitions), seed-mcp-servers.ts (seeding function), seed-default-profiles.ts (default profiles per server). Define server configurations: Slack (npx @modelcontextprotocol/server-slack, SLACK_BOT_TOKEN, SLACK_TEAM_ID env template with setup guide), Jira (npx @anthropic/mcp-server-jira, JIRA_URL, JIRA_EMAIL, JIRA_API_TOKEN), GitHub (npx @modelcontextprotocol/server-github, GITHUB_TOKEN), Terraform (npx terraform-docs-mcp). Create src/db/tests/seed directory with tests: seed-mcp-servers.test.ts, seed-default-profiles.test.ts. Tests should verify: (1) Each server is created with correct data, (2) Idempotency (running twice doesn't create duplicates), (3) Default profiles are linked correctly, (4) envTemplate JSON structure is valid.

### 2.5. Create database migrations and perform security/architecture review

**Status:** pending  
**Dependencies:** 2.3, 2.4  

Generate initial Prisma migration, create migration helper utilities with tests, and conduct comprehensive security and architecture review documenting findings.

**Details:**

Run 'npx prisma migrate dev --name init' to create initial migration in src/db/prisma/migrations. Create src/db/src/migration-helpers.ts with utilities: resetDatabase(), applyMigrations(), rollbackMigration() with proper error handling. Write unit tests in src/db/tests/migration-helpers.test.ts. Conduct security review and document in src/db/SECURITY_REVIEW.md: (1) PII handling - email in User is only PII, add note about GDPR considerations, (2) Credentials handling - envTemplate, config fields contain secrets, document encryption-at-rest requirement at application layer, (3) Audit log indexes verified for query performance, (4) Cascade delete behavior reviewed (Session deletes with User, but AuditLog userId set to null), (5) No sensitive data in plain text validation. Conduct architecture review documenting in src/db/ARCHITECTURE.md: (1) Schema supports all 18 tasks, (2) McpInstance.metadata Json field ready for K8s pod metadata, (3) AuditLog.details flexible for various action types, (4) Future migration considerations for adding fields without breaking data.
