# 🔌 Vibn MCP Integration

**Model Context Protocol (MCP) support for Vibn**

Connect AI assistants like Claude, ChatGPT, and custom agents to your Vibn projects, enabling them to access your coding sessions, project data, and conversation history.

---

## 📦 What's Included

### 1. **MCP Server** (stdio)
- Standalone server that runs locally
- Exposes Vibn data through the standard MCP protocol
- Works with Claude Desktop, custom AI applications, and more
- File: `lib/mcp/server.ts`
- Launcher: `mcp-server.js`

### 2. **HTTP API** (REST)
- Web-accessible MCP endpoint
- Authentication via Firebase ID tokens
- Perfect for web-based AI assistants
- Endpoint: `/api/mcp`

### 3. **Interactive Playground**
- Test MCP capabilities directly in the Vibn UI
- View how AI assistants see your data
- Debug MCP requests and responses
- Page: `/[workspace]/mcp`

---

## 🚀 Getting Started

### Option 1: For Claude Desktop

1. **Open Claude Desktop configuration:**
   - macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
   - Windows: `%APPDATA%/Claude/claude_desktop_config.json`

2. **Add Vibn MCP server:**
```json
{
  "mcpServers": {
    "vibn": {
      "command": "node",
      "args": ["/Users/your-username/ai-proxy/vibn-frontend/mcp-server.js"],
      "env": {
        "FIREBASE_PROJECT_ID": "your-project-id",
        "FIREBASE_CLIENT_EMAIL": "your-service-account-email",
        "FIREBASE_PRIVATE_KEY": "your-private-key"
      }
    }
  }
}
```

3. **Restart Claude Desktop**

4. **Test it:**
   - Open a new chat in Claude
   - Type: "Can you show me my Vibn projects?"
   - Claude will use the MCP server to fetch your project data!

### Option 2: For Web-Based AI (HTTP API)

Use the REST endpoint to integrate with any AI application:

```typescript
const response = await fetch('https://vibnai.com/api/mcp', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_FIREBASE_ID_TOKEN',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    action: 'read_resource',
    params: {
      uri: 'vibn://projects/YOUR_USER_ID'
    }
  })
});

const data = await response.json();
console.log(data);
```

### Option 3: Test in Vibn UI

1. **Navigate to:** `https://vibnai.com/your-workspace/mcp`
2. **Click on any tool card** to test MCP requests
3. **View responses** in the interactive playground

---

## 📚 Available Resources

| Resource URI | Description | Returns |
|-------------|-------------|---------|
| `vibn://projects/{userId}` | All user projects | Array of project objects |
| `vibn://projects/{userId}/{projectId}` | Specific project | Single project with details |
| `vibn://sessions/{userId}` | All coding sessions | Array of session objects |
| `vibn://sessions/{projectId}` | Project sessions | Sessions for specific project |
| `vibn://conversations/{projectId}` | AI chat history | Conversation messages |

---

## 🛠️ Available Tools

### `get_project_summary`
Get comprehensive project insights.

**Input:**
```json
{
  "projectId": "project-abc123"
}
```

**Output:**
```json
{
  "project": { "name": "My App", ... },
  "stats": {
    "totalSessions": 42,
    "totalCost": 12.50,
    "totalTokens": 125000,
    "totalDuration": 3600
  },
  "recentSessions": [...]
}
```

### `search_sessions`
Find sessions with filters.

**Input:**
```json
{
  "projectId": "project-abc123",
  "workspacePath": "/path/to/workspace",
  "startDate": "2024-01-01T00:00:00Z",
  "endDate": "2024-12-31T23:59:59Z"
}
```

**Output:**
```json
[
  {
    "id": "session-xyz",
    "workspacePath": "/path/to/workspace",
    "cost": 0.25,
    "tokensUsed": 2500,
    "duration": 300,
    ...
  }
]
```

### `get_conversation_context`
Reference past AI conversations.

**Input:**
```json
{
  "projectId": "project-abc123",
  "limit": 50
}
```

**Output:**
```json
[
  {
    "role": "user",
    "content": "How do I implement auth?",
    "createdAt": "2024-11-14T10:30:00Z"
  },
  {
    "role": "assistant",
    "content": "Here's how to set up authentication...",
    "createdAt": "2024-11-14T10:30:05Z"
  }
]
```

---

## 💡 Example Use Cases

### 1. Project Status Update
**Prompt:** "Give me a status update on my Vibn projects"

**What happens:**
- AI calls `vibn://projects/{userId}` to list projects
- AI calls `get_project_summary` for each project
- AI presents a comprehensive overview of all work

### 2. Cost Analysis
**Prompt:** "How much have I spent on AI for project X?"

**What happens:**
- AI calls `get_project_summary` for project X
- AI analyzes the `totalCost` metric
- AI breaks down costs by session if needed

### 3. Conversation Continuity
**Prompt:** "What did we discuss about authentication last week?"

**What happens:**
- AI calls `get_conversation_context` for the project
- AI searches through conversation history
- AI references past discussions with full context

### 4. Development Insights
**Prompt:** "What files am I spending the most time on?"

**What happens:**
- AI calls `search_sessions` to get all sessions
- AI analyzes file change patterns
- AI identifies productivity hotspots

---

## 🏗️ Architecture

```
┌─────────────────┐
│  AI Assistant   │ (Claude, ChatGPT, etc.)
└────────┬────────┘
         │
         ├─────────── stdio ────────────┐
         │                              │
         └─────────── HTTP ─────────────┤
                                        │
                              ┌─────────▼─────────┐
                              │   Vibn MCP Server │
                              │  (server.ts/api)  │
                              └─────────┬─────────┘
                                        │
                              ┌─────────▼─────────┐
                              │  Firebase Admin   │
                              │    (Firestore)    │
                              └───────────────────┘
                                        │
                              ┌─────────▼─────────┐
                              │   User Projects   │
                              │    + Sessions     │
                              │  + Conversations  │
                              └───────────────────┘
```

---

## 🔒 Security

### Authentication
- **stdio server:** Requires Firebase Admin credentials (environment variables)
- **HTTP API:** Requires Firebase ID token in Authorization header
- **User isolation:** All queries filter by `userId` to prevent data leaks

### Best Practices
1. **Never expose MCP server publicly** - Run it locally or behind a firewall
2. **Use environment variables** - Don't hardcode credentials
3. **Rotate keys regularly** - Update Firebase service account keys periodically
4. **Monitor access logs** - Review MCP usage in Firebase logs

---

## 🧪 Testing

### Test the stdio server:
```bash
cd vibn-frontend
npm run mcp:server
```

The server will start and wait for connections. To test manually, you can send MCP JSON-RPC messages via stdin.

### Test the HTTP API:
```bash
# Get capabilities
curl https://vibnai.com/api/mcp

# List resources (requires auth token)
curl -X POST https://vibnai.com/api/mcp \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"action": "list_resources"}'
```

### Test in the UI:
1. Navigate to `/your-workspace/mcp`
2. Click tool cards to trigger requests
3. View formatted JSON responses

---

## 🐛 Troubleshooting

### "Server won't start"
- ✅ Check `.env.local` has all Firebase credentials
- ✅ Verify Node.js version (18+)
- ✅ Run `npm install` to ensure dependencies are installed

### "AI can't connect"
- ✅ Use absolute paths in Claude config
- ✅ Verify the MCP server is running
- ✅ Check environment variables are set in config

### "No data returned"
- ✅ Confirm you have projects/sessions in Firebase
- ✅ Check userId matches your authenticated user
- ✅ Review server logs for errors

### "Permission denied"
- ✅ Ensure Firebase service account has Firestore read access
- ✅ Verify security rules allow server-side access
- ✅ Check ID token is valid and not expired

---

## 📈 Roadmap

Future MCP enhancements:

- [ ] **Write operations** - Create/update projects via MCP
- [ ] **Real-time subscriptions** - Stream session updates
- [ ] **Advanced analytics** - Cost forecasting, productivity insights
- [ ] **Git integration** - Access commit history via MCP
- [ ] **File content access** - Read actual code files
- [ ] **Prompt templates** - Pre-built prompts for common tasks

---

## 🤝 Contributing

Want to extend Vibn's MCP capabilities? Here's how:

1. **Add new resources** - Edit `lib/mcp/server.ts` and `/api/mcp/route.ts`
2. **Add new tools** - Implement in both stdio and HTTP handlers
3. **Update docs** - Keep `MCP_SETUP.md` in sync
4. **Test thoroughly** - Use the playground to verify changes

---

## 📖 Learn More

- [Model Context Protocol Spec](https://modelcontextprotocol.io/)
- [OpenAI MCP Documentation](https://platform.openai.com/docs/mcp)
- [Vibn Documentation](https://vibnai.com/docs)
- [Firebase Admin SDK](https://firebase.google.com/docs/admin/setup)

---

## 💬 Support

Need help with MCP integration?

- 📧 Email: support@vibnai.com
- 💬 Discord: [Join our community](https://discord.gg/vibn)
- 🐛 Issues: [GitHub Issues](https://github.com/vibn/vibn/issues)

---

**Built with ❤️ by the Vibn team**

*Making AI assistants truly understand your codebase.*

