# DSS MCP-First Architecture

## Why MCP? Why Not REST?

You were absolutely right to question REST endpoints. Here's why **MCP-first is the right approach** for DSS:

### The Problem with REST (Traditional Approach)

```
JavaScript Chat UI
    ↓
REST API (/api/projects, /api/manifest, etc.)
    ↓
Python Backend
    ↓
Database/Filesystem
    ↓
Response → Chat UI
```

**Issues:**
- ❌ Duplicate business logic (REST endpoint + MCP tool)
- ❌ Latency: JS → HTTP → Python → DB → HTTP → JS
- ❌ Two implementations of same feature
- ❌ Hard to test end-to-end
- ❌ Claude can't directly call your tools
- ❌ Requires building REST wrapper around everything

---

## The MCP-First Solution

```
JavaScript Chat UI
    ↓
Claude (with MCP tools available)
    ↓
Call MCP Tool (tool_use)
    ↓
Python MCP Server
    ↓
Database/Filesystem
    ↓
Response → Claude → Chat UI
```

**Benefits:**
- ✅ Single source of truth (MCP tool)
- ✅ Claude makes intelligent decisions
- ✅ Native tool_use integration
- ✅ No REST endpoints to maintain
- ✅ Better context awareness
- ✅ Simpler architecture

---

## The Workflow

### Old Way (REST-based)

```javascript
// UI code
const response = await fetch('/api/projects', {
  method: 'POST',
  body: JSON.stringify({name, root_path, description})
});
const project = await response.json();
```

### New Way (MCP-first)

```javascript
// Chat interprets: "create project test in ./src"
// JavaScript just parses and sends to Claude:

{
  action: 'call_mcp_tool',
  tool: 'dss_create_project',
  args: {name, root_path, description}
}

// Claude receives the tool result and responds naturally
```

---

## Component Roles

### JavaScript (Frontend)
- Parse natural language input
- Extract structured parameters using AI
- Display MCP tool results
- Manage chat conversation
- **Does NOT** make API calls

### Claude (AI Agent)
- Understands user intent
- Calls appropriate MCP tools
- Chains tools together (e.g., create project → setup Figma → discover files)
- Returns human-readable results
- **Orchestrates the workflow**

### MCP Server (Backend)
- Implements all business logic as **tools**
- Reads/writes to database and filesystem
- Manages project manifests
- Handles Figma API integration
- Encrypts credentials
- Audit logging
- **Single implementation**

---

## Architecture Comparison

| Aspect | REST Approach | MCP-First Approach |
|--------|---------------|-------------------|
| **API Endpoints** | Many (/projects, /manifest, /figma, etc.) | None (just MCP tools) |
| **Where logic lives** | Scattered (REST + MCP) | Centralized (MCP tools only) |
| **Data flow** | JS → HTTP → Python → DB → HTTP → JS | JS → Claude → MCP Server → DB |
| **Claude integration** | Hooks into REST responses | Direct tool_use |
| **Debugging** | Need to trace both REST and MCP | Trace MCP tool directly |
| **Tool reusability** | Limited | All MCP tools available to Claude |
| **Latency** | 2 HTTP roundtrips | 1 MCP tool call |
| **Testing** | Unit test REST, unit test MCP | Integration test MCP tools |

---

## Implementation Phases

### Phase 1: Implement MCP Tools
- Add 6 new MCP tools to `tools/dss_mcp/tools/project_tools.py`
- Implement manifest management
- Encrypt Figma credentials in database
- Register tools in handler

### Phase 2: Update JavaScript
- Remove REST calls
- Keep command parsing
- Return MCP tool specifications
- Let Claude execute tools

### Phase 3: End-to-End Testing
- Test full workflow: user input → Claude → MCP tool → result
- Verify credential encryption
- Test manifest creation/updates
- Test Figma API integration

---

## Example Workflow: Create Project with Figma

### User says:
```
"Create a design system project called web-ui in ./packages/design with my Figma workspace"
```

### JavaScript processes:
```javascript
// Parse natural language
const command = '/init'
const params = {
  name: 'web-ui',
  root_path: './packages/design'
}
```

### Claude orchestrates:
```
1. Ask for Figma API token if not already configured
2. Call dss_setup_figma_credentials (if needed)
3. Call dss_create_project
4. Call dss_discover_figma_files
5. Return summary to user
```

### Each tool runs:
```python
# Tool 1: dss_create_project
- Create project in database
- Create figma.json manifest
- Return project_id

# Tool 2: dss_setup_figma_credentials (cached if already set)
- Encrypt and store token
- Validate with Figma API

# Tool 3: dss_discover_figma_files
- Read credentials from database
- Query Figma API for user's files
- Return suggestions
```

### Result:
```
✅ Project created: web-ui
✅ Figma credentials stored
✅ Found 5 Figma files:
   - Design Tokens
   - Components
   - Icons
   - Patterns
   - Documentation

Next steps:
- /add-figma <file_key> to link specific files
- /sync to extract tokens
- /analyze to scan for components
```

---

## Database Schema Integration

### Existing Tables Used:
- `projects` - Project metadata
- `project_integrations` - User-scoped encrypted credentials
- `integration_health` - API health monitoring
- `mcp_tool_usage` - Audit log

### No New Tables Needed!
The existing schema already supports:
- Project creation
- User-scoped credentials
- Integration health tracking
- Tool usage auditing

### Manifest Location:
- File-based: `{project_root}/figma.json`
- Version controlled: Can be checked into git
- Fast access: Direct filesystem read/write
- Auditable: Last modified timestamp

---

## Security

### Credential Storage
```
User Input: "figd_pAT_xxxxxxxxxxxx"
    ↓
Encrypted with Fernet: cipher.encrypt(config.encode())
    ↓
Stored in project_integrations.config
    ↓
Retrieved and decrypted when needed
    ↓
Never exposed to frontend
```

### User Isolation
- Credentials scoped to user_id
- Each project can have user's own integration configs
- No global shared credentials
- Audit trail of all tool usage

### Circuit Breaker
- Protects against cascading Figma API failures
- Fails gracefully with clear error messages
- Tracks integration health
- Automatic recovery

---

## Why This is Better

1. **Single Source of Truth**
   - MCP tools define everything
   - No REST endpoints to maintain
   - No duplication

2. **Better User Experience**
   - Claude understands context
   - Can chain operations (create → setup → discover)
   - Returns natural language feedback
   - Anticipates next steps

3. **Easier to Debug**
   - Trace single execution path
   - Clear tool input/output
   - Audit log of all operations
   - No HTTP layer to troubleshoot

4. **Scales Better**
   - Add new tools without REST endpoints
   - Claude can discover and use new tools
   - No coordination between layers
   - Clear separation of concerns

5. **More Secure**
   - Credentials never exposed to frontend
   - Encrypted storage in database
   - User-scoped access control
   - Complete audit trail

---

## Next Steps

1. **Backend Implementation**
   - [ ] Implement 6 MCP tools (see MCP_TOOLS_SPEC.md)
   - [ ] Add encryption to project_integrations
   - [ ] Register tools in handler
   - [ ] Test with MCP client

2. **Frontend Updates**
   - [ ] Keep command parsing in JavaScript
   - [ ] Return MCP tool specifications
   - [ ] Let Claude handle execution
   - [ ] Display results naturally

3. **Testing**
   - [ ] Test each MCP tool individually
   - [ ] Test end-to-end workflow
   - [ ] Verify encryption/decryption
   - [ ] Load test Figma API calls

4. **Documentation**
   - [ ] Update user guides
   - [ ] Document command flow
   - [ ] Add troubleshooting guide
   - [ ] Create architecture diagram

---

## Result

A true **MCP-first, AI-native design system platform** where:
- Claude orchestrates all operations
- Tools are the single source of truth
- No REST API complexity
- Clean, maintainable architecture
- Better user experience
- Maximum security

**This is how modern AI applications should be built!** 🚀
