# Trackex MCP Server

A Model Context Protocol (MCP) server for Trackex that provides task management capabilities to Claude.ai through OAuth 2.1 authentication.

## 🚀 Overview

This MCP server enables Claude.ai to interact with the Trackex task management system through a secure OAuth 2.1 flow. It uses the `@cloudflare/workers-oauth-provider` library to handle OAuth authentication and provides MCP tools for task management.

## 🔧 Architecture

The server is built on Cloudflare Workers and uses:

- **OAuth 2.1 Provider**: `@cloudflare/workers-oauth-provider` for standards-compliant OAuth
- **Microsoft OAuth**: Integration with Microsoft Azure AD for user authentication
- **Trackex API**: Backend integration for task management operations
- **MCP Protocol**: Server-Sent Events (SSE) for real-time communication with Claude.ai

## 🌟 Features

### OAuth 2.1 Compliance
- ✅ RFC 8414 OAuth Authorization Server Metadata discovery
- ✅ RFC 7591 Dynamic Client Registration
- ✅ PKCE (Proof Key for Code Exchange) support
- ✅ Secure token storage with KV namespace
- ✅ End-to-end encryption for user properties

### MCP Tools
- **Get Today's Tasks**: Retrieve tasks assigned for today
- **Get Today's Adhoc Tasks**: Retrieve ad-hoc tasks for today
- **Get Today's Pending Tasks**: Retrieve pending tasks for today
- **Create Task**: Create new tasks in Trackex

### Authentication Flow
1. Claude.ai discovers OAuth endpoints via `/.well-known/oauth-authorization-server`
2. User is redirected to Microsoft OAuth for authentication
3. After Microsoft auth, user is redirected back to `/callback`
4. Server creates Trackex session and completes OAuth authorization
5. Claude.ai receives access token for MCP API calls

## 📁 Project Structure

```
trackex-mcp-server/
├── src/
│   ├── index.ts                 # Main OAuth provider configuration
│   ├── mcp-server-handler.ts    # MCP protocol implementation
│   ├── trackex-api-client.ts    # Trackex API integration
│   ├── types.ts                 # TypeScript interfaces
│   └── tools.ts                 # MCP tool definitions
├── test/
│   └── index.spec.ts           # Unit tests
├── test-oauth-discovery.js      # OAuth endpoint testing
├── test-mcp.js                 # MCP protocol testing
├── wrangler.jsonc              # Cloudflare Workers configuration
└── package.json                # Dependencies and scripts
```

## 🛠️ Setup

### Prerequisites

1. **Cloudflare Account**: For Workers deployment
2. **Microsoft Azure App Registration**: For OAuth authentication
3. **Trackex API Access**: Backend API credentials (optional - mock mode available)

### Installation

1. **Clone and install dependencies**:
   ```bash
   npm install
   ```

2. **Create KV Namespace**:
   ```bash
   wrangler kv:namespace create "OAUTH_KV"
   ```
   
   Update `wrangler.jsonc` with the returned namespace ID:
   ```json
   "kv_namespaces": [
     {
       "binding": "OAUTH_KV",
       "id": "your-actual-kv-namespace-id"
     }
   ]
   ```

3. **Set Environment Secrets**:
   ```bash
   wrangler secret put MICROSOFT_CLIENT_ID
   wrangler secret put MICROSOFT_CLIENT_SECRET
   wrangler secret put MICROSOFT_TENANT_ID
   ```

4. **Configure Microsoft Azure App**:
   - Create an App Registration in Azure Portal
   - Set redirect URI: `https://your-worker.workers.dev/callback`
   - Grant necessary permissions (User.Read, profile, email)

5. **Configure Mock Mode (Optional)**:
   - Set `TRACKEX_MOCK_MODE=true` in `wrangler.jsonc` to enable mock API responses
   - Useful for development when Trackex API endpoints are not yet available
   - Mock mode provides realistic sample data for all API calls

### Deployment

```bash
# Deploy to Cloudflare Workers
npm run deploy

# Test locally
npm run dev
```

## 🎭 Mock Mode

The MCP server includes a comprehensive mock mode for development and testing when the Trackex API is not available.

### Features

- **Automatic Fallback**: If the Trackex API returns 404 or is unreachable, automatically falls back to mock mode
- **Realistic Data**: Provides sample tasks, user info, and session management
- **Full API Coverage**: All Trackex API methods have mock implementations
- **Easy Toggle**: Enable/disable via `TRACKEX_MOCK_MODE` environment variable

### Configuration

**Enable Mock Mode:**
```bash
# In wrangler.jsonc
"vars": {
  "TRACKEX_MOCK_MODE": "true"
}
```

**Disable Mock Mode:**
```bash
# In wrangler.jsonc
"vars": {
  "TRACKEX_MOCK_MODE": "false"
}
```

### Mock Data

Mock mode provides:
- **Sessions**: Valid mock session tokens with user information
- **Tasks**: Sample tasks for today, adhoc, and pending categories
- **User Info**: Mock user profiles based on Microsoft OAuth data
- **Task Creation**: Simulated task creation with realistic responses

### Switching to Production

When your Trackex API endpoints are ready:

1. Set `TRACKEX_MOCK_MODE=false` in `wrangler.jsonc`
2. Ensure `TRACKEX_API_BASE_URL` points to your real API
3. Deploy the updated configuration
4. The system will automatically use real API calls

**Required Trackex API Endpoints:**
- `POST /api/auth/microsoft-token` - Create session from Microsoft token
- `GET /api/tasks/today` - Get today's tasks
- `GET /api/tasks/today/adhoc` - Get today's adhoc tasks
- `GET /api/tasks/today/pending` - Get today's pending tasks
- `POST /api/tasks` - Create new task
- `GET /api/auth/validate` - Validate session token
- `GET /api/user/me` - Get user information

## 🧪 Testing

### Test OAuth Discovery
```bash
# Test local development
node test-oauth-discovery.js

# Test production deployment
node test-oauth-discovery.js https://your-worker.workers.dev
```

### Test MCP Protocol
```bash
# Test local development
npm run test-mcp

# Test production deployment
npm run test-mcp:prod
```

### Test Claude.ai Integration
```bash
# Test Claude.ai compatibility endpoints
npm run test-claude

# Test production deployment
npm run test-claude:prod
```

## 🔗 Integration with Claude.ai

### Remote MCP Server Configuration

This server is designed to work as a **Remote MCP Server** with Claude.ai. Simply add your server URL to Claude.ai's remote MCP server configuration:

**Server URL**: `https://your-worker.workers.dev`

Claude.ai will automatically:
1. Discover server capabilities via `/.well-known/oauth-authorization-server`
2. Discover MCP-specific metadata via `/.well-known/mcp`
3. Handle OAuth 2.1 authentication flow
4. Connect to the MCP endpoint at `/mcp`

### Discovery Endpoints

The server provides two discovery endpoints for Claude.ai compatibility:

1. **OAuth Discovery**: `/.well-known/oauth-authorization-server`
   - Provides OAuth 2.1 metadata
   - Includes MCP endpoint location (`/mcp`)
   - Server info and capabilities

2. **MCP Discovery**: `/.well-known/mcp`
   - MCP protocol version (2024-11-05)
   - Server capabilities and tools
   - Transport configuration (SSE)
   - Authentication details

### Legacy MCP Configuration (for reference)

For older MCP clients, you can still use the traditional configuration:

```json
{
  "mcpServers": {
    "trackex": {
      "command": "npx",
      "args": [
        "@modelcontextprotocol/server-everything",
        "--oauth-discovery-url",
        "https://your-worker.workers.dev/.well-known/oauth-authorization-server"
      ]
    }
  }
}
```

### OAuth Flow

1. **Discovery**: Claude.ai fetches OAuth metadata from `/.well-known/oauth-authorization-server`
2. **Registration**: Claude.ai registers as an OAuth client via `/oauth/register`
3. **Authorization**: User is redirected to `/authorize` → Microsoft OAuth → `/callback`
4. **Token Exchange**: Claude.ai exchanges authorization code for access token via `/oauth/token`
5. **API Access**: Claude.ai makes authenticated requests to `/sse` with Bearer token

## 🔧 Configuration

### Environment Variables

| Variable | Description | Example |
|----------|-------------|---------|
| `MICROSOFT_CLIENT_ID` | Azure App Registration Client ID | `12345678-1234-1234-1234-123456789012` |
| `MICROSOFT_CLIENT_SECRET` | Azure App Registration Client Secret | `your-secret-value` |
| `MICROSOFT_TENANT_ID` | Azure AD Tenant ID | `common` or specific tenant ID |
| `TRACKEX_API_BASE_URL` | Trackex API base URL | `https://api.trackex.co` |
| `MCP_SERVER_NAME` | Server name for identification | `trackex-mcp-server` |
| `MCP_SERVER_VERSION` | Server version | `1.0.0` |
| `ALLOWED_ORIGINS` | CORS allowed origins | `*` |

### KV Namespace

The `OAUTH_KV` namespace stores:
- OAuth client registrations
- Authorization grants
- Access tokens (hashed)
- Encrypted user properties

## 🛡️ Security Features

### OAuth 2.1 Compliance
- **PKCE Required**: All authorization flows use PKCE for security
- **Token Hashing**: Access tokens stored as hashes, not plaintext
- **Property Encryption**: User properties encrypted with token-derived keys
- **Single-Use Codes**: Authorization codes are single-use with expiration

### Data Protection
- **End-to-End Encryption**: Sensitive data encrypted in storage
- **Minimal Storage**: Only necessary metadata stored unencrypted
- **Secure Headers**: CORS and security headers properly configured

## 📊 Monitoring

### Available Scripts

```bash
npm run dev          # Local development
npm run deploy       # Deploy to production
npm run test         # Run unit tests
npm run test-mcp     # Test MCP protocol
npm run logs         # View production logs
npm run secrets:list # List configured secrets
```

### Health Monitoring

The server provides built-in monitoring through:
- Cloudflare Workers analytics
- Real-time logs via `wrangler tail`
- OAuth error callbacks for debugging

## 🚨 Troubleshooting

### Common Issues

1. **"failed to retrieve state data"**:
   - Ensure KV namespace is properly configured
   - Check that OAUTH_KV binding is correct in wrangler.jsonc

2. **Microsoft OAuth redirect errors**:
   - Verify redirect URI matches Azure App Registration
   - Check Microsoft Client ID/Secret are correctly set

3. **MCP connection failures**:
   - Verify OAuth discovery URL is accessible
   - Check CORS headers are properly configured

### Debug Mode

Enable debug logging by setting `DEBUG=true` in environment variables.

## 📝 API Endpoints

### Discovery Endpoints
- `GET /.well-known/oauth-authorization-server` - OAuth 2.1 metadata discovery (Claude.ai compatible)
- `GET /.well-known/mcp` - MCP capability discovery (Claude.ai compatible)

### OAuth Endpoints (handled by workers-oauth-provider)
- `POST /oauth/register` - Dynamic client registration
- `GET /authorize` - Authorization endpoint (redirects to Microsoft)
- `POST /oauth/token` - Token exchange endpoint (with PKCE support)

### MCP Endpoints
- `GET /mcp` - MCP capabilities discovery (primary endpoint)
- `POST /mcp` - MCP JSON-RPC endpoint (requires auth for tool calls)
- `GET /sse` - Legacy MCP endpoint (fallback compatibility)
- `POST /sse` - Legacy MCP JSON-RPC endpoint (fallback compatibility)

### Custom Endpoints
- `GET /callback` - Microsoft OAuth callback handler

## 🔄 Version History

### v1.1.0 (Current)
- ✅ **Claude.ai Remote MCP Server Integration**
- ✅ Added `/.well-known/mcp` discovery endpoint
- ✅ Updated OAuth discovery for Claude.ai compatibility
- ✅ Changed primary MCP endpoint to `/mcp` (with `/sse` fallback)
- ✅ Updated MCP protocol version to 2024-11-05
- ✅ Enhanced CORS headers for all responses
- ✅ Improved server info and capabilities structure

### v1.0.0
- ✅ Migrated to `@cloudflare/workers-oauth-provider`
- ✅ Full OAuth 2.1 compliance
- ✅ Microsoft OAuth integration
- ✅ Secure token storage with KV
- ✅ End-to-end encryption
- ✅ Basic Claude.ai compatibility

### Previous Versions
- v0.x: Custom OAuth implementation (deprecated)

## 📞 Support

For issues and questions:
- Create an issue in the repository
- Check Cloudflare Workers logs for debugging
- Verify OAuth configuration with test scripts

## 📄 License

This project is licensed under the MIT License. 