# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Build and Test Commands
```bash
npm run build # TypeScript compilation
npm test # Run all tests
npm run test:watch # Run tests in watch mode
npx vitest run src/auth/session.test.ts # Run single test file
npm run dev # Development mode with tsx watch
npm start # Run compiled server
```
## Architecture
Gmail MCP Server with read-only access and label-based filtering. Implements MCP SDK's OAuth 2.1 with PKCE for authentication.
### Two-Tier OAuth Flow
The server bridges Google OAuth with MCP OAuth:
1. **MCP Client → Server**: Client initiates OAuth via `mcpAuthRouter` (standard MCP SDK flow)
2. **Server → Google**: `GmailOAuthServerProvider.authorize()` creates pending request, redirects to Google
3. **Google → Server**: `/callback` receives Google auth code, `oauth-bridge.getRedirectUrl()` exchanges it for tokens
4. **Server → MCP Client**: Returns MCP auth code, client exchanges for session token (used as bearer token)
Session token (not Google access token) is the MCP bearer token. Google tokens are stored server-side in `SessionStore`.
### Key Components
- `src/index.ts` - Express HTTPS server setup, registers routes
- `src/auth/gmail/oauth-provider.ts` - `GmailOAuthServerProvider` implements MCP SDK's `OAuthServerProvider`, manages pending auth requests and auth codes
- `src/auth/gmail/oauth-handler.ts` - Google OAuth operations (auth URL, token exchange, refresh)
- `src/auth/session.ts` - `SessionStore` manages session lifecycle (temp → active), stores Google tokens
- `src/auth/routes.ts` - OAuth endpoints via `mcpAuthRouter`, `/callback` for Google redirect
- `src/mcp/routes.ts` - `/mcp` endpoint with bearer auth and labels middleware
- `src/mcp/server.ts` - `GmailMCPServer` handles MCP tool requests
- `src/gmail/client.ts` - `GmailClient` wraps Gmail API with label filtering
### Label-Based Access Control
Labels are passed via `allowed_labels` query parameter on `/mcp` endpoint. The `labelsMiddleware` validates and stores them in session. `GmailClient` enforces label filtering on all Gmail API calls.
### Environment Variables
- `OAUTH_CREDENTIALS_PATH` - Path to Google OAuth credentials JSON
- `TLS_KEY_PATH`, `TLS_CERT_PATH` - TLS certificate paths
- `HOST`, `PORT` - Server binding (default: localhost:3000)
- `SESSION_TTL` - Session TTL in seconds (default: 86400)
## Code Style
- 4-space indentation
- ESM modules with `.js` extension in imports
- Tests colocated with source files (`*.test.ts`)