# Code Review MCP Server - Development Guidelines
## Project Overview
This is a Model Context Protocol (MCP) server that provides GitLab code review functionality. It exposes four main tools for interacting with GitLab merge requests:
- `get-projects` - Search and list GitLab projects
- `get-merge-requests` - List merge requests from a project
- `get-merge-request-diffs` - Get code diffs for specific merge requests
- `create-draft-note` - Create draft comments on merge requests
## Build/Configuration Instructions
### Prerequisites
- Node.js (ES2022+ support required)
- pnpm package manager (version 10.11.1+ recommended)
- TypeScript 5.8.3+
### Environment Setup
1. **Install dependencies:**
```bash
pnpm install
```
2. **Environment Configuration:**
Copy `.env.example` to `.env` and configure the required variables:
```bash
cp .env.example .env
```
Required environment variables:
- `GITLAB_PAT` - GitLab Personal Access Token with API access
- `GITLAB_API_URL` - GitLab instance URL (e.g., https://gitlab.com)
- `GITLAB_PROJECT_ID` - Default project ID (numeric)
- `SERVER_NAME` - MCP server name identifier
- `SERVER_VERSION` - Server version string
**Important:** The environment validation uses Zod schema and will throw an error on startup if any required variables are missing or invalid.
3. **Build the project:**
```bash
pnpm run build
```
This compiles TypeScript from `src/` to `build/` directory and makes the output executable.
### TypeScript Configuration
The project uses modern TypeScript settings:
- Target: ES2022
- Module: Node16 with Node16 module resolution
- Strict mode enabled
- ES module interop enabled
- Output directory: `./build`
- Root directory: `./src`
## Testing Information
### Running Tests
The project includes a comprehensive test suite that can be run without requiring actual GitLab credentials:
```bash
node test_mcp_server.js
```
This test verifies:
- Build process functionality
- Output file generation and permissions
- Environment variable validation
- MCP server initialization
### Test Structure
The test suite demonstrates:
1. **Build Verification** - Ensures TypeScript compilation works
2. **Output Validation** - Checks that build artifacts are created correctly
3. **Environment Testing** - Validates environment variable handling
4. **Server Initialization** - Tests MCP server startup process
### Adding New Tests
When adding new functionality:
1. **Unit Tests**: Create focused tests for individual functions
2. **Integration Tests**: Test MCP tool interactions
3. **Environment Tests**: Verify new environment variables are properly validated
Example test pattern for MCP tools:
```javascript
// Test MCP tool response format
const testRequest = {
jsonrpc: "2.0",
id: 1,
method: "tools/call",
params: {
name: "tool-name",
arguments: { /* tool arguments */ }
}
};
```
### Manual Testing
For manual testing with actual GitLab integration:
1. Build the project: `pnpm run build`
2. Configure valid GitLab credentials in `.env`
3. Run the server: `node build/index.js`
4. Send JSON-RPC requests via stdio
Example requests are provided in `test_draft_note.js` and `test_projects.js`.
## Development Information
### Code Architecture
**Entry Point**: `src/index.ts`
- Creates MCP server instance
- Registers four GitLab tools
- Handles stdio transport communication
**Environment Management**: `src/env.ts`
- Uses Zod for runtime environment validation
- Exports typed environment configuration
- Fails fast on invalid configuration
**Key Components**:
- `makeGitLabRequest<T>()` - Generic GitLab API client function
- Interface definitions for GitLab entities (MergeRequest, Diff, Project, DraftNote)
- MCP tool handlers with Zod schema validation
### Code Style Guidelines
1. **TypeScript Strict Mode**: All code must pass strict TypeScript checks
2. **Environment Variables**: Always validate through the centralized env.ts module
3. **Error Handling**: Use try-catch blocks and return structured error responses
4. **API Responses**: Follow consistent MCP response format with content arrays
5. **Zod Validation**: All tool parameters must be validated with Zod schemas
### MCP Tool Development Pattern
When adding new MCP tools:
```typescript
server.tool(
"tool-name",
"Tool description",
{
// Zod schema for parameters
param1: z.string().describe("Parameter description"),
param2: z.number().optional().describe("Optional parameter"),
},
async ({ param1, param2 }) => {
// Tool implementation
try {
// Business logic
return {
content: [
{
type: "text",
text: "Response content",
},
],
};
} catch (error) {
// Error handling
return {
content: [
{
type: "text",
text: `Error: ${error.message}`,
},
],
};
}
},
);
```
### GitLab API Integration
**Authentication**: Uses `PRIVATE-TOKEN` header with GitLab PAT
**Base URL Pattern**: `${GITLAB_API_URL}/api/v4/...`
**Error Handling**: All API calls go through `makeGitLabRequest()` with built-in error handling
**Common API Endpoints Used**:
- `/projects` - Project listing and search
- `/projects/{id}/merge_requests` - Merge request operations
- `/projects/{id}/merge_requests/{iid}/diffs` - Diff retrieval
- `/projects/{id}/merge_requests/{iid}/draft_notes` - Draft note creation
### Debugging Tips
1. **Environment Issues**: Check that all required environment variables are set and valid
2. **GitLab API Errors**: Enable verbose logging by checking response status in `makeGitLabRequest()`
3. **MCP Communication**: Server logs to stderr, responses go to stdout
4. **Build Issues**: Ensure TypeScript compilation succeeds before testing
### Package Management
- **Package Manager**: pnpm (specified in package.json)
- **Module Type**: ES modules (`"type": "module"`)
- **Binary**: Executable at `./build/index.js` after build
### Dependencies
**Runtime Dependencies**:
- `@modelcontextprotocol/sdk` - MCP server framework
- `dotenv` - Environment variable loading
- `zod` - Runtime type validation
**Development Dependencies**:
- `@types/node` - Node.js type definitions
- `typescript` - TypeScript compiler
### Performance Considerations
1. **API Rate Limiting**: GitLab APIs have rate limits; consider caching for frequently accessed data
2. **Large Diffs**: Diff responses can be large; consider pagination for large merge requests
3. **Memory Usage**: Server runs indefinitely; monitor for memory leaks in long-running instances
### Security Notes
1. **Token Security**: GitLab PAT should have minimal required permissions
2. **Input Validation**: All user inputs are validated through Zod schemas
3. **Error Messages**: Avoid exposing sensitive information in error responses
4. **Environment Variables**: Never commit actual credentials to version control
## File Structure
```
├── src/
│ ├── index.ts # Main MCP server implementation
│ └── env.ts # Environment configuration and validation
├── build/ # Compiled output (generated)
├── docs/
│ └── system-prompt.md # End-user documentation for AI assistants
├── test_mcp_server.js # Comprehensive test suite
├── test_draft_note.js # Example requests for draft note tool
├── test_projects.js # Example data for projects tool
├── .env.example # Environment variable template
├── package.json # Project configuration
└── tsconfig.json # TypeScript configuration
```