|
| 1 | +# CLAUDE.md |
| 2 | + |
| 3 | +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. |
| 4 | + |
| 5 | +## Project Overview |
| 6 | + |
| 7 | +This is a Model Context Protocol (MCP) server that provides MySQL database access to LLMs like Claude, with enhanced write operation support and Claude Code optimizations. |
| 8 | + |
| 9 | +**Key Technologies:** |
| 10 | + |
| 11 | +- TypeScript with ES Modules (NodeNext) |
| 12 | +- MCP SDK (@modelcontextprotocol/sdk v1.15.1) |
| 13 | +- mysql2 for database connectivity |
| 14 | +- Vitest for testing |
| 15 | +- Express for remote MCP mode (optional) |
| 16 | + |
| 17 | +## Build and Development Commands |
| 18 | + |
| 19 | +### Building |
| 20 | + |
| 21 | +```bash |
| 22 | +# Build TypeScript to dist/ |
| 23 | +pnpm build |
| 24 | + |
| 25 | +# Watch mode (auto-rebuild on changes) |
| 26 | +pnpm watch |
| 27 | +``` |
| 28 | + |
| 29 | +### Running |
| 30 | + |
| 31 | +```bash |
| 32 | +# Run built version |
| 33 | +pnpm start |
| 34 | + |
| 35 | +# Development mode with ts-node |
| 36 | +pnpm dev |
| 37 | + |
| 38 | +# Run directly with environment variables |
| 39 | +pnpm exec |
| 40 | +``` |
| 41 | + |
| 42 | +### Testing |
| 43 | + |
| 44 | +```bash |
| 45 | +# Setup test database (creates mcp_test DB and seeds data) |
| 46 | +pnpm run setup:test:db |
| 47 | + |
| 48 | +# Run all tests (includes pretest hook that runs setup:test:db) |
| 49 | +pnpm test |
| 50 | + |
| 51 | +# Run specific test suites |
| 52 | +pnpm test:unit # Unit tests only |
| 53 | +pnpm test:integration # Integration tests only |
| 54 | +pnpm test:e2e # End-to-end tests only |
| 55 | +pnpm test:socket # Socket connection tests |
| 56 | + |
| 57 | +# Watch mode for development |
| 58 | +pnpm test:watch |
| 59 | + |
| 60 | +# Coverage report |
| 61 | +pnpm test:coverage |
| 62 | +``` |
| 63 | + |
| 64 | +**Test Environment Requirements:** |
| 65 | + |
| 66 | +- MySQL server running locally or remotely |
| 67 | +- Test database user: `mcp_test` with password `mcp_test_password` |
| 68 | +- Test database: `mcp_test` |
| 69 | +- Configuration via `.env.test` file |
| 70 | + |
| 71 | +### Linting |
| 72 | + |
| 73 | +```bash |
| 74 | +pnpm lint |
| 75 | +``` |
| 76 | + |
| 77 | +## Architecture |
| 78 | + |
| 79 | +### Core Entry Point |
| 80 | + |
| 81 | +- `index.ts` - Main server file that exports `createMcpServer()` function |
| 82 | + - Supports both stdio and HTTP transport modes |
| 83 | + - Handles MCP protocol setup and request routing |
| 84 | + - Configures shutdown handlers for graceful cleanup |
| 85 | + |
| 86 | +### Key Modules |
| 87 | + |
| 88 | +**Configuration (`src/config/index.ts`)** |
| 89 | + |
| 90 | +- Loads environment variables via dotenv |
| 91 | +- Exports connection config, permission flags, and mode detection |
| 92 | +- Key exports: |
| 93 | + - `mcpConfig` - MySQL connection configuration |
| 94 | + - `isMultiDbMode` - Boolean indicating multi-database mode |
| 95 | + - `ALLOW_*_OPERATION` - Global write permission flags |
| 96 | + - `SCHEMA_*_PERMISSIONS` - Schema-specific permission maps |
| 97 | + - `MYSQL_DISABLE_READ_ONLY_TRANSACTIONS` - Control transaction mode |
| 98 | + |
| 99 | +**Database Layer (`src/db/index.ts`)** |
| 100 | + |
| 101 | +- Connection pooling via `getPool()` and lazy-loaded `poolPromise` |
| 102 | +- Three query execution methods: |
| 103 | + - `executeQuery<T>()` - Basic query execution |
| 104 | + - `executeReadOnlyQuery<T>()` - Enforces read-only transaction mode (unless disabled) |
| 105 | + - `executeWriteQuery<T>()` - Handles INSERT/UPDATE/DELETE/DDL with transactions |
| 106 | +- Permission checking integrated into query execution |
| 107 | +- Schema extraction from queries for permission enforcement |
| 108 | + |
| 109 | +**Permissions (`src/db/permissions.ts`)** |
| 110 | + |
| 111 | +- Schema-specific permission checking functions: |
| 112 | + - `isInsertAllowedForSchema(schema)` |
| 113 | + - `isUpdateAllowedForSchema(schema)` |
| 114 | + - `isDeleteAllowedForSchema(schema)` |
| 115 | + - `isDDLAllowedForSchema(schema)` |
| 116 | +- Falls back to global permissions if no schema-specific rule exists |
| 117 | + |
| 118 | +**Utilities (`src/db/utils.ts`)** |
| 119 | + |
| 120 | +- `getQueryTypes()` - Parses SQL to identify operation types (SELECT, INSERT, etc.) |
| 121 | +- `extractSchemaFromQuery()` - Extracts database schema from qualified table names or USE statements |
| 122 | + |
| 123 | +### MCP Protocol Implementation |
| 124 | + |
| 125 | +**Resources** (Database introspection): |
| 126 | + |
| 127 | +- `ListResourcesRequest` - Returns all tables across accessible schemas |
| 128 | +- `ReadResourceRequest` - Returns column metadata for specific tables |
| 129 | +- URIs: `mysql://tables` and `mysql://tables/{tableName}` |
| 130 | + |
| 131 | +**Tools** (Query execution): |
| 132 | + |
| 133 | +- `mysql_query` - Single tool that executes SQL queries |
| 134 | +- Input: `{ sql: string }` |
| 135 | +- Output: JSON result set with execution time |
| 136 | +- Enforces permissions based on query type and target schema |
| 137 | + |
| 138 | +### Multi-Database Mode |
| 139 | + |
| 140 | +When `MYSQL_DB` environment variable is empty or unset: |
| 141 | + |
| 142 | +- Server operates in multi-DB mode |
| 143 | +- Queries must use fully qualified table names (`database.table`) or `USE` statements |
| 144 | +- Schema-specific permissions apply per database |
| 145 | +- Write operations disabled by default unless `MULTI_DB_WRITE_MODE=true` |
| 146 | + |
| 147 | +### Permission System |
| 148 | + |
| 149 | +**Two-Level Hierarchy:** |
| 150 | + |
| 151 | +1. Global flags: `ALLOW_INSERT_OPERATION`, `ALLOW_UPDATE_OPERATION`, `ALLOW_DELETE_OPERATION`, `ALLOW_DDL_OPERATION` |
| 152 | +2. Schema-specific overrides: `SCHEMA_*_PERMISSIONS` environment variables |
| 153 | + |
| 154 | +**Format:** `SCHEMA_INSERT_PERMISSIONS=development:true,test:true,production:false` |
| 155 | + |
| 156 | +**Transaction Safety:** |
| 157 | + |
| 158 | +- Read operations use `SET SESSION TRANSACTION READ ONLY` by default |
| 159 | +- Can be disabled with `MYSQL_DISABLE_READ_ONLY_TRANSACTIONS=true` for DDL support |
| 160 | +- Write operations use explicit transactions with commit/rollback |
| 161 | + |
| 162 | +### Remote MCP Mode |
| 163 | + |
| 164 | +When `IS_REMOTE_MCP=true` and `REMOTE_SECRET_KEY` is set: |
| 165 | + |
| 166 | +- Starts Express HTTP server on `PORT` (default 3000) |
| 167 | +- Accepts POST requests to `/mcp` endpoint |
| 168 | +- Requires `Authorization: Bearer <REMOTE_SECRET_KEY>` header |
| 169 | +- Uses StreamableHTTPServerTransport instead of stdio |
| 170 | + |
| 171 | +## Project Structure |
| 172 | + |
| 173 | +```markdown |
| 174 | +. |
| 175 | +├── index.ts # Main entry point |
| 176 | +├── src/ |
| 177 | +│ ├── config/index.ts # Configuration and env loading |
| 178 | +│ ├── db/ |
| 179 | +│ │ ├── index.ts # Database connection and query execution |
| 180 | +│ │ ├── permissions.ts # Schema permission checks |
| 181 | +│ │ └── utils.ts # SQL parsing utilities |
| 182 | +│ ├── types/index.ts # TypeScript type definitions |
| 183 | +│ └── utils/index.ts # General utilities (logging, etc.) |
| 184 | +├── scripts/ |
| 185 | +│ └── setup-test-db.ts # Test database setup script |
| 186 | +├── tests/ |
| 187 | +│ ├── unit/ # Unit tests |
| 188 | +│ ├── integration/ # Integration tests (MySQL required) |
| 189 | +│ └── e2e/ # End-to-end server tests |
| 190 | +├── evals.ts # MCP evaluation scripts |
| 191 | +└── dist/ # Compiled JavaScript output |
| 192 | +``` |
| 193 | + |
| 194 | +## Important Development Notes |
| 195 | + |
| 196 | +### Connection Methods |
| 197 | + |
| 198 | +The server supports two MySQL connection methods: |
| 199 | + |
| 200 | +1. **TCP/IP**: Set `MYSQL_HOST` and `MYSQL_PORT` |
| 201 | +2. **Unix Socket**: Set `MYSQL_SOCKET_PATH` (takes precedence over TCP/IP) |
| 202 | + |
| 203 | +### Testing Strategy |
| 204 | + |
| 205 | +- Tests require a real MySQL instance |
| 206 | +- `setup:test:db` script must run before tests to create schema and seed data |
| 207 | +- Use `.env.test` for test-specific configuration |
| 208 | +- Integration tests cover multi-DB mode, schema permissions, and socket connections |
| 209 | + |
| 210 | +### ES Module Configuration |
| 211 | + |
| 212 | +- Uses `"type": "module"` in package.json |
| 213 | +- All imports must include `.js` extension (TypeScript quirk for ES modules) |
| 214 | +- `tsconfig.json` uses `"module": "NodeNext"` and `"moduleResolution": "NodeNext"` |
| 215 | + |
| 216 | +### Error Handling |
| 217 | + |
| 218 | +- `safeExit()` function prevents process.exit during tests |
| 219 | +- All database operations use try/catch with proper connection release |
| 220 | +- Query errors include execution context and schema information |
| 221 | + |
| 222 | +### Performance Considerations |
| 223 | + |
| 224 | +- Connection pooling with configurable limit (default 10) |
| 225 | +- Query execution timing tracked via `performance.now()` |
| 226 | +- Lazy pool initialization on first query |
| 227 | + |
| 228 | +## Common Development Tasks |
| 229 | + |
| 230 | +### Adding New Query Types |
| 231 | + |
| 232 | +1. Update SQL parser logic in `src/db/utils.ts` (`getQueryTypes`) |
| 233 | +2. Add permission checking in `src/db/index.ts` (`executeReadOnlyQuery`) |
| 234 | +3. Handle result formatting in `executeWriteQuery` if needed |
| 235 | +4. Add integration tests in `tests/integration/` |
| 236 | + |
| 237 | +### Adding Environment Variables |
| 238 | + |
| 239 | +1. Add to `.env` example in README |
| 240 | +2. Parse in `src/config/index.ts` |
| 241 | +3. Export for use in other modules |
| 242 | +4. Document in README's Environment Variables section |
| 243 | + |
| 244 | +### Modifying Permission Logic |
| 245 | + |
| 246 | +1. Update permission functions in `src/db/permissions.ts` |
| 247 | +2. Modify schema extraction if needed in `src/db/utils.ts` |
| 248 | +3. Test with schema-specific permission scenarios |
| 249 | +4. Update permission checking in `executeReadOnlyQuery` |
0 commit comments