# Chilean Law Defense MCP Server

> **Empowering Chilean workers against legal harassment through AI-powered legal defense**

[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
[![TypeScript](https://img.shields.io/badge/TypeScript-5.3-blue)](https://www.typescriptlang.org/)
[![Model Context Protocol](https://img.shields.io/badge/MCP-1.0-green)](https://modelcontextprotocol.io/)

A Model Context Protocol (MCP) server that provides Chilean labor law expertise through Retrieval-Augmented Generation (RAG). Designed to help workers defend their rights against workplace harassment and illegal termination.

## Features

- **Legal Article Search**: RAG-powered search across 500+ articles from Chilean labor law
- **Case Analysis**: AI-driven analysis of employment termination cases
- **Defense Document Generation**: Automated creation of legal complaints and defense documents
- **Precedent Search**: Find relevant court cases to support your case
- **Ley Karin Analysis**: Specialized harassment detection and analysis

## What Makes This Unique

Unlike generic legal AI tools with 17-33% hallucination rates, this MCP:
- ✅ Focuses exclusively on Chilean labor law
- ✅ Grounds every response in actual legal articles
- ✅ Includes real case precedents
- ✅ Provides actionable defense strategies
- ✅ Free and accessible to all workers

## Installation

### Via NPM (Recommended)

```bash
npm install -g chilean-law-defense-mcp
```

### From Source

```bash
git clone https://github.com/JavierCollipal/chilean-law-defense-mcp.git
cd chilean-law-defense-mcp
npm install
npm run build
```

## Configuration

### Prerequisites

1. **MongoDB Atlas Account** (free tier works!)
   - Create account at https://www.mongodb.com/cloud/atlas
   - Create a cluster named `chilean-law-rag`
   - Get your connection URI

2. **OpenAI API Key**
   - Get from https://platform.openai.com/api-keys
   - Used for generating embeddings

### Environment Setup

1. Copy the example environment file:

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

2. Edit `.env` with your credentials:

```env
MONGODB_URI=mongodb+srv://YOUR_USERNAME:YOUR_PASSWORD@YOUR_CLUSTER.mongodb.net/chilean-law-rag
OPENAI_API_KEY=sk-YOUR_OPENAI_API_KEY_HERE
```

### Claude Desktop Integration

⚠️ **IMPORTANT**: MCP servers only work with **Claude Desktop**, not claude.ai web version.

Download Claude Desktop: https://claude.ai/download

Add to your Claude Desktop MCP configuration:

**Location**: `~/.config/Claude/claude_desktop_config.json` (Linux/Mac) or `%APPDATA%\Claude\claude_desktop_config.json` (Windows)

```json
{
  "mcpServers": {
    "chilean-law-defense": {
      "command": "npx",
      "args": ["-y", "chilean-law-defense-mcp"],
      "env": {
        "MONGODB_URI": "mongodb+srv://YOUR_USERNAME:YOUR_PASSWORD@YOUR_CLUSTER.mongodb.net/chilean-law-rag",
        "OPENAI_API_KEY": "sk-YOUR_OPENAI_API_KEY_HERE"
      }
    }
  }
}
```

Restart Claude Desktop after saving the configuration.

## Usage Examples

Once installed in Claude Desktop, you can ask questions like:

### Example 1: Finiquito Rejection
```
"My employer sent me a finiquito under Article 160 but hasn't provided
any proof of misconduct. Can I reject it?"
```

**MCP Response**: Analyzes Article 160 requirements, confirms proof is mandatory, identifies employment as still active, generates defense document.

### Example 2: Ley Karin Harassment
```
"My supervisor has been threatening me with termination for two weeks.
Is this harassment under Ley Karin?"
```

**MCP Response**: Analyzes incidents against Ley Karin criteria, identifies termination threats as harassment, provides filing instructions.

### Example 3: Article 22 Remote Work
```
"I'm on an Article 22 contract and my employer wants to terminate me
without following remote work protections. What are my rights?"
```

**MCP Response**: Retrieves Article 22 protections, analyzes employer obligations, generates defense strategy.

## Available MCP Tools

### 1. `query_labor_law`
Search Chilean labor law articles using natural language.

**Parameters:**
- `query` (string): Legal question in Spanish
- `articles?` (string[]): Specific article numbers (optional)
- `law_code?` (enum): codigo_trabajo | constitucion | ley_karin
- `category?` (string): Legal category (optional)

### 2. `analyze_case`
Analyze a complete employment case with AI.

**Parameters:**
- `contract_type` (enum): indefinido | plazo_fijo | articulo_22 | honorarios
- `termination_cause?` (string): Claimed termination reason
- `finiquito_status` (enum): accepted | rejected | not_received
- `evidence` (string[]): Available evidence
- `timeline` (Event[]): Case timeline

### 3. `generate_defense`
Generate legal defense documents.

**Parameters:**
- `type` (enum): denuncia | reclamo_administrativo | ley_karin
- `case_analysis` (object): Result from analyze_case
- `user_info?` (object): User details for document

### 4. `find_precedents`
Search for relevant court precedents.

**Parameters:**
- `situation` (string): Case description
- `court?` (string): Specific court (optional)
- `year_from?` (number): Minimum year (optional)

### 5. `analyze_harassment`
Analyze workplace harassment under Ley Karin.

**Parameters:**
- `incidents` (Incident[]): Harassment incidents
- `perpetrator_role` (string): Position of harasser
- `witnesses?` (string[]): Available witnesses

## Architecture

```
User Query (Spanish)
    ↓
Claude Code (MCP Client)
    ↓
Chilean Law Defense MCP Server
    ↓
├─ Embedding Generation (OpenAI 1536-dim)
├─ Vector Search (MongoDB Atlas)
├─ Context Building (RAG)
└─ Tool Execution (5 specialized functions)
    ↓
Legal Analysis + Documents + Precedents
    ↓
Worker Empowered
```

## Technology Stack

- **MCP SDK**: @modelcontextprotocol/sdk
- **Database**: MongoDB Atlas (vector search)
- **Embeddings**: OpenAI text-embedding-3-small
- **Language**: TypeScript
- **Testing**: Jest with MongoDB Memory Server

## Data Sources

- **Código del Trabajo**: 506 articles with embeddings
- **Constitución Política**: Labor rights articles
- **Ley Karin**: Complete anti-harassment law
- **Case Precedents**: 100+ court decisions

## Development

### Setup Development Environment

```bash
# Install dependencies
npm install

# Copy environment template
cp .env.example .env

# Run tests
npm test

# Run with coverage
npm run test:coverage

# Build
npm run build

# Watch mode (development)
npm run dev
```

### Project Structure

```
chilean-law-defense-mcp/
├── src/
│   ├── index.ts              # MCP server entry
│   ├── tools/                # 5 MCP tools
│   ├── resources/            # Legal code resources
│   ├── rag/                  # RAG engine
│   ├── types/                # TypeScript types
│   └── utils/                # Utilities
├── tests/
│   ├── unit/                 # Unit tests
│   └── integration/          # Integration tests
├── scripts/                  # Data ingestion scripts
└── docs/                     # Documentation
```

### Running Tests

```bash
# All tests
npm test

# Watch mode
npm run test:watch

# Coverage report
npm run test:coverage
```

### Code Quality

```bash
# Lint
npm run lint

# Fix linting issues
npm run lint:fix
```

## Contributing

We welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.

### Development Roadmap

- [x] Phase 1: Foundation (Project setup, types, validators)
- [x] Phase 2: RAG Engine (Embeddings, vector search, context building)
- [x] Phase 3: MCP Server (5 specialized legal defense tools)
- [ ] Phase 4: Data Ingestion (Legal articles + precedents database)
- [x] Phase 5: Testing (206 tests passing!)
- [ ] Phase 6: NPM Publishing & Promotion

**Current Status**: 80% Complete - Ready for NPM publishing!

## Legal Disclaimer

This tool provides legal information, not legal advice. While it uses official Chilean legal codes, users should:

- Verify information with qualified legal professionals
- Understand their specific case circumstances
- Seek professional legal counsel for serious matters
- Use generated documents as templates requiring review

The developers are not responsible for legal outcomes from using this tool.

## Privacy & Security

- ✅ All credentials stored in `.env` files (never hardcoded)
- ✅ MongoDB Atlas connections only (no localhost)
- ✅ User queries not logged or shared
- ✅ Private repository, public NPM package
- ✅ No tracking or analytics

## License

MIT License - see [LICENSE](LICENSE) file for details.

## Support

- **Issues**: [GitHub Issues](https://github.com/JavierCollipal/chilean-law-defense-mcp/issues)
- **Discussions**: [GitHub Discussions](https://github.com/JavierCollipal/chilean-law-defense-mcp/discussions)

## Acknowledgments

Built with the Model Context Protocol by Anthropic. Designed to empower Chilean workers with legal knowledge and defense capabilities.

---

**Made with ⚖️ for Chilean workers everywhere**

*"Justice delayed is justice denied. But justice with AI? Justice is instant."*
