Skip to main content
Glama
gurkanfikretgunak

CRM Employee Management MCP Server

README.md
# MCP Gateway and Inspector

A modular Microservice Communication Protocol (MCP) Gateway package for wrapping GraphQL APIs with standardized tracing, authentication, and error handling. Includes a full-featured web inspector for testing and monitoring.

## Features

### MCP Gateway Package
- **Modular Design**: Reusable Python package that can be installed via pip or used standalone
- **Tracing**: Automatic correlation ID generation and propagation
- **Authentication**: Bearer token validation middleware
- **Error Handling**: Standardized MCP error codes and responses
- **GraphQL Proxy**: Seamless proxying to backend GraphQL services

### MCP Inspector Web App
- **Request Builder**: Visual GraphQL query editor
- **Response Viewer**: Formatted JSON response display with error highlighting
- **Request History**: Track and replay previous requests
- **Environment Management**: Switch between dev/staging/prod environments
- **Request Templates**: Save and reuse common queries
- **Export/Import**: Share requests as JSON files
- **Correlation ID Tracking**: View and copy correlation IDs for debugging

## Installation

### Python Package

```bash
# Install dependencies
pip install -r requirements.txt

# Or install as a package
pip install -e .
```

### Inspector Web App

```bash
cd inspector
npm install
```

## Configuration

Copy `.env.example` to `.env` and configure:

```bash
cp .env.example .env
```

Key configuration options:
- `TARGET_GRAPHQL_URL`: Backend GraphQL API endpoint
- `PORT`: Gateway server port (default: 8080)
- `ENABLE_AUTH`: Enable/disable authentication (default: true)
- `LOG_LEVEL`: Logging level (DEBUG, INFO, WARNING, ERROR)

## Usage

### Running the Gateway

```bash
# Using uvicorn directly
uvicorn gateway.main:app --reload --host 0.0.0.0 --port 8080

# Or using Python
python -m gateway.main
```

The gateway will be available at `http://localhost:8080`

### Running Mock Backend (for Testing)

If you don't have a real GraphQL backend, you can use the included mock backend for testing:

```bash
# Easy way: Use the startup script
./start_mock_backend.sh

# Or manually:
python3 mock_backend.py
# or
uvicorn mock_backend:app --reload --port 8081
```

The mock backend will be available at `http://localhost:8081` and supports common GraphQL queries like:
- `query { hello }`
- `query { user(id: "1") { id name email } }`
- `query { users { id name email } }`
- `mutation { createUser(input: {name: "John", email: "john@example.com"}) { id } }`

**Important:** 
- Make sure the mock backend is running before starting the gateway
- Test the backend: `curl http://localhost:8081/health`
- If you get "Connection refused", the mock backend is not running
- See `QUICKSTART.md` for detailed troubleshooting

### Running MCP Server for LLM Integration

The CRM Employee Management MCP Server (Model Context Protocol) exposes CRM functions as tools that LLMs can use:

```bash
# Install MCP SDK first
pip install git+https://github.com/modelcontextprotocol/python-sdk.git

# Start the MCP server
./start_crm_mcp.sh
# or
python3 crm_mcp_server.py
```

**MCP Server Tools:**
- `list_employees` - List/search employees with filters
- `get_employee` - Get employee details by ID
- `create_employee` - Create new employee
- `update_employee` - Update employee information
- `delete_employee` - Delete employee (soft delete)
- `search_employees` - Search employees by name, email, etc.
- `get_employee_stats` - Get employee statistics
- `get_departments` - List all departments

**Configuration:**
See `MCP_SETUP.md` for detailed setup instructions for Claude Desktop, Cursor, and other MCP-compatible clients.

**Example Usage with LLM:**
Once connected to Claude Desktop or Cursor, you can use natural language:
- "List all employees in the Engineering department"
- "Show me employee statistics"
- "Create a new employee named John Doe in Sales"
- "Search for employees with 'engineer' in their position"

### Running CRM REST API Server

The CRM Employee Management REST API Server is a comprehensive REST API server for managing employee data:

```bash
# Easy way: Use the startup script
./start_crm_rest.sh

# Or manually:
python3 crm_rest_server.py
# or
uvicorn crm_rest_server:app --reload --port 8083
```

The CRM server will be available at `http://localhost:8083` and provides:

**Employee Management Endpoints:**
- `GET /api/employees` - List all employees (with filtering, pagination, sorting)
- `GET /api/employees/{id}` - Get employee details
- `POST /api/employees` - Create new employee
- `PUT /api/employees/{id}` - Update employee
- `DELETE /api/employees/{id}` - Delete employee (soft delete)
- `GET /api/employees/search?q={query}` - Search employees
- `GET /api/employees/department/{dept}` - Get employees by department
- `GET /api/employees/stats` - Get employee statistics
- `GET /api/departments` - List all departments

**Example Employee Data Model:**
```json
{
  "id": "emp-001",
  "firstName": "Ahmet",
  "lastName": "Yılmaz",
  "email": "ahmet.yilmaz@company.com",
  "phone": "+90 555 123 4567",
  "department": "Engineering",
  "position": "Senior Software Engineer",
  "salary": 85000.0,
  "hireDate": "2020-03-15",
  "status": "active",
  "address": "Atatürk Cad. No:123",
  "city": "Istanbul",
  "country": "Turkey",
  "managerId": null,
  "skills": ["Python", "JavaScript", "React", "Node.js"],
  "notes": "Team lead candidate"
}
```

### Running the Inspector

```bash
cd inspector
npm run dev
```

The inspector will be available at `http://localhost:3000` and includes:
- **GraphQL Inspector**: Test GraphQL queries and mutations
- **CRM Manager**: Full-featured employee management interface with:
  - Employee list with search and filtering
  - Add/Edit/Delete employees
  - Department-based filtering
  - Employee statistics dashboard

### Quick Start - All Services at Once

To start all four services (Mock Backend, Gateway, CRM MCP Server, and Inspector) with a single command:

```bash
./dev-live.sh
```

This script will:
- Check dependencies and port availability
- Start all services in separate terminal windows
- Display service URLs and useful endpoints
- Show informative status messages

**Note:** On macOS, the script opens new Terminal windows. On Linux, it uses `gnome-terminal`.

**Services Started:**
1. Mock Backend (port 8081) - GraphQL test backend
2. Gateway (port 8080) - MCP Gateway with REST and GraphQL proxy
3. CRM MCP Server (port 8083) - Employee management REST API
4. Inspector (port 3000) - Web UI for testing and management

### Stopping All Services

To stop all services and free up ports:

```bash
./dev-live-shutdown.sh
```

This script will stop all running services (Mock Backend, Gateway, CRM MCP Server, Inspector) and verify that ports 8081, 8080, 8083, and 3000 are free.

### Using the MCP Package in Your Project

#### As a Package

```python
from mcp import MCPGateway, TracingMiddleware, AuthMiddleware
from fastapi import FastAPI

app = FastAPI()
app.add_middleware(TracingMiddleware)

gateway = MCPGateway(target_url="http://backend:8081/graphql")
auth = AuthMiddleware()

@app.post("/graphql")
async def graphql_proxy(request: Request, graphql_request: MCPRequest):
    auth.validate_request(request)
    return await gateway.proxy_graphql_request(request, graphql_request)
```

#### Standalone Module

Copy the `mcp/` directory to your project and import as needed.

## API Endpoints

### Gateway Endpoints

- `POST /graphql` - Proxy GraphQL requests
- `POST /mcp/proxy` - Dynamic GraphQL proxy (for Inspector)
- `POST /mcp/rest-proxy` - REST API proxy (supports GET, POST, PUT, DELETE, PATCH)
- `GET /health` - Health check endpoint

### Request Format

```json
{
  "query": "query { hello }",
  "operationName": "MyQuery",
  "variables": { "key": "value" }
}
```

### Authentication

Include Bearer token in Authorization header:

```
Authorization: Bearer your-token-here
```

## Error Codes

- `MCP-401`: Authentication failed
- `MCP-503`: Backend service unavailable
- `BACKEND-ERROR`: Backend service error
- `MCP-500`: Internal server error

## Project Structure

```
mcp/
├── mcp/                    # Core MCP package (modular, reusable)
│   ├── __init__.py
│   ├── gateway.py          # Gateway base class
│   ├── middleware.py       # Tracing middleware
│   ├── auth.py             # Authentication handlers
│   ├── errors.py           # Error handling
│   └── models.py            # Pydantic models
├── gateway/                 # FastAPI application
│   ├── main.py             # FastAPI app entry point
│   └── config.py           # Configuration management
├── inspector/               # Next.js web application
│   ├── app/                # Next.js app directory
│   ├── components/         # React components
│   └── lib/                # Utilities
├── crm_rest_server.py      # CRM REST API server
├── crm_mcp_server.py       # CRM MCP Server (for LLM integration)
├── mcp_config.json         # MCP client configuration example
├── MCP_SETUP.md            # MCP Server setup guide
├── pyproject.toml          # Python package config
├── requirements.txt        # Python dependencies
└── README.md               # This file
```

## Testing

### Test the Gateway

```bash
# Successful request
curl -X POST "http://localhost:8080/graphql" \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer my-valid-token-123" \
     -d '{
         "query": "query { hello }",
         "operationName": "TestQuery"
     }'

# Authentication error
curl -X POST "http://localhost:8080/graphql" \
     -H "Content-Type: application/json" \
     -d '{
         "query": "query { hello }"
     }'
```

### Using the Inspector

1. Start the gateway and inspector
2. Open `http://localhost:3000` in your browser
3. Configure an environment (default: `http://localhost:8080`)
4. Enter your GraphQL query
5. Add authentication token if required
6. Click "Send Request"
7. View response, correlation ID, and timing information

## Development

### Python Development

```bash
# Install development dependencies
pip install -e ".[dev]"

# Run tests (when implemented)
pytest

# Format code
black .
ruff check .
```

### Inspector Development

```bash
cd inspector
npm run dev      # Development server
npm run build    # Production build
npm run lint     # Lint code
```

## MCP Server for LLM Integration

This project includes a Model Context Protocol (MCP) server that allows LLMs (like Claude Desktop, Cursor) to interact with the CRM system through natural language.

### Quick Start

1. **Install MCP SDK:**
```bash
pip install git+https://github.com/modelcontextprotocol/python-sdk.git
```

2. **Start the MCP Server:**
```bash
./start_crm_mcp.sh
# or
python3 crm_mcp_server.py
```

3. **Configure Claude Desktop or Cursor:**
   - See `MCP_SETUP.md` for detailed instructions
   - Add the MCP server configuration pointing to `crm_mcp_server.py`

### Available Tools

The MCP server exposes 8 tools for comprehensive CRM management:

- **list_employees** - List/search employees with optional filtering by department, status, or search query
- **get_employee** - Get detailed information about a specific employee by ID
- **create_employee** - Create a new employee record in the CRM system
- **update_employee** - Update an existing employee's information
- **delete_employee** - Delete an employee (soft delete - sets status to 'terminated')
- **search_employees** - Search for employees by name, email, position, or department
- **get_employee_stats** - Get statistics and analytics about employees
- **get_departments** - Get a list of all departments in the organization

### Example Usage

Once connected to Claude Desktop or Cursor, you can use natural language:

```
"Show me all employees in the Engineering department"
"Create a new employee named Jane Smith in Sales"
"What are the employee statistics?"
"Search for employees with 'manager' in their title"
"Update employee emp-001's salary to 90000"
```

The LLM will automatically use the appropriate MCP tools to fulfill your requests.

### Data Store Integration

The MCP server uses the same data store as the REST API server (`crm_rest_server.py`). Both servers share the same `employees_db` dictionary, so changes made through one interface are visible in the other.

### Documentation

For complete setup instructions, see `MCP_SETUP.md`.

## License

MIT

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.