# IMO Publications MCP Server

A comprehensive Model Context Protocol (MCP) server for accessing and searching International Maritime Organization (IMO) publications, regulations, and maritime documentation.

## 🌊 Overview

This MCP server provides powerful tools for maritime professionals to search, access, and manage IMO publications including:
- **SOLAS** (Safety of Life at Sea)
- **MARPOL** (Marine Pollution Prevention)
- **STCW** (Standards of Training, Certification and Watchkeeping)
- **GMDSS** (Global Maritime Distress and Safety System)
- **ISM Code** (International Safety Management)
- **ISPS Code** (International Ship and Port Facility Security)
- And comprehensive collection of IMO conventions, codes, and circulars

## ✨ Features

### 🛠️ Available Tools

| Tool | Description |
|------|-------------|
| `list_imo_publications` | Complete catalog of all available IMO publications |
| `fetch_imo_publication_by_vector_search` | Advanced content-based search across all publications |
| `get_by_imo_publication_name` | Quick lookup by publication name or reference |
| `smart_imo_publication_search` | Universal search with intelligent filtering and semantic understanding |
| `parse_document_content` | Extract and parse content from document URLs |
| `google_search` | Enhanced web search for maritime information |
| `get_table_schema` | Database schema information for integration |

### 🏗️ Architecture

**Consolidated Design** - Single comprehensive server with modular utilities:
- **Main Server**: `src/index.ts` (919 lines) - All MCP functionality in one file
- **Utils**: Modular utilities for API, MongoDB, and Typesense operations
- **CLI**: Comprehensive command-line interface with configuration management
- **Type Safety**: Full TypeScript implementation with strict typing

## 🚀 Quick Start

### NPX Usage (Recommended)
```bash
# Test the server
npx imo-publications-mcp-server --help

# Run with configuration
MONGODB_URI=mongodb://localhost:27017 \
TYPESENSE_HOST=localhost \
TYPESENSE_PORT=8108 \
TYPESENSE_PROTOCOL=http \
TYPESENSE_API_KEY=your-key \
npx imo-publications-mcp-server
```

### Local Installation
```bash
# Clone and install
git clone <repository-url>
cd imo-publications-mcp-server
npm install

# Build the project
npm run build

# Run with help
node dist/index.js --help
```

## ⚙️ Configuration

The server supports both **environment variables** (recommended) and **command-line arguments**.

### Environment Variables (Priority)
```bash
export MONGODB_URI="mongodb://localhost:27017"
export MONGODB_DB_NAME="imo_publications"
export TYPESENSE_HOST="localhost"
export TYPESENSE_PORT="8108"
export TYPESENSE_PROTOCOL="http"
export TYPESENSE_API_KEY="your-typesense-key"

# Optional API Keys
export COHERE_API_KEY="your-cohere-key"
export OPENAI_API_KEY="your-openai-key"
export PERPLEXITY_API_KEY="your-perplexity-key"
```

### Command Line Arguments
```bash
node dist/index.js \
  --mongo-uri mongodb://localhost:27017 \
  --db-name imo_publications \
  --typesense-host localhost \
  --typesense-port 8108 \
  --typesense-protocol http \
  --typesense-api-key your-key
```

### CLI Help
```bash
node dist/index.js --help
```

## 🔧 Development

### Prerequisites
- **Node.js** >= 18.0.0
- **TypeScript** >= 5.7.2
- **MongoDB** instance
- **Typesense** search engine
- API keys for enhanced functionality

### Development Setup
```bash
# Install dependencies
npm install

# Development mode with hot reload
npm run dev

# Build for production
npm run build

# Run tests
npm test

# Test with MCP Inspector
npm test  # Opens on http://localhost:6274
```

### Testing
```bash
# Test imports and basic functionality
npx tsx test.ts

# Test with MCP Inspector (interactive)
npm test

# Test specific functionality
echo '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}' | \
  MONGODB_URI=mongodb://localhost:27017 \
  TYPESENSE_HOST=localhost \
  TYPESENSE_PORT=8108 \
  TYPESENSE_PROTOCOL=http \
  TYPESENSE_API_KEY=test-key \
  node dist/index.js
```

## 📋 Usage Examples

### Basic Tool Usage
```json
// List all available tools
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/list",
  "params": {}
}

// Search for SOLAS regulations
{
  "jsonrpc": "2.0",
  "id": 2,
  "method": "tools/call",
  "params": {
    "name": "smart_imo_publication_search",
    "arguments": {
      "query": "SOLAS fire safety requirements",
      "max_results": 5
    }
  }
}

```

### MCP Client Integration
```javascript
// Example using MCP SDK
import { Client } from '@modelcontextprotocol/sdk/client/index.js';

const client = new Client({
  name: "imo-client",
  version: "1.0.0"
}, {
  capabilities: {}
});

// Connect to server
await client.connect(transport);

// List available tools
const tools = await client.request({
  method: "tools/list",
  params: {}
});

console.log('Available tools:', tools.result.tools);
```

## 🗄️ Database Requirements

### Typesense Collection Schema
```javascript
{
  "name": "imo_publication",
  "fields": [
    {"name": "documentName", "type": "string", "facet": true},
    {"name": "content", "type": "string"},
    {"name": "documentLink", "type": "string", "optional": true},
    {"name": "chapter", "type": "string", "facet": true, "optional": true},
    {"name": "section", "type": "string", "facet": true, "optional": true},
    {"name": "page", "type": "int32", "facet": true, "optional": true},
    {"name": "originalText", "type": "string", "optional": true},
    {"name": "embedding", "type": "float[]", "optional": true}
  ],
  "default_sorting_field": "documentName"
}
```

### MongoDB Collections
- `imo_publications` - Publication metadata
- `imo_casefiles` - Maritime casefile management
- Additional collections as needed for your use case

## 🔌 API Integration

### Supported Services
- **Typesense** - Primary search engine (required)
- **MongoDB** - Data storage and casefile management (required)
- **Cohere** - Advanced reranking and embeddings (optional)
- **OpenAI** - LLM functionality (optional)
- **Perplexity** - Enhanced web search (optional)

### Error Handling
The server provides comprehensive error handling with clear messages:
- Configuration validation
- Database connection issues
- API rate limiting
- Malformed requests

## 📦 Deployment

### Docker (Recommended)
```dockerfile
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY dist/ ./dist/
COPY bin/ ./bin/
EXPOSE 3000
CMD ["node", "dist/index.js"]
```

### Global Installation
```bash
npm run install-global
imo-publications-mcp-server --help
```

### Environment Configuration
```bash
# Production environment file
cat > .env << EOF
MONGODB_URI=mongodb://prod-mongodb:27017
MONGODB_DB_NAME=imo_publications_prod
TYPESENSE_HOST=prod-typesense
TYPESENSE_PORT=8108
TYPESENSE_PROTOCOL=https
TYPESENSE_API_KEY=prod-api-key
COHERE_API_KEY=prod-cohere-key
EOF
```

## 🧪 Testing & Quality Assurance

### Test Coverage
- ✅ **Build System** - TypeScript compilation
- ✅ **Import Verification** - All dependencies load correctly
- ✅ **MCP Protocol** - Full protocol compliance
- ✅ **Tool Functionality** - All 8 tools tested
- ✅ **Environment Configuration** - Variable precedence and validation
- ✅ **CLI Interface** - Help system and configuration management

### Performance Features
- **Lazy Loading** - Database connections only when needed
- **Caching** - Intelligent result caching for repeated queries
- **Streaming** - Efficient handling of large result sets
- **Error Recovery** - Graceful degradation when services are unavailable

## 🔒 Security

- **Input Validation** - All inputs validated and sanitized
- **API Key Management** - Secure handling of sensitive credentials
- **Database Security** - Connection string validation and secure practices
- **Error Sanitization** - No sensitive information in error responses

## 🤝 Contributing

1. Fork the repository
2. Create a feature branch: `git checkout -b feature/new-tool`
3. Make your changes with proper TypeScript types
4. Add tests for new functionality
5. Update documentation
6. Submit a pull request

### Development Guidelines
- Follow TypeScript best practices
- Maintain backward compatibility
- Add comprehensive error handling
- Include JSDoc documentation
- Test with MCP Inspector

## 📄 License

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

## 🚢 About IMO Publications

The International Maritime Organization (IMO) is the United Nations specialized agency responsible for regulating shipping. This server provides access to:

- **Conventions** - SOLAS, MARPOL, STCW, etc.
- **Codes** - ISM Code, ISPS Code, IMDG Code, etc.
- **Guidelines** - Technical and operational guidance
- **Circulars** - Updates and amendments
- **Resolutions** - Assembly and committee decisions

Perfect for:
- **Maritime Lawyers** - Legal research and compliance
- **Ship Operators** - Operational guidance and regulations
- **Port Authorities** - Inspection and enforcement
- **Maritime Consultants** - Advisory services
- **Training Institutions** - Educational content
- **Surveyors** - Technical standards and procedures

---

**Built with ❤️ for the maritime community** 