# MCP Vessel Accounts Server

A Model Context Protocol (MCP) server for comprehensive vessel account management, integrating data from multiple maritime systems:
- **EyeShare**: Invoice and vessel data
- **ShipNet**: Vessel expenses and budget data
- **ShipPalm V2/V3**: Purchase order management

## Features

- **EyeShare API Integration**: Access vessel data, invoices, and attachments
- **ShipNet Integration**: MongoDB-powered vessel expenses with category lookup
- **ShipPalm Integration**: Purchase order data from V2 and V3 systems
- **MongoDB Integration**: Direct database queries with aggregation pipelines
- **Comprehensive Logging**: Structured logging with Winston
- **Environment Configuration**: Flexible configuration via environment variables

## Installation Instructions

### Prerequisites

✅ **Node.js is already available** on your local environment
- MongoDB connection (for ShipNet vessel expenses and ShipPalm purchase orders)
- EyeShare API credentials

### Step-by-Step Setup Guide for Team Members

1. **Clone the Repository**
   ```bash
   git clone https://github.com/syia-ai/mcp-vessel-accounts.git
   cd mcp-vessel-accounts
   ```

2. **Install Dependencies**
   ```bash
   npm install
   ```

3. **Configure Environment**
   ```bash
   # Copy the example environment file
   cp .env.example .env
   
   # Open the .env file in your editor and update:
   # - EYESHARE_BASE_URL with the correct API endpoint
   # - EYESHARE_CLIENT_ID and EYESHARE_CLIENT_SECRET with your credentials
   # - MONGODB_URI with your database connection string
   ```

4. **Build the Project**
   ```bash
   npm run build
   ```

5. **Run the Server**
   ```bash
   # For development with auto-reload
   npm run dev
   
   # For production
   npm start
   ```

6. **Verify Installation**
   ```bash
   # Test token generation to verify EyeShare API connection
   node get-token.js
   ```

### Alternative: Installation via npm

If you prefer to install as a package:

```bash
# Install locally in your project
npm install mcp-vessel-accounts

# Or install globally on your system
npm install -g mcp-vessel-accounts
```

### From Source (For Contributors)

```bash
# Clone and install
git clone https://github.com/syia-ai/mcp-vessel-accounts.git
cd mcp-vessel-accounts
npm install

# Build the project
npm run build

# Install globally (optional)
npm run install-global
```

### Environment Setup

Create a `.env` file with your configuration (or copy from .env.example):

```env
# EyeShare API Configuration
EYESHARE_BASE_URL=https://api.eyeshare.com
EYESHARE_CLIENT_ID=your_client_id
EYESHARE_CLIENT_SECRET=your_client_secret
EYESHARE_COMPANY_CODE=your_company_code
EYESHARE_MODULE=your_module

# MongoDB Configuration (ShipNet & ShipPalm)
MONGODB_URI=mongodb://username:password@host:port/database
MONGODB_DATABASE=your_database_name

# Logging
LOG_LEVEL=info
NODE_ENV=production
```

## Usage Instructions

### Running the Server

```bash
# Development mode (with auto-reload)
npm run dev

# Production mode
npm start

# With custom configuration file
mcp-vessel-accounts --env-file ./custom.env

# With debug logging enabled
mcp-vessel-accounts --debug
```

### Using as an MCP Tool in Siya

This package is designed to work with Siya's Model Context Protocol. After installation:

1. **Configure in Siya**
   - Add the server to your Siya configuration
   - Set the necessary environment variables

2. **Access MCP Tools**
   - Use the vessel_expenses tool to get financial data
   - Use the search_invoices tool to find invoice information
   - Use the get_vessels tool to retrieve vessel information

3. **Example MCP Usage**
   ```javascript
   // Example of using the vessel_expenses tool
   const result = await mcp.callTool("vessel_expenses", {
     vesselCode: "TANK",
     limit: 1000
   }, "mcp-vessel-accounts");
   ```

## Available Tools

### 1. get_vessels (EyeShare)

Get all vessels from EyeShare API. Returns a list of vessels with their codes and names extracted from the company hierarchy.

**Data Source:** EyeShare API
**Parameters:** None

**Example:**
```json
{
  "name": "get_vessels",
  "arguments": {}
}
```

**Response Format:**
```json
[
  {
    "code": "TANK",
    "name": "Synergy Denmark A/S",
    "id": "59d7fd16-3ead-4c82-9c40-31fbdf30fae8",
    "organizationNumber": "0",
    "companyType": "Standard",
    "parent": "Denmark",
    "implemented": true,
    "customerRootCompany": false
  }
]
```

### 2. search_invoices (EyeShare)

Search for invoices with various filters from EyeShare system.

**Data Source:** EyeShare API
**Parameters:**
- `vesselCode` (string, optional): Vessel code to filter by (used as CompanyCode in API filter)
- `vesselKey` (string, optional): Alternative vessel key filter
- `invoiceId` (string, optional): Specific invoice ID to get details for
- `fromDate` (string, optional): Start date for invoice search (ISO 8601 format)
- `toDate` (string, optional): End date for invoice search (ISO 8601 format)
- `dateField` (string, optional): Date field to filter on (default: Head.InvoiceDate)
- `minAmount` (number, optional): Minimum invoice amount
- `maxAmount` (number, optional): Maximum invoice amount
- `status` (string, optional): Invoice status filter
- `supplier` (string, optional): Supplier name or code
- `limit` (number, optional): Maximum results (default: 100)
- `skip` (number, optional): Skip results for pagination (default: 0)

**Example:**
```json
{
  "name": "search_invoices",
  "arguments": {
    "vesselCode": "TANK",
    "fromDate": "2024-01-01T00:00:00.000Z",
    "toDate": "2024-12-31T23:59:59.999Z",
    "limit": 50
  }
}
```

### 3. download_attachment (EyeShare)

Download an attachment from an invoice or document in EyeShare.

**Data Source:** EyeShare API
**Parameters:**
- `attachmentId` (string, required): The unique identifier of the attachment
- `documentId` (string, required): The unique identifier of the document
- `version` (number, optional): Version number (default: 0)

**Example:**
```json
{
  "name": "download_attachment",
  "arguments": {
    "attachmentId": "74b0a0d2-8152-4f14-837c-4aad9a678699",
    "documentId": "4899f862-8b25-4b96-9058-c5bdd2d45561",
    "version": 0
  }
}
```

### 4. vessel_expenses (ShipNet)

Get vessel expenses data from ShipNet system with category lookup and vessel code filtering.

**Data Source:** ShipNet (MongoDB)
**Collection:** `budget_expenses_raw_data`
**Parameters:**
- `vesselCode` (string, optional): Vessel code to filter budget expenses
- `limit` (number, optional): Maximum number of documents to return (max 10000)
- `timeout` (number, optional): Query timeout in milliseconds (max 5 minutes)

**Pipeline:**
The tool executes a pipeline that:
1. Filters by vessel code (if provided)
2. Looks up category data from `budget_category_raw_data` collection
3. Unwinds the category data array
4. Adds a `category` field to each document
5. Removes the temporary `category_data` field

**Example:**
```json
{
  "name": "vessel_expenses",
  "arguments": {
    "vesselCode": "BLBU",
    "limit": 1000
  }
}
```

### 5. purchase_orders (ShipPalm V2/V3)

Get purchase order data from ShipPalm V2 and V3 systems with vessel code filtering.

**Data Source:** ShipPalm V2/V3 (MongoDB)
**Collection:** `purchase_order`
**Parameters:**
- `vesselCode` (string, optional): Vessel code to filter purchase orders
- `limit` (number, optional): Maximum number of documents to return (max 10000)
- `timeout` (number, optional): Query timeout in milliseconds (max 5 minutes)

**Example:**
```json
{
  "name": "purchase_orders",
  "arguments": {
    "vesselCode": "BLBU",
    "limit": 500
  }
}
```

**Note:** MongoDB connection is configured via environment variables:
- `MONGODB_URI`: MongoDB connection string
- `MONGODB_DATABASE`: Database name

## Data Sources Overview

| Tool | Data Source | System | Purpose |
|------|-------------|---------|---------|
| `get_vessels` | EyeShare API | EyeShare | Vessel master data |
| `search_invoices` | EyeShare API | EyeShare | Invoice management |
| `download_attachment` | EyeShare API | EyeShare | Document attachments |
| `vessel_expenses` | MongoDB | ShipNet | Budget and expense tracking |
| `purchase_orders` | MongoDB | ShipPalm V2/V3 | Purchase order management |

## API Integration

The server integrates with multiple maritime systems:

### EyeShare API Endpoints:
- **Authentication**: `/auth/connect/token`
- **Vessels**: `/api/system/config/allclientcompany`
- **Invoice Search**: `/api/search`
- **Attachments**: `/api/attachments/{attachmentId}/{documentId}/{version}`

### MongoDB Collections (ShipNet & ShipPalm):
- **ShipNet**: `budget_expenses_raw_data`, `budget_category_raw_data`
- **ShipPalm**: `purchase_order`

## MongoDB Security

The MongoDB query tools include several security measures:

1. **Connection Pooling**: Efficient connection management with configurable pool sizes
2. **Timeout Protection**: Queries have a maximum timeout of 5 minutes
3. **Connection Management**: Automatic connection cleanup after each query
4. **Error Handling**: Comprehensive error handling and logging
5. **Resource Limits**: Configurable limits on document counts and execution time

**Supported Operations:**
- **ShipNet Integration**: Vessel expenses data with category lookup and vessel filtering
- **ShipPalm Integration**: Purchase order data from V2 and V3 systems with vessel filtering

## Error Handling

The server includes comprehensive error handling and logging:

- API authentication errors
- Network connectivity issues
- Invalid parameter validation
- Rate limiting and timeout handling
- MongoDB connection and query errors

## Development

### Project Structure

```
mcp-vessel-accounts/
├── src/
│   ├── index.ts              # Main server entry point
│   ├── types/
│   │   └── index.ts          # TypeScript interfaces
│   ├── utils/
│   │   ├── config.ts         # Configuration management
│   │   ├── logger.ts         # Logging configuration
│   │   ├── api.ts            # EyeShare API client
│   │   └── mongodb.ts        # MongoDB utilities (ShipNet & ShipPalm)
│   └── tools/
│       ├── index.ts          # Tool handler
│       ├── schema.ts         # Tool definitions
│       └── mongodb.ts        # MongoDB tools
├── bin/
│   └── cli.js               # CLI entry point
├── dist/                    # Compiled JavaScript
├── package.json
├── tsconfig.json
└── README.md
```

### Building

```bash
# Development build
npm run build

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

### Testing

```bash
# Test token generation
node get-token.js
```

## License

MIT License - see LICENSE file for details.

## Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests if applicable
5. Submit a pull request

## Troubleshooting Guide

### Common Issues and Solutions

#### Connection Issues
- **EyeShare API Connection Fails**
  - Verify your CLIENT_ID and CLIENT_SECRET are correct
  - Check if the API endpoint URL is accessible from your network
  - Run `node get-token.js` to test authentication directly

- **MongoDB Connection Issues**
  - Ensure your MongoDB connection string is correct
  - Check if MongoDB server is running and accessible
  - Verify database name and collection permissions

#### Data Retrieval Problems
- **No Vessel Data**
  - Verify the vessel code exists in the system
  - Check EyeShare company hierarchy configuration
  - Ensure your user has permissions to access vessel data

- **Missing Expense Data**
  - Confirm the MongoDB collections contain data for the requested vessel
  - Check date ranges in your queries
  - Verify account codes and category mappings

### Getting Support

If you encounter issues:
1. Check the documentation in this README
2. Review error logs (set LOG_LEVEL=debug for more details)
3. Ensure all environment variables are correctly configured
4. Verify MongoDB connection and EyeShare API credentials
5. Contact the Data Engineering team for assistance 