# sinhala-mcp 🇱🇰

**Production-ready MCP server** that translates Sinhala/Singlish instructions into English technical prompts using Google Gemini AI.

[![Python Version](https://img.shields.io/badge/python-3.10%2B-blue)](https://www.python.org/downloads/)
[![License](https://img.shields.io/badge/license-MIT-green)](LICENSE)
[![MCP](https://img.shields.io/badge/MCP-Compatible-orange)](https://modelcontextprotocol.io/)

## ✨ Features

- 🌍 **Sinhala/Singlish Translation**: Convert colloquial commands into structured English technical specifications
- 🧠 **Context-Aware**: Automatically infers technical context (e.g., "Login" → "Authentication flow")
- 🔒 **Environment Variable Auth**: Secure API key management via environment variables
- 🚀 **Production-Ready**:
  - Comprehensive error handling and logging
  - Retry logic for API failures
  - Timeout protection (30s default)
  - Input validation and sanitization
  - Health check endpoint for monitoring
  - Rate limit handling
- 📦 **MCP Compliant**: Works with Claude Desktop, VS Code MCP client, and other MCP-compatible tools
- 🎯 **Latest AI**: Uses Google GenAI SDK with Gemini 2.0 Flash (GA as of May 2025)

## 📦 Installation

### Using uvx (Recommended - No installation required)

```bash
# Just run it directly!
uvx sinhala-mcp
```

### Using pip

```bash
pip install sinhala-mcp
```

### Using uv

```bash
uv pip install sinhala-mcp
```

## 🔑 Configuration

### Step 1: Get a Google Gemini API Key

1. Visit [Google AI Studio](https://makersuite.google.com/app/apikey)
2. Create a new API key
3. Keep it secure - never commit it to version control

### Step 2: Configure Your MCP Client

**IMPORTANT**: The server reads the API key from the `GEMINI_API_KEY` environment variable. Do not use the old `set_gemini_key` tool - it has been removed for security and store compatibility.

#### Claude Desktop Configuration

**macOS:** `~/Library/Application Support/Claude/claude_desktop_config.json`
**Windows:** `%APPDATA%\Claude\claude_desktop_config.json`

```json
{
  "mcpServers": {
    "sinhala-mcp": {
      "command": "uvx",
      "args": ["sinhala-mcp"],
      "env": {
        "GEMINI_API_KEY": "your-api-key-here"
      }
    }
  }
}
```

#### VS Code MCP Extension

```json
{
  "mcp.servers": {
    "sinhala-mcp": {
      "command": "uvx",
      "args": ["sinhala-mcp"],
      "env": {
        "GEMINI_API_KEY": "your-api-key-here"
      }
    }
  }
}
```

#### Command Line / Development

```bash
# Linux/macOS
export GEMINI_API_KEY="your-api-key-here"

# Windows CMD
set GEMINI_API_KEY=your-api-key-here

# Windows PowerShell
$env:GEMINI_API_KEY="your-api-key-here"
```

## 🛠️ Available Tools

### 1. `translate_sinhala_instruction`

Translates Sinhala or Singlish instructions into precise English technical prompts.

**Parameters:**
- `instruction` (string, required): The Sinhala or Singlish instruction to translate (max 5000 characters)

**Example:**
```
Translate "mama login ekak hadanna one" using translate_sinhala_instruction
```

**Output:**
```
Original (Sinhala/Singlish):
mama login ekak hadanna one

Translated (English Technical Prompt):
Implement a user authentication system with login functionality including:
- Username/email and password input fields
- Form validation for credentials
- Authentication endpoint integration
- Session management after successful login
- Error handling for failed authentication attempts
```

### 2. `health_check`

Check if the MCP server and Gemini API connection are working properly.

**Parameters:** None

**Example:**
```
Run health_check
```

**Output:**
```
Health Check: PASSED
Server: sinhala-mcp v0.1.0
API Connection: Active
Timestamp: 2025-01-26T12:00:00.000000
```

## 💡 Usage Examples

### Example 1: Web Development

**Input (Sinhala):**
```
"Mama dashboard ekak denna user stats tikkai"
```

**Translated Output:**
```
Create a user analytics dashboard with:
- Real-time user statistics display
- Data visualization charts
- Filtering and search capabilities
- Responsive layout for mobile/desktop
- Authentication-protected access
```

### Example 2: Backend Development

**Input (Sinhala):**
```
"Database eka connect karanna API endpoint ekak hadala ganna"
```

**Translated Output:**
```
Implement database integration with REST API:
- Set up database connection pool
- Create CRUD endpoints for data access
- Implement proper error handling
- Add data validation and sanitization
- Include authentication/authorization middleware
```

### Example 3: Frontend Features

**Input (Sinhala):**
```
"Profile page eka photo upload eka danne"
```

**Translated Output:**
```
Implement profile photo upload feature:
- File upload input with image type validation
- Client-side image preview
- Size and format restrictions
- Upload progress indicator
- Server-side file storage integration
- Error handling for upload failures
```

## 🏗️ Development

### Setup Development Environment

```bash
# Clone the repository
git clone https://github.com/Thamindu-Dev/sinhala-mcp.git
cd sinhala-mcp

# Install dependencies
pip install -e .

# Or using uv
uv pip install -e .
```

### Running Tests

```bash
# Test server import
python test_simple.py

# Run with verbose logging
LOGLEVEL=DEBUG python -m sinhala_mcp.server
```

### Project Structure

```
sinhala-mcp/
├── src/
│   └── sinhala_mcp/
│       ├── __init__.py
│       └── server.py          # Main MCP server implementation
├── pyproject.toml              # Package configuration
├── smithery.yaml              # Store publishing configuration
├── README.md                  # This file
└── LICENSE                    # MIT License
```

## 🔒 Security

- ✅ API keys stored in environment variables only
- ✅ No local file storage of credentials
- ✅ Input validation and sanitization
- ✅ Protection against injection attacks
- ✅ Rate limit handling
- ✅ Open source - fully auditable

## 📊 Technical Specifications

- **Build Backend**: hatchling
- **Package Layout**: Modern `src/` layout
- **Python Version**: 3.10+ (tested on 3.10-3.13)
- **Dependencies**:
  - `mcp>=0.9.0` - Model Context Protocol SDK
  - `google-genai>=1.0.0` - Official Google GenAI SDK (GA)
- **AI Model**: Gemini 2.0 Flash Experimental
- **Max Instruction Length**: 5000 characters
- **API Timeout**: 30 seconds
- **Retry Logic**: 2 retries with exponential backoff

## 🚀 Production Deployment

The server is production-ready with:

- **Structured Logging**: Timestamped logs for debugging
- **Error Handling**: Graceful failure with user-friendly messages
- **Health Checks**: Monitor API connectivity
- **Timeout Protection**: Prevents hanging requests
- **Retry Logic**: Handles transient API failures
- **Input Validation**: Prevents abuse and injection attacks

## 📚 Architecture

```
┌─────────────────┐      ┌──────────────────┐      ┌─────────────────┐
│ User (Sinhala)  │─────>│  MCP Server      │─────>│ Google Gemini   │
│ "mama login eka │      │  (translate_     │      │ AI API          │
│  karanna one"   │      │   sinhala_       │      │                 │
└─────────────────┘      └──────────────────┘      └─────────────────┘
                                  │
                                  ▼
                         ┌──────────────────┐
                         │ English Output   │
                         │ "Implement user  │
                         │  authentication │
                         │  with login form"│
                         └──────────────────┘
```

## 🤝 Contributing

Contributions are welcome! Please feel free to:

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Submit a Pull Request

## 📝 License

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

## 🔧 Troubleshooting

### Common Issues

1.  **"GEMINI_API_KEY not found" Error**
    - Ensure you have added the key to your configuration file (Claude Desktop or VS Code).
    - If using the terminal, ensure you ran `export GEMINI_API_KEY=...` (Mac/Linux) or `$env:GEMINI_API_KEY=...` (Windows).
    - Restart your MCP client after changing the configuration.

2.  **Connection Refused / Server Error**
    - Check if you have the latest version installed: `uv tool upgrade sinhala-mcp`
    - Verify your internet connection (Google Gemini API requires internet access).

3.  **Translation is empty or incorrect**
    - The model might have blocked the content due to safety settings. Try rephrasing the instruction.

## 🆘 Support

- **Report Issues**: [GitHub Issues](https://github.com/Thamindu-Dev/sinhala-mcp/issues)
- **Documentation**: This README
- **MCP Protocol**: [modelcontextprotocol.io](https://modelcontextprotocol.io/)

## 🙏 Acknowledgments

Built with:
- [Model Context Protocol](https://modelcontextprotocol.io/) - Standard for AI context
- [Google GenAI SDK](https://github.com/googleapis/python-genai) - Official Python SDK
- [MCP Python SDK](https://github.com/jlowin/mcp-python) - MCP implementation

## 📈 Roadmap

- [ ] Add more language pairs (Tamil, etc.)
- [ ] Support for streaming responses
- [ ] Custom system prompt configuration
- [ ] Translation history/caching
- [ ] Web UI for testing

## 👨‍💻 About the Developer

**sinhala-mcp** was created by **Thamindu Hatharasinha**.

- 🌐 **Portfolio**: [www.thamidu.me](https://www.thamidu.me)
- 🐙 **GitHub**: [Thamindu-Dev](https://github.com/Thamindu-Dev)

---

**Made with ❤️ for Sinhala-speaking developers worldwide**

For more information about MCP, visit [modelcontextprotocol.io](https://modelcontextprotocol.io/).
