npm package: @haneeshpld/csp-mcp
Description: Mock IBM CSP Entitlement Service MCP Server for Watson Orchestrate
Author: Your Name
Latest version: 1.0.6

# Mock IBM CSP Entitlement Service - Salesforce-Like Support System

A comprehensive Python-based mock implementation of IBM CSP (Customer Support Platform) that simulates a complete Salesforce-like customer service system. Features products, support cases, comments, entitlements, and knowledge articles - all powered by JSON data without requiring a database.

## 🌟 What's New in v1.0.4

**Complete Salesforce-Like Experience:**
- ✅ **No Database Required** - All data stored in JSON files
- ✅ **10 IBM Products** - DB2, WebSphere, MQ, Integration Bus, SPSS, Cognos, DataStage, Guardium, QRadar, Cloud Pak for Data
- ✅ **12 Support Cases** - Full lifecycle with open, in-progress, and closed states
- ✅ **27 Comments** - Rich conversation history between customers and IBM support
- ✅ **11 MCP Tools** - Enhanced tools for Watson Orchestrate integration
- ✅ **Product Issue Tracking** - Primary tool for "I have issues with [product]" scenarios

## Overview

This mock service provides:

- **Salesforce-Like Support System** with products, cases, comments, and resolutions
- **MCP Server** with 11 tools for Watson Orchestrate and AI assistants
- **REST API endpoints** for direct HTTP access
- **JSON-Based Data** - No database setup required
- **Rich Mock Data** - Realistic scenarios with complete conversation history
- **Entitlement Management** - Product access control and validation

## Architecture

```
┌─────────────────────────────────────────────────────────┐
│                    Client Applications                   │
│         (Watson Orchestrate, AI Assistants, etc.)       │
└────────────────┬────────────────────┬───────────────────┘
                 │                    │
                 │ REST API           │ MCP Protocol
                 │                    │
┌────────────────▼────────────────────▼───────────────────┐
│              FastAPI Server    MCP Server                │
│                                                           │
│  ┌─────────────────────────────────────────────────┐   │
│  │           Authentication Middleware              │   │
│  └─────────────────────────────────────────────────┘   │
│                                                           │
│  ┌─────────────────────────────────────────────────┐   │
│  │          Entitlement Service Layer               │   │
│  │  (Shared by REST API and MCP Tools)              │   │
│  └─────────────────────────────────────────────────┘   │
│                                                           │
│  ┌─────────────────────────────────────────────────┐   │
│  │            In-Memory Database                    │   │
│  │  (Users, Accounts, Entitlements, Assets, etc.)  │   │
│  └─────────────────────────────────────────────────┘   │
└───────────────────────────────────────────────────────────┘
```

## Features

### REST API Endpoints

1. **User-Based Entitlement** (`POST /services/apexrest/ICNBasedEntitlement/v1`)
   - Validates product-level entitlements for users
   - Supports multiple SLCs (Support Level Codes)
   - Version-based service extension checks
   - Adopter-specific SLC eligibility

2. **Machine-Based Entitlement** (`POST /services/apexrest/MachineBasedEntitlement/v1`)
   - Validates entitlements for machines/assets
   - Supports machine type/serial number lookup
   - Default SLC mapping for machine types
   - Summary-only response format

3. **Part-ID Based Entitlement** (`POST /services/apexrest/PartIdBasedEntitlement/v1`)
   - Validates entitlements by offering part IDs
   - Supports expired entitlement detection
   - Per-part entitlement status

### MCP Tools

1. **check_user_entitlement** - User-based entitlement validation
2. **check_machine_entitlement** - Machine-based entitlement validation
3. **check_part_entitlement** - Part-ID based entitlement validation

### Authentication

Three API adopters are supported:

- **Fix Central** - Broad access to all SLCs
- **Drupal** - Restricted to eligible SLCs only
- **Knowledge Center** - Restricted to eligible SLCs only

## Installation

### Prerequisites

- Python 3.11 or higher
- Node.js 18+ (for npm installation)
- pip or uv package manager

### Option 1: Install via npm (Recommended for MCP Server)

```bash
# Global installation
npm install -g @your-org/mock-csp-entitlement-mcp

# Run MCP server
mock-csp-mcp

# Or use npx without installation
npx @your-org/mock-csp-entitlement-mcp
```

**Note:** Replace `@your-org` with the actual npm package name once published.

### Option 2: Manual Setup

1. **Clone or extract the project:**

```bash
cd mcp-csp
```

2. **Create a virtual environment:**

```bash
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
```

3. **Install dependencies:**

```bash
pip install -e ".[dev]"
```

4. **Configure environment variables:**

```bash
cp .env.example .env
# Edit .env if needed (default values work for local testing)
```

### Mock Data Configuration

The service supports two modes of seed data:

1. **Hardcoded Test Data** (default) - Minimal data for unit tests and API examples
2. **Comprehensive JSON Data** - Realistic dataset with 10 users, 5 accounts, 10 products, 12 entitlements, and 5 assets

To use comprehensive mock data, set the environment variable:

```bash
export USE_JSON_SEED_DATA=true
```

Or add to your `.env` file:

```
USE_JSON_SEED_DATA=true
```

See [COMPREHENSIVE_MOCK_DATA.md](COMPREHENSIVE_MOCK_DATA.md) for detailed documentation on the comprehensive mock data feature.


## Usage

### Running the REST API Server

Start the FastAPI server:

```bash
python -m mock_csp.main
```

Or using uvicorn directly:

```bash
uvicorn mock_csp.main:app --host 0.0.0.0 --port 8000 --reload
```

The API will be available at `http://localhost:8000`

API documentation: `http://localhost:8000/docs`

### Running the MCP Server

Start the MCP server:

```bash
python -m mock_csp.mcp.server
```


### Testing with MCP Inspector

Test and debug the MCP server interactively using the MCP Inspector:

```bash
npx @modelcontextprotocol/inspector python -m mock_csp.mcp.server
```

This will open a web interface where you can:
- View available tools and their schemas
- Execute tools with custom inputs
- See real-time responses
- Debug MCP protocol communication

See [MCP_INSPECTOR_GUIDE.md](MCP_INSPECTOR_GUIDE.md) for detailed instructions.

The MCP server runs on stdio and can be connected to Watson Orchestrate or other MCP clients.

### Running Tests

Run all tests:

```bash
pytest
```

Run with coverage:

```bash
pytest --cov=mock_csp --cov-report=html
```

Run specific test file:

```bash
pytest tests/test_user_entitlement.py -v
```

## API Examples

### User-Based Entitlement

**Request:**

```bash
curl -X POST http://localhost:8000/services/apexrest/ICNBasedEntitlement/v1 \
  -H "Content-Type: application/json" \
  -H "X-API-Key: fc_test_key_12345" \
  -d '{
    "uid": "123450",
    "supportLevelCodes": ["test123", "abc"]
  }'
```

**Response:**

```json
{
  "responseList": [
    {
      "supportLevelCode": "test123",
      "entitled": "Yes"
    },
    {
      "supportLevelCode": "abc",
      "entitled": "Invalid"
    }
  ],
  "isEntitled": true,
  "errorMessage": null
}
```

### Machine-Based Entitlement

**Request:**

```bash
curl -X POST http://localhost:8000/services/apexrest/MachineBasedEntitlement/v1 \
  -H "Content-Type: application/json" \
  -H "X-API-Key: fc_test_key_12345" \
  -d '{
    "machineDetails": [
      {
        "machineType": "7145",
        "serialNumber": "0689018",
        "countryCode": "ZA",
        "products": [
          {
            "supportLevelCode": "SML0D00"
          }
        ]
      }
    ]
  }'
```

**Response:**

```json
{
  "isEntitled": true,
  "errorMessage": null
}
```

### Part-ID Based Entitlement

**Request:**

```bash
curl -X POST http://localhost:8000/services/apexrest/PartIdBasedEntitlement/v1 \
  -H "Content-Type: application/json" \
  -H "X-API-Key: fc_test_key_12345" \
  -d '{
    "uid": "100000VNBT",
    "partIds": ["abc", "D50MRLL"]
  }'
```

**Response:**

```json
{
  "responseList": [
    {
      "partId": "abc",
      "entitled": "No"
    },
    {
      "partId": "D50MRLL",
      "entitled": "Yes"
    }
  ],
  "isEntitled": true,
  "errorMessage": null
}
```

## MCP Tool Examples

### Using with Watson Orchestrate

1. **Configure MCP server in Watson Orchestrate:**

Add the following to your MCP configuration:

```json
{
  "mcpServers": {
    "csp-entitlement": {
      "command": "python",
      "args": ["-m", "mock_csp.mcp.server"],
      "cwd": "/path/to/mcp-csp"
    }
  }
}
```

2. **Invoke tools from Watson Orchestrate:**

```
Check user entitlement for uid 123450 with SLC test123
```

Watson Orchestrate will automatically call the `check_user_entitlement` tool.

### Direct MCP Tool Invocation

Example tool call structure:

```json
{
  "name": "check_user_entitlement",
  "arguments": {
    "uid": "123450",
    "supportLevelCodes": ["test123"],
    "version": "12.0"
  }
}
```

## Test Credentials

For local testing, use these API keys:

| Adopter | API Key | Access Level |
|---------|---------|--------------|
| Fix Central | `fc_test_key_12345` | All SLCs |
| Drupal | `drupal_test_key_67890` | Eligible SLCs only |
| Knowledge Center | `kc_test_key_abcde` | Eligible SLCs only |

## Seeded Test Data

The service includes pre-seeded data for testing:

### Users

- `123450` - User with active entitlements
- `100000VNBT` - User with part-based entitlements
- `USER_NO_ACCOUNTS` - User with no account links
- `USER_EXPIRED` - User with expired entitlements

### Support Level Codes (SLCs)

- `test123` - Valid SLC with active entitlements
- `SML0D00` - Storage product SLC
- `ELIGIBLE_SLC` - SLC eligible for Drupal/KC
- `NOT_ELIGIBLE_SLC` - SLC not eligible for Drupal/KC
- `abc` - Invalid SLC (not in system)

### Machines

- Machine Type: `7145`, Serial: `0689018`, Country: `ZA` - Valid asset
- Machine Type: `2828`, Serial: `0060F4B`, Country: `US` - Valid asset

### Part IDs

- `D50MRLL` - Active part entitlement
- `EXPIRED_PART` - Expired part entitlement

## Configuration

Environment variables (see `.env.example`):

```bash
# Server Configuration
HOST=0.0.0.0
PORT=8000
LOG_LEVEL=INFO

# Database
DATABASE_URL=sqlite:///./csp_entitlement.db

# API Configuration
API_PREFIX=/services/apexrest

# Authentication
FIXCENTRAL_API_KEY=fc_test_key_12345
DRUPAL_API_KEY=drupal_test_key_67890
KC_API_KEY=kc_test_key_abcde

# MCP Server Configuration
MCP_SERVER_NAME=csp-entitlement-mcp
MCP_SERVER_VERSION=1.0.0
```

## Docker Support

Build the Docker image:

```bash
docker build -t mock-csp-entitlement .
```

Run the REST API server:

```bash
docker run -p 8000:8000 mock-csp-entitlement
```

## Project Structure

```
mcp-csp/
├── src/
│   └── mock_csp/
│       ├── __init__.py
│       ├── main.py              # FastAPI application
│       ├── config.py            # Configuration management
│       ├── logging_config.py    # Logging setup
│       ├── api/
│       │   └── routes/          # REST API endpoints
│       ├── mcp/
│       │   ├── server.py        # MCP server
│       │   └── tools.py         # MCP tool implementations
│       ├── services/
│       │   └── entitlement_service.py  # Core business logic
│       ├── models/
│       │   ├── api_models.py    # Pydantic request/response models
│       │   └── domain_models.py # Domain entities
│       ├── middleware/
│       │   └── auth.py          # Authentication middleware
│       └── db/
│           ├── database.py      # In-memory database
│           └── seed.py          # Seed data
├── tests/                       # Test suite
├── pyproject.toml              # Project dependencies
├── Dockerfile                  # Docker configuration
├── .env.example               # Environment template
└── README.md                  # This file
```

## Implementation Notes and Assumptions

### Spec Ambiguities Resolved

1. **Version Parameter with Multiple SLCs:**
   - The spec states version limits to one SLC/version combination
   - Example shows version with multiple SLCs
   - **Implementation:** Accepts version with multiple SLCs; applies version check to all

2. **Empty SLC Array:**
   - Spec says "SLC must be provided" but also shows empty array example
   - **Implementation:** Strict validation requiring at least one SLC

3. **Error Message Spelling:**
   - Preserved original spellings from spec examples:
     - "Atleast one partId is required" (not "At least")
     - "Contact not found for this uid"
     - "machineType, serialNumber and countryCode are required"

4. **Response Value Capitalization:**
   - Preserved exact capitalization from spec:
     - "Yes", "No", "Invalid", "Not eligible", "Expired"

5. **Drupal/KC Eligibility:**
   - Implemented as configurable SLC whitelist
   - Non-eligible SLCs return "Not eligible" without checking entitlements

### Design Decisions

1. **In-Memory Database:**
   - Used for simplicity and easy local testing
   - Database layer is abstracted for future replacement with SQLite/PostgreSQL

2. **Shared Service Layer:**
   - Both REST API and MCP tools use the same service methods
   - Ensures consistent behavior across interfaces

3. **Authentication:**
   - Simple API key-based authentication
   - Suitable for mock/testing purposes
   - Can be extended for production use

4. **MCP Tool Default Client:**
   - MCP tools use Fix Central credentials by default
   - Provides broadest access for AI assistant use cases

## Troubleshooting

### Port Already in Use

If port 8000 is already in use:

```bash
# Change port in .env
PORT=8001

# Or specify when running
uvicorn mock_csp.main:app --port 8001
```

### Import Errors

Ensure the package is installed in development mode:

```bash
pip install -e .
```

### MCP Server Not Connecting

1. Check that the MCP server is running
2. Verify the command path in Watson Orchestrate configuration
3. Check logs for error messages

## Development

### Adding New Test Data

Edit `src/mock_csp/db/seed.py` to add new users, accounts, entitlements, etc.

### Adding New Endpoints

1. Create route file in `src/mock_csp/api/routes/`
2. Add business logic to `src/mock_csp/services/entitlement_service.py`
3. Include router in `src/mock_csp/main.py`
4. Add tests in `tests/`

### Code Quality

Format code:

```bash
black src/ tests/
```

Lint code:

```bash
ruff check src/ tests/
```

Type check:

```bash
mypy src/
```

## Documentation

- **[MCP_INSPECTOR_GUIDE.md](MCP_INSPECTOR_GUIDE.md)** - How to test and debug with MCP Inspector
- **[USER_ENTITLEMENT_WORKFLOW.md](USER_ENTITLEMENT_WORKFLOW.md)** - Complete guide for checking all products a user is entitled to on login
- **[COMPREHENSIVE_MOCK_DATA.md](COMPREHENSIVE_MOCK_DATA.md)** - Guide to using comprehensive mock data with realistic test scenarios
- **[MOCK_DATA_EXAMPLES.md](MOCK_DATA_EXAMPLES.md)** - API examples and test scenarios
- **[WATSON_ORCHESTRATE.md](WATSON_ORCHESTRATE.md)** - Watson Orchestrate integration guide
- **[IMPLEMENTATION_NOTES.md](IMPLEMENTATION_NOTES.md)** - Technical implementation details and assumptions
- **[NPM_PUBLISHING.md](NPM_PUBLISHING.md)** - Guide for publishing to npm registry


## License

This is a mock implementation for testing and development purposes.

## Support

For issues or questions, please refer to the project documentation or create an issue in the repository.