UNPKG

crew-management-mcp-server

Version:

Crew management server handling crew records, certifications, scheduling, payroll, and vessel assignments with ERP access for data extraction

948 lines 80.6 kB
export const listToolsRequestSchema = {
    type: "object",
    properties: {
        category: {
            type: "string",
            description: "Optional category to filter tools by",
            enum: ["crew", "certification", "schedule", "payroll", "vessel"]
        },
        search: {
            type: "string",
            description: "Optional search term to filter tools by name or description"
        },
        include_deprecated: {
            type: "boolean",
            description: "Whether to include deprecated tools in the response",
            default: false
        }
    },
    additionalProperties: false
};
export const toolDefinitions = [
    // {
    //     name: "get_vessel_details",
    //     description: "Retrieves vessel details including IMO number, vessel name,class,flag,DOC and the ERP version for a specific vessel.",
    //     inputSchema: {
    //         type: "object",
    //         properties: {
    //             query: {
    //                 type: "string", 
    //                 description: "Pass the vessel name to search for the IMO number"
    //             }
    //         },
    //         required: ["query"],
    //         additionalProperties: false
    //     }
    // },
    {
        name: "get_seafarer_id",
        description: `Get Seafarer IDs(crew code) from user query by querying in typesense crew_details collection. This seafarer id is used to get the seafarer details like name, rank,nationality, contract end date, sign on date, etc. from the snowflake database using the get_seafarer_details tool right after this tool.
                        
                        ## SCHEMA OF THE crew_details TABLE in TYPESENSE.

                        * 'name': 'AGE', 'type': 'string', 'desc': 'Age of the seafarer in years. To be used for querying the seafarers based on age', 'index': true, 'sort': true
                        * 'name': 'CREW_CODE', 'type': 'string', 'desc': 'Primary crew identifier for the seafarer in the crewing system. To be used for querying the seafarers based on crew code', 'index': true, 'sort': false
                        * 'name': 'OLD_CREW_CODE', 'type': 'string', 'desc': 'Legacy crew identifier retained for historical cross-reference. To be used for querying the seafarers based on old crew code', 'index': true, 'sort': false
                        * 'name': 'SEAFARER_NAME', 'type': 'string', 'desc': 'Full name of the seafarer as recorded in official documents. To be used for querying the seafarers based on name', 'index': true, 'sort': false
                        * 'name': 'CURRENT_RANK_NAME', 'type': 'string', 'desc': 'Current rank/position held onboard (e.g., Chief Cook, Master). Note: Captain should be treated as Master while querying the seafarers based on rank', 'index': true, 'sort': false
                        * 'name': 'CURRENT_STATUS', 'type': 'string', 'desc': 'Present Contract status of the seafarer. Typical values: SIGN ON, SIGN OFF, SHORTLISTED'.. To be used for querying the seafarers based on current status and only to be used if asked explicitly for the current status', 'index': true, 'sort': false
                        * 'name': 'PROFILE_STATUS', 'type': 'string', 'desc': 'Present work status with respect to the company like being active or inactive. ENUM values: ["Active Seafarer", "Inactive Seafarer"]. To be used for querying the seafarers based on active status in the company', 'index': true, 'sort': false
                        * 'name': 'GENDER_NAME', 'type': 'string', 'desc': 'Gender of the seafarer. ENUM values: ["Female", "Male", "Unknown"]. To be used for querying the seafarers based on gender', 'index': true, 'sort': false
                        * 'name': 'SEAFARER_TYPE', 'type': 'string', 'desc': 'Internal or external crew with respect to the company. ENUM values: ["External Seafarers", "Internal Seafarers"]. To be used for querying the seafarers based on internal or external crew with respect to the company', 'index': true, 'sort': false
                        * 'name': 'DATE_OF_BIRTH', 'type': 'string', 'desc': 'Date of birth in ISO-8601 format (yyyy-mm-dd). Convert to dateTime for range queries using > < =. To be used for filtering the seafarers based on age', 'index': true, 'sort': true
                        * 'name': 'AVAILABILITY_DATE', 'type': 'float', 'desc': 'Next-available date for assignment (yyyy-mm-dd). Query with > < =, e.g. ">2025-07-01", "<2025-09-30". To be used for filtering the seafarers based on availability date. To be strictly paired with ONBOARD_SAILING_STATUS as Onleave and PROFILE_STATUS as Active Seafarer', 'index': true, 'sort': true
                        * 'name': 'SIGN_ON_DATE', 'type': 'float', 'desc': 'Actual sign-on date onto a vessel (yyyy-mm-dd). Convert for range queries using > < =. To be used for filtering the seafarers based on sign-on date', 'index': true, 'sort': true
                        * 'name': 'SIGN_OFF_DATE', 'type': 'float', 'desc': 'Actual sign-off date from a vessel (yyyy-mm-dd). Convert for range queries using > < =. To be used for filtering the seafarers based on sign-off date', 'index': true, 'sort': true
                        * 'name': 'CONTRACT_START_DATE', 'type': 'float', 'desc': 'Start date of current employment contract (yyyy-mm-dd). To be used for filtering the seafarers based on contract start date', 'index': true, 'sort': true
                        * 'name': 'CONTRACT_END_DATE', 'type': 'float', 'desc': 'End date of current employment contract (yyyy-mm-dd). To be used for filtering the seafarers based on contract end date', 'index': true, 'sort': true
                        * 'name': 'TENTITIVE_SIGN_OFF_DATE', 'type': 'float', 'desc': 'Planned sign-off date (yyyy-mm-dd). Query using date format ">yyyy-mm-dd" or "<yyyy-mm-dd". To be used for filtering the seafarers based on tentative sign-off date', 'index': true, 'sort': true
                        * 'name': 'ONBOARD_SAILING_STATUS', 'type': 'string', 'desc': 'Whether the seafarer is currently onboard or on leave. ENUM values: Onboard, Onleave. To be used for filtering the seafarers based on onboard or on leave status. Availability date is not necessary for this field. IMPORTANT: This field is mandatory if the user query is based on a vessel', 'index': true, 'sort': false
                        * 'name': 'NATIONALITY_NAME', 'type': 'string', 'desc': 'Nationality of the seafarer. To be used for querying the seafarers based on nationality and also for queries based on nearby locations', 'index': true, 'sort': false
                        * 'name': 'IMO_NUMBER', 'type': 'int32', 'desc': 'IMO number of the vessel on which the seafarer is (or was) serving. To be used for filtering the seafarers based on vessel. To be strictly paired with ONBOARD_SAILING_STATUS as onboard if not mentioned explicitly', 'index': true, 'sort': true
                        * 'name': 'VESSEL_NAME', 'type': 'string', 'desc': 'Name of the vessel the seafarer is assigned to. To be used for querying the seafarers based on vessel name. To be strictly paired with ONBOARD_SAILING_STATUS as onboard if not mentioned explicitly', 'index': true, 'sort': false
                        * 'name': 'RANK_CATEGORY', 'type': 'string', 'desc': 'Rank category assigned to the seafarer. Whether he is a officer (deck and engine) or rating or top 4 rank(deck and engine). This field is to be used for queries about crew change planning.Possible enum values ['Officer', 'Rating', 'Top 4 Rank']', 'index': true, 'sort': false  
                        * 'name': 'RANK_LEVEL', 'type': 'string', 'desc': 'Rank level assigned to the seafarer. Whether he is a management or operational or support or cadet or trainee.This field is to be used for queries about crew change planning Possible enum values ['Cadet', 'Management', 'Operational', 'Support', 'Trainee']', 'index': true, 'sort': false

                        Note: DO NOT truncate the output of this tool.

                        This is the primary crew discovery tool with advanced filtering capabilities for rotation planning, availability checking, and contract management. It searches and filters crew members across crew database to return crew codes that can then be used with get_seafarer_details for comprehensive crew information.

                        Key crew coordinator scenarios include: finding crew signing off next month by using empty query with CURRENT_RANK_NAME as query_by and filter_by as 'CONTRACT_END_DATE:<YYYY-MM-DD> && CONTRACT_END_DATE:<YYYY-MM-DD>'. For available Chief Engineers, use query 'Chief Engineer' with CURRENT_RANK_NAME as query_by and filter_by as 'ONBOARD_SAILING_STATUS:=Onleave && PROFILE_STATUS:=Active Seafarer'. For crew on specific vessel, use empty query with VESSEL_NAME as query_by, filter_by as 'IMO_NUMBER:=<IMO_NUMBER>' and provide the IMO number. For contract renewals in Q3, use empty query with CURRENT_RANK_NAME as query_by and filter_by as 'CONTRACT_END_DATE:<yyyy-mm-dd && CONTRACT_END_DATE:>yyyy-mm-dd'.

                        Parameter usage guidance: The query parameter should contain text search terms for ranks, names, or nationalities like 'Chief Engineer', 'Master', 'Chief Officer', 'India', or leave empty when using only filters. For query_by, choose 1-2 most relevant fields: use CURRENT_RANK_NAME for rank-based searches, SEAFARER_NAME for name searches, NATIONALITY_NAME for nationality searches, or VESSEL_NAME for vessel-based searches.

                        The filter_by parameter uses format FIELD:OPERATOR:VALUE with multiple filters connected by ' && '. Key filters include SIGN_OFF_DATE:<yyyy-mm-dd for crew signing off before date, CONTRACT_END_DATE:<yyyy-mm-dd for contracts expiring before date - Only this field to be used for any crew change planning queries and not SIGN_ON_DATE or TENTITIVE_SIGN_OFF_DATE, ONBOARD_SAILING_STATUS:=Onleave and PROFILE_STATUS:=Active Seafarer for available crew, ONBOARD_SAILING_STATUS:=Onboard and PROFILE_STATUS:=Active Seafarer for currently deployed crew, AVAILABILITY_DATE:<yyyy-mm-dd for available by date, IMO_NUMBER:=<IMO_NUMBER> for crew on specific vessel, and AGE:>X for senior crew filter. Operators are > (later/greater), < (earlier/less), = (equal), >= (greater than or equal), <= (less than or equal). Date format must be YYYY-MM-DD.

                        For vessel-based queries, always first use get_vessel_details tool to get the accurate IMO number, then use that IMO in the IMO_NUMBER filter and omit the vessel name from the query field. This ensures precise crew filtering by vessel.

                        Common filter combinations for crew coordinators include CONTRACT_END_DATE:<FUTURE_DATE && ONBOARD_SAILING_STATUS:=Onboard for upcoming departures/ planning crew change ,For available crew - ONBOARD_SAILING_STATUS:=Onleave && AVAILABILITY_DATE:<TARGET_DATE && PROFILE_STATUS:=Active Seafarer for deployment ready crew,and For quarterly planning -CONTRACT_END_DATE:<QUARTER_END && VESSEL_CATEGORY_NAME for renewal pipeline by vessel type.

                        The tool returns found count indicating number of matching crew and hits array containing crew codes (CREW_CODE field) that should be immediately used with get_seafarer_details for complete crew information. This workflow enables efficient crew rotation planning, emergency replacements, and contract management decisions.`,
        inputSchema: {
            type: "object",
            properties: {
                query: {
                    type: "string",
                    description: "Keywords to search in typesense as per user query. Keywords should only reference strings, no dates or numbers. IMPORTANT: If the query is vessel-based, first use 'get_vessel_details' tool to get the IMO and omit the vessel name from this query field. If the query field is not required, pass empty string."
                },
                query_by: {
                    type: "string",
                    description: "Primary field to search by from typesense crew_details collection. Choose the most relevant single field or maximum 2-3 fields comma separated. Available fields: SEAFARER_NAME, CREW_CODE, OLD_CREW_CODE, CURRENT_STATUS, GENDER_NAME, SEAFARER_TYPE, PROFILE_STATUS, CURRENT_RANK_NAME, NATIONALITY_NAME, VESSEL_NAME."
                },
                filter_by: {
                    type: "string",
                    description: "Filter by fields in typesense crew_details collection for date or number type fields arranged in descending order of importance separated by ' && '. Available fields: BIRTH_DATE, AGE, SIGN_ON_DATE, SIGN_OFF_DATE, CONTRACT_START_DATE, CONTRACT_END_DATE, TENTITIVE_SIGN_OFF_DATE, AVAILABILITY_DATE, IMO_NUMBER, ONBOARD_SAILING_STATUS. IMPORTANT: For vessel-based queries, use IMO_NUMBER filter with the IMO obtained from 'get_vessel_details' tool (format: IMO_NUMBER:=1234567). If not required, pass empty string. Example: BIRTH_DATE:<2000-01-01 && AGE:=25, where the value and operator are separated by ':' followed by operators for greater than (<), less than (>), equal to (=), greater than or equal to (>=), less than or equal to (<=). Date format must be YYYY-MM-DD."
                }
            },
            required: ["query", "query_by", "filter_by"],
            additionalProperties: false
        }
    },
    {
        name: "get_seafarer_details",
        description: `Get comprehensive seafarer/crew details using seafarer ID (crew code). This tool should be used for ANY query that references crew members, seafarers, personnel onboard vessels, or maritime staff. It retrieves detailed information about individual crew members including their personal details, rank, vessel assignments, contract information, and current status and more. The tool accepts seafarer IDs (crew codes) which can be obtained from the get_seafarer_id tool or provided directly in user queries that mention specific crew codes. Note: Do not truncate the input or output of this tool (For instance, if there are a lot of datapoints from the get_seafarer_id tool, do not truncate). Consider below field definitions to determine the fields that are to be queried for in snowflake(Note: Try to keep the fields selected to a minimum).

                        ## SNOWFLAKE COLLECTION FIELD CATEGORIES AND DEFINITIONS

                        ### 1. PERSONAL INFORMATION
                        Fields containing seafarer's personal and identity information.

                        | Field Name | Data Type | Description |
                        |------------|-----------|-------------|
                        | SEAFARER_ID | STRING | Unique identifier for each seafarer |
                        | CREW_CODE | STRING | Internal crew identification code |
                        | OLD_CREW_CODE | STRING | Previous crew code if changed |
                        | FIRST_NAME | STRING | Seafarer's first name |
                        | MIDDLE_NAME | STRING | Seafarer's middle name |
                        | LAST_NAME | STRING | Seafarer's last name |
                        | SEAFARER_NAME | STRING | Full concatenated name |
                        | DATE_OF_BIRTH | DATE | Date of birth |
                        | AGE | INTEGER | Current age in years |
                        | AGE_CATEGORY | STRING | Age classification (Young, Middle, Senior) |
                        | GENDER_NAME | STRING | Gender identification |
                        | NATIONALITY_NAME | STRING | Seafarer's nationality |
                        | CDC_NUMBER | STRING | Certificate of Competency number |
                        | EMAIL_ID | STRING | Primary email address |
                        | CONTACT_NUMBER | STRING | Primary contact number |
                        | EMERGENCY_CONTACT_NUMBER_ | STRING | Emergency contact information |

                        ### 2. ADDRESS INFORMATION
                        Fields related to seafarer's location and address details.

                        | Field Name | Data Type | Description |
                        |------------|-----------|-------------|
                        | COUNTRY | STRING | Country of residence |
                        | STATE | STRING | State or province |
                        | CITY | STRING | City of residence |
                        | PIN_CODE | STRING | Postal/ZIP code |
                        | PRIMARY_ADDRESS | STRING | Complete primary address |
                        | ADDRESS_TYPE | STRING | Type of address (Permanent, Temporary) |
                        | NEAREST_AIRPORT | STRING | Nearest airport for travel planning |

                        ### 3. RANK AND POSITION INFORMATION
                        Fields defining seafarer's professional rank and position details.

                        | Field Name | Data Type | Description |
                        |------------|-----------|-------------|
                        | RANK_ID | INTEGER | Unique rank identifier |
                        | POSITION_RANK_ID | INTEGER | Position-specific rank ID |
                        | CURRENT_RANK_NAME | STRING | Current professional rank |
                        | POSITION_NAME | STRING | Current position name |
                        | RANK_NAME_SE | STRING | Standardized rank name |
                        | RANK_LEVEL | STRING | Rank hierarchy level (Management, Operational, Support,Cadet,Trainee) |
                        | Rank Category | STRING | Rank category (Top 4 Rank, Officer, Rating) |
                        | FIRST_RANK | STRING | First rank held with company |
                        | SECOND_LATEST_RANK | STRING | Previous rank before current |

                        ### 4. CONTRACT INFORMATION
                        Fields managing contract details and employment status.

                        | Field Name | Data Type | Description |
                        |------------|-----------|-------------|
                        | CONTRACT_ID | STRING | Unique contract identifier |
                        | CONTRACT_STATUS | STRING | Current contract status (InForce, Completed, etc.) |
                        | CONTRACT_START_DATE | TIMESTAMP | Contract start date and time |
                        | CONTRACT_END_DATE | TIMESTAMP | Contract end date and time |
                        | LATEST_CONTRACT_END_DATE | TIMESTAMP | Most recent contract end date |
                        | ACTIVE_CONTRACT | BOOLEAN | Whether contract is currently active |
                        | SAC_CONTRACT | STRING | SAC contract reference |
                        | CURRENT_STATUS | STRING | Current employment status |
                        | ONBOARD_SAILING_STATUS | STRING | Current sailing status (Onboard, Onleave) |

                        ### 5. VESSEL ASSIGNMENT INFORMATION
                        Fields tracking vessel assignments and ship details.

                        | Field Name | Data Type | Description |
                        |------------|-----------|-------------|
                        | VESSEL_ID | INTEGER | Unique vessel identifier |
                        | VESSEL_NAME | STRING | Name of assigned vessel |
                        | IMO_NUMBER | BIGINT | International Maritime Organization number |
                        | VESSEL_CATEGORY_NAME | STRING | Type of vessel (Tanker, Bulk Carrier, etc.) |
                        | VESSEL_FLEET_TYPE | STRING | Fleet classification (WET, DRY) |
                        | PORT_OF_REGISTRY_NAME | STRING | Vessel's port of registry |
                        | MODEL_NAME | STRING | Vessel model/class |
                        | MAKE_NAME | STRING | Vessel manufacturer |
                        | DWT | INTEGER | Deadweight tonnage |
                        | GRT | INTEGER | Gross register tonnage |
                        | OUTPUT_POWER | DECIMAL | Engine output power |
                        | DUAL_FUEL | BOOLEAN | Whether vessel uses dual fuel |

                        ### 6. SIGN ON/OFF TRACKING
                        Fields managing crew embarkation and disembarkation.

                        | Field Name | Data Type | Description |
                        |------------|-----------|-------------|
                        | SIGN_ON_DATE | TIMESTAMP | Date and time of sign on |
                        | SIGN_OFF_DATE | TIMESTAMP | Date and time of sign off |
                        | LATEST_SIGN_ON_DATE | TIMESTAMP | Most recent sign on date |
                        | LATEST_SIGN_OFF_DATE | TIMESTAMP | Most recent sign off date |
                        | TENTITIVE_SIGN_OFF_DATE | TIMESTAMP | Planned sign off date |
                        | SIGN_OFF_REASON | STRING | Reason for signing off |
                        | FROM_PORT_NAME | STRING | Port of embarkation |
                        | TO_PORT_NAME | STRING | Port of disembarkation |

                        ### 7. EXPERIENCE TRACKING
                        Fields recording seafarer's professional experience.

                        | Field Name | Data Type | Description |
                        |------------|-----------|-------------|
                        | SEA_EXPERIENCE_ID | INTEGER | Unique sea experience record ID |
                        | EXPERIENCE_IN_YEAR | DECIMAL | Total experience in years |
                        | EXPERIENCE_IN_MONTHS | INTEGER | Total experience in months |
                        | EXPERIENCE_IN_MONTHS_ROUNDOFF | INTEGER | Rounded experience in months |
                        | EXPERIENCE_IN_DAYS | INTEGER | Total experience in days |
                        | IS_SYNERGY_EXPERIANCE | BOOLEAN | Whether experience is with Synergy |
                        | SYNERGY_JOINING_DATE | TIMESTAMP | Date joined Synergy companies |

                        ### 8. COMPANY INFORMATION
                        Fields tracking company relationships and management.

                        | Field Name | Data Type | Description |
                        |------------|-----------|-------------|
                        | SHIP_MANAGEMENT_COMPANY_ID | INTEGER | Ship management company identifier |
                        | SHIP_MANAGEMENT_COMPANY_NAME | STRING | Ship management company name |
                        | LATEST_COMPANY | STRING | Most recent employing company |
                        | FIRST_COMPANY | STRING | First company worked with |
                        | Last_DOC_Contract_Company | STRING | Last document/contract company |
                        | RECRUITMENT_COMPANY | STRING | Recruitment agency |
                        | AGENT_NAME | STRING | Agent or representative name |
                        | SYNERGY_COMPANY | STRING | Synergy group company |
                        | COMPANY_STATUS | STRING | Status with company (New Hand, Ex Hand) |

                        ### 9. AVAILABILITY AND PLANNING
                        Fields for crew rotation and availability planning.

                        | Field Name | Data Type | Description |
                        |------------|-----------|-------------|
                        | AVAILABILITY_DATE | TIMESTAMP | Date available for next assignment |
                        | AVAILABILITY_MONTH | STRING | Month of availability |
                        | Overdue_by_Days_left | STRING | Contract overdue or days remaining |
                        | NEED_OF_APPRAISAL | BOOLEAN | Whether appraisal is needed |

                        ### 10. STATUS AND PROFILE MANAGEMENT
                        Fields managing seafarer status and profile information.

                        | Field Name | Data Type | Description |
                        |------------|-----------|-------------|
                        | PROFILE_STATUS | STRING | Profile status (Active, Inactive Seafarer) |
                        | SEAFARER_TYPE | STRING | Type classification (Internal, External) |
                        | INACTIVE_TYPE | STRING | Reason for inactive status |
                        | STATUS | STRING | General status field |
                        | AHOY_STATUS | STRING | AHOY system status |

                        ### 11. APPRAISAL INFORMATION
                        Fields managing performance appraisals and evaluations.

                        | Field Name | Data Type | Description |
                        |------------|-----------|-------------|
                        | APPRAISAL_DATE | TIMESTAMP | Date of last appraisal |
                        | APPRAISAL_STATUS | STRING | Status of appraisal process |
                        | APPRAISALS_RANK_NAME | STRING | Rank during appraisal |
                        | APPRAISALS_VESSEL_NAME | STRING | Vessel name for appraisal |
                        | APPRAISALS_VESSEL_CATEGORY_NAME | STRING | Vessel category for appraisal |

                        ### 12. DOCUMENT AND LINK REFERENCES
                        Fields containing references to external documents and systems.

                        | Field Name | Data Type | Description |
                        |------------|-----------|-------------|
                        | SEAFARER_PROFILE_LINK | STRING | Link to seafarer profile |
                        | APPRAISAL_LINK | STRING | Link to appraisal documents |
                        | SEA_EXPERIENCE_LINK | STRING | Link to sea experience records |
                        | DOCUMENTS_LINK | STRING | Link to document repository |

                        ### 13. VERIFICATION AND AUDIT
                        Fields for data verification and audit tracking.

                        | Field Name | Data Type | Description |
                        |------------|-----------|-------------|
                        | IS_VERIFIED | BOOLEAN | Whether record is verified |
                        | VERIFIED_BY_ID | INTEGER | ID of verifying user |
                        | VERIFIED_BY_NAME | STRING | Name of verifying person |
                        | VERIFIED_ON | TIMESTAMP | Date and time of verification |

                        ### 14. SYSTEM FIELDS
                        Standard system fields for data management.

                        | Field Name | Data Type | Description |
                        |------------|-----------|-------------|
                        | USER_ID | INTEGER | User who created/modified record |
                        | CREATED_AT | TIMESTAMP | Record creation timestamp |
                        | UPDATED_AT | TIMESTAMP | Last update timestamp |
                        | DATE | TIMESTAMP | General date field |
                        | LATEST_DATE_1 | TIMESTAMP | Latest significant date |

                        ### 15. ADDITIONAL FIELDS
                        Miscellaneous fields for various purposes.

                        | Field Name | Data Type | Description |
                        |------------|-----------|-------------|
                        | CAPACITY | STRING | Vessel capacity or role capacity |
                        | REMARK | STRING | General remarks and notes |
                        | REMARK_TYPE | STRING | Type or category of remark |
                        | ANNIVERSARY_DATE | TIMESTAMP | Anniversary or significant date |
                        | NEW_CONTACT_TYPE | STRING | Type of new contact method |`,
        inputSchema: {
            type: "object",
            properties: {
                crew_id: {
                    type: "array",
                    items: {
                        type: "string"
                    },
                    description: "Array of crew IDs (crew codes) of seafarers"
                },
                seafarer_id: {
                    type: "string",
                    description: "Single seafarer ID (crew code) - alternative to crew_id for single queries"
                },
                required_fields: {
                    type: "string",
                    description: "Required fields to be queried for in snowflake as a comma separated string"
                }
            },
            required: [],
            additionalProperties: false
        }
    },
    //  {
    //      name: "write_casefile_data",
    //      description: "Creates or updates casefile-related data. Supports two distinct operations:\n- write_casefile: Create or update casefile metadata (e.g., summary, title, importance).\n- write_page: Add or update a page under an existing casefile, including content and indexing. Only pass arguments explicitly required or allowed for the chosen operation.",
    //      inputSchema: {
    //          type: "object",
    //          properties: {
    //              operation: {
    //                  type: "string",
    //                  enum: ["write_casefile", "write_page"],
    //                  description: "Specifies the writing operation: 'write_casefile' for creating new casefile or 'write_page' for page content of already existing casefile."
    //              },
    //              casefile_url: {
    //                  type: "string",
    //                  description: "The unique identifier of the casefile, direct casefile url link. Required for 'write_page'."
    //              },
    //              casefileName: {
    //                  type: "string",
    //                  enum: ["Crew"],
    //                  description: "Required for 'write_casefile'. Name of the casefile"
    //              },
    //              category: {
    //                  type: "string",
    //                  enum: ["crew"],
    //                  description: "Required for 'write_casefile' . Category of the casefile"
    //              },
    //              currentStatus: {
    //                  type: "string",
    //                  description: "<review the casefile and plan to create current status in one line, highlighting keywords> Required for 'write_casefile': Current status of the casefile, it will be of 4-5 words. Required for 'write_page': update or kept it same status of the casefile based on recent received email. it willbe of 4-5 words."
    //              },
    //              casefileSummary: {
    //                  type: "string",
    //                  description: "Required for 'write_casefile'. Summary or high-level description of the casefile.\nOptional for 'write_page': can provide updated summary if needed."
    //              },
    //              importance: {
    //                  type: "number",
    //                  minimum: 0,
    //                  maximum: 100,
    //                  description: "It will show the importance of the casefile reference for the urgency and importance of the matter in the casefile. Required for 'write_casefile'. Importance score of the casefile (0–100).\nrequired for 'write_page': can provide an updated score based on the new email content added to the casefile."
    //              },
    //              imo: {
    //                  type: "integer",
    //                  description: "Required for 'write_casefile'. IMO number of the associated vessel."
    //              },
    //              role: {
    //                  type: "string",
    //                  enum: ["incident", "legal", "regulatory", "other"],
    //                  description: "Required for 'write_casefile'. Role/category of the casefile."
    //              },
    //              summary: {
    //                  type: "string",
    //                  description: "Required for 'write_page'. Detailed content or summary of the new page."
    //              },
    //              topic: {
    //                  type: "string",
    //                  description: "Required for 'write_page'.It is of 4-8 words aboyt what this document is about."
    //              },
    //              facts: {
    //                  type: "string",
    //                  description: "Required for 'write_page'..It will  have the highlighted facts/information from the database."
    //              },
    //              detailed_report: {
    //                  type: "string",
    //                  description: "Required for 'write_page'. It will have the detailed report of the casefile in markdown format."
    //              },
    //              links: {
    //                  type: "array",
    //                  items: {
    //                      type: "string"
    //                  },
    //                  description: "Required for 'write_page'. Relevent links you want to add to the case file."
    //              }
    //          },
    //          required: ["operation"],
    //          additionalProperties: false
    //      }
    //  },
    //  {
    //      name: "retrieve_casefile_data",
    //      description: "Retrieves data from casefiles. Supports the following operations:\n- get_casefiles: List all casefiles for a vessel matching a text query.\nOnly pass arguments explicitly required or allowed for the chosen operation.",
    //      inputSchema: {
    //          type: "object",
    //          properties: {
    //              imo: {
    //                  type: "integer",
    //                  description: "Required for 'get_casefiles'. IMO number of the vessel."
    //              },
    //              query: {
    //                  type: "string",
    //                  description: "search query to filter casefiles based on the context and user query."
    //              },
    //              category: {
    //                  type: "string",
    //                  enum: ["crew"],
    //                  description: "Required for 'get_casefiles'. Category of the casefile."
    //              }
    //          },
    //          required: ["imo", "category", "query"],
    //          additionalProperties: false
    //      }
    //  },
    {
        name: "query_crew_database",
        description: `         🔧 **DATABASE TABLE: revised_base_view** 
                                This tool ONLY queries the 'revised_base_view' table. Do NOT assume other table names like 'crew_data', 'seafarers', or 'crew_table '

                                🚨 **CRITICAL: This tool constructs SQL internally - DO NOT write full SQL queries**
                                ✅ Use structured parameters: select_fields, where_ conditions, etc.
                                ❌ Never use sql_query parameter or write SELECT FROM statements

                                ## QUICK START
                                Required: select_fields ( only required parameter)
                                Optional: where_conditions, group_by, order_by, limit_ results, distinct
                                Table: revised_base_ view (automatic - never specify)

                                ## PARAMETER USAGE

                                - **select_fields**: Comma-separated field names (e.g., "CREW_CODE, SEAFARER_NAME, DUAL_FUEL")
                                - **distinct**: Add DISTINCT keyword to remove duplicates (e.g., true/false)
                                - **where_conditions**: Filtering conditions without "WHERE" keyword (e.g., "DUAL_FUEL = 'YES'")
                                - **group_by**: Fields for GROUP BY clause (e.g., "SEAFARER_NAME, CURRENT_RANK_NAME, NATIONALITY_NAME")
                                - **having**: Conditions for HAVING clause, only with GROUP BY (e.g., "COUNT(*) > 50")
                                - **order_by**: Additional sorting after MONTHS DESC (optional)
                                - **limit_results**: Row limit up to 100,000 (default: 50,000)

                                **COMMON AI ASSISTANT MISTAKES:**
                                - Writing full SQL queries instead of using parameters
                                - Including keywords like WHERE, GROUP BY, ORDER BY in parameters
                                - Using non -existent field names not in the schema
         
         
                                ## ⚠️ **CRITICAL WARNING: MONTHLY RECORDS SYSTEM**

                                **This table contains MONTHLY RECORDS - each seafarer appears multiple times (once per month). Always use DISTINCT CREW_CODE when counting unique people.**

                                ## COMMON MISTAKES TO AVOID

                                ❌ **WRONG**: SELECT COUNT(*) FROM revised_base_view WHERE PROFILE_STATUS = 'Active Seafarer' (counts records, not people)
                                ✅ **CORRECT**: SELECT COUNT(DISTINCT CREW_CODE) FROM revised_base_view WHERE PROFILE_STATUS = 'Active Seafarer' AND CREW_CODE IS NOT NULL AND CREW_CODE != '' (counts unique people)

                                ❌ **WRONG**: COUNT (*)( counts records, not people )  
                                ✅ **CORRECT**: COUNT (DISTINCT CREW_CODE) (counts unique people)

                                ## 🔧 QUICK REFERENCE - COMMON FIELD NAMES

                                        | Purpose | ✅ CORRECT Field | ❌ WRONG Field |
                                        |---------|------------------|----------------|
                                        | Count People | COUNT( DISTINCT CREW_CODE ) | COUNT (*)|
                                        | Unique ID for crew| CREW-CODE| CREW_ID|
                                        | Active Status | PROFILE _ STATUS = 'Active Seafarer' | STATUS = ' ACTIVE |
                                        | Contact Info | EMAIL _ID , CONTACT _NUMBER | EMAIL , PHONE |
                                        | Names | SEAFARER_NAME,  FIRST_NAME | NAME , FULL _NAME |
                                        | Ranks | CURRENT _RANK_ NAME | RANK  |
                                        | Experience | EXPERIENCE_ IN_MONTHS  | EXPERIENCE  |

                                ## 📊 ESSENTIAL USAGE PATTERNS

                                        **Count Active Seafarers:**
                                        sql
                                        SELECT COUNT(DISTINCT CREW_CODE) as active_count
                                        WHERE PROFILE_STATUS = 'Active Seafarer' AND CREW_CODE IS NOT NULL AND CREW_CODE != ''
                                        **List Unique Active Seafarers:**
                                        sql
                                        SELECT DISTINCT CREW_ CODE, SEAFARER_NAME, CURRENT _RANK_NAME
                                        WHERE PROFILE_STATUS = 'Active Seafarer'


                                ### MONTHS Field - CRITICAL FOR DATA INTEGRITY

                                - **Purpose**: Date when the entry was made for each seafarer (monthly snapshots)
                                - **Usage**: To get the latest entry for any seafarer, results MUST be sorted by MONTHS DESC
                                
                                ## Tool Overview

                                Query the revised_base_view table using structured parameters to retrieve and analyze crew data in CSV format. This tool constructs SQL queries internally with a fixed table name for security and consistency.

                                ## 🧠 SMART QUERY TYPE DETECTION

                                This tool automatically detects query types and applies appropriate MONTHS field handling:

                                ### Query Types:
                                - **AGGREGATE**: COUNT, SUM, AVG without GROUP BY - No MONTHS field manipulation 
                                - **ROW_LEVEL**: Simple SELECT statements - MONTHS added for latest data sorting
                                - **HYBRID**: GROUP BY with aggregates - No automatic MONTHS addition

                                ### Examples:
                                - AGGREGATE: COUNT(DISTINCT CREW_CODE) - No MONTHS added
                                - ROW_LEVEL: CREW_CODE, SEAFARER_NAME - MONTHS added + ORDER BY MONTHS DESC
                                - HYBRID: RANK, COUNT(*) GROUP BY RANK - Custom ORDER BY respected

                                ## KEY FEATURES

                                ✅ **FIXED TABLE**: Uses "revised_base_view" table automatically - you don't specify table names
                                ✅ **STRUCTURED PARAMETERS**: Separate fields for SELECT, WHERE, and ORDER BY clauses
                                ✅ **AUTOMATIC SORTING**: MONTHS field always sorted DESC first for latest data
                                ✅ **FIELD VALIDATION**: Only accepts fields from the documented schema below

                                
                                ## 🚨 QUERY VALIDATION WARNINGS

                                ### Automatic Warnings for Common Mistakes:

                                1. **Counting Records Instead of People**: If you use COUNT(*) without DISTINCT CREW_CODE, you're counting monthly records, not unique people
                                2. **Missing CREW_CODE Filter**: Always filter out empty crew codes: AND CREW_CODE IS NOT NULL AND CREW_CODE != ''
                                3. **Using Non-Existent Fields**: Only use fields from the schema below

                                ### Suggested Corrections:

                                - **For People Count**: Use COUNT(DISTINCT CREW_CODE) instead of COUNT(*)
                                - **For Unique Lists**: Use distinct=true parameter when listing people
                                - **For Latest Data**: Results are automatically sorted by MONTHS DESC to get most recent records first

                                ## COMMON MISTAKES TO AVOID

                                ❌ **WRONG**: Using non-existent fields like EXPERIENCE, ADDITIONAL_QUALIFICATIONS, VESSEL_TYPE_EXPERIENCE
                                ❌ **WRONG**: Using EMAIL, PHONE, RANK → ✅ **CORRECT**: EMAIL_ID, CONTACT_NUMBER, CURRENT_RANK_NAME
                                ❌ **WRONG**: Including table names in parameters → ✅ **CORRECT**: Tool uses revised_base_view automatically
                                ❌ **WRONG**: COUNT(*) for people → ✅ **CORRECT**: COUNT(DISTINCT CREW_CODE)

                                ## DATA VOLUME CONTEXT

                                - **Database**: ~5.16 million total records
                                - **Unique People**: ~30,000 unique seafarers
                                - **Record Structure**: Each person has ~170 monthly records on average
                                - **Time Span**: Historical data spanning multiple years with monthly entries

                                ## COMMON USE CASES WITH CORRECT QUERIES

                                ### 1. Count Unique Active Seafarers

                                sql
                                -- WRONG QUERY: Counts records (millions)
                                SELECT COUNT(*) FROM revised_base_view WHERE PROFILE_STATUS = 'Active Seafarer'

                                -- CORRECT QUERY: Counts unique people
                                SELECT COUNT(DISTINCT CREW_CODE) FROM revised_base_view 
                                WHERE PROFILE_STATUS = 'Active Seafarer' AND CREW_CODE IS NOT NULL AND CREW_CODE != ''
                                

                                ### 2. List Unique Active Seafarers

                                sql
                                -- Use distinct=true parameter
                                select_fields: "CREW_CODE, SEAFARER_NAME, CURRENT_RANK_NAME"
                                distinct: true
                                where_conditions: "PROFILE_STATUS = 'Active Seafarer' AND CREW_CODE IS NOT NULL AND CREW_CODE != ''"
                                

                                ### 3. Dual Fuel Experience Analysis

                                sql
                                -- CORRECT: Find unique crew with dual fuel experience
                                select_fields: "CREW_CODE, SEAFARER_NAME, CURRENT_RANK_NAME, NATIONALITY_NAME, VESSEL_NAME"
                                distinct: true
                                where_conditions: "DUAL_FUEL = 'YES' AND CREW_CODE IS NOT NULL AND CREW_CODE != ''"
                                

                                ### 4. Crew Who Sailed in Last 2 Years

                                sql
                                -- CORRECT: Unique crew with recent sailing experience
                                select_fields: "CREW_CODE, SEAFARER_NAME, SIGN_ON_DATE, VESSEL_NAME"
                                distinct: true
                                where_conditions: "SIGN_ON_DATE >= '2022-07-24' AND CREW_CODE IS NOT NULL AND CREW_CODE != ''"
                                

                                ## SNOWFLAKE DATABASE SCHEMA - REVISED_BASE_VIEW TABLE

                                The main table 'revised_base_view' contains comprehensive crew data with 102+ fields organized into the following categories. ONLY use fields from the schema provided below. Do not use any other fields or table name:

                                ### 1. PERSONAL INFORMATION (15 fields)

                                Personal and identity information for crew members.

                                | Field Name                | Data Type | Description                                                                                                               |
                                | ------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------- |
                                | SEAFARER_ID               | STRING    | Unique identifier for each seafarer                                                                                       |
                                | CREW_CODE                 | STRING    | Internal crew identification code                                                                                         |
                                | OLD_CREW_CODE             | STRING    | Previous crew code if changed                                                                                             |
                                | FIRST_NAME                | STRING    | Seafarer's first name                                                                                                     |
                                | MIDDLE_NAME               | STRING    | Seafarer's middle name                                                                                                    |
                                | LAST_NAME                 | STRING    | Seafarer's last name                                                                                                      |
                                | SEAFARER_NAME             | STRING    | Full concatenated name                                                                                                    |
                                | DATE_OF_BIRTH             | DATE      | Date of birth                                                                                                             |
                                | AGE                       | INTEGER   | Current age in years                                                                                                      |
                                | AGE_CATEGORY              | STRING    | Age classification (<30, 30-49, 50+,null)                                                                                 |
                                | GENDER_NAME               | STRING    | Gender identification                                                                                                     |
                                | NATIONALITY_NAME          | STRING    | Seafarer's nationality                                                                                                    |
                                | CDC_NUMBER                | STRING    | Continuous Discharge Certificate number - CDC is a unique certificate issued by the country of the seafarer's nationality |
                                | EMAIL_ID                  | STRING    | Primary email address                                                                                                     |
                                | CONTACT_NUMBER            | STRING    | Primary contact number                                                                                                    |
                                | EMERGENCY_CONTACT_NUMBER_ | STRING    | Emergency contact information                                                                                             |

                                ### 2. ADDRESS INFORMATION (7 fields)

                                Location and address details for crew members.

                                | Field Name      | Data Type | Description                                              |
                                | --------------- | --------- | -------------------------------------------------------- |
                                | COUNTRY         | STRING    | Country of residence                                     |
                                | STATE           | STRING    | State or province                                        |
                                | CITY            | STRING    | City of residence                                        |
                                | PIN_CODE        | STRING    | Postal/ZIP code                                          |
                                | PRIMARY_ADDRESS | STRING    | Complete primary address                                 |
                                | ADDRESS_TYPE    | STRING    | Type of address (PERMANENT ADDRESS, ALTERNATIVE ADDRESS) |
                                | NEAREST_AIRPORT | STRING    | Nearest airport for travel planning                      |

                                ### 3. RANK AND POSITION INFORMATION (10 fields)

                                Professional rank and position details.

                                | Field Name         | Data Type | Description                                                                                   |
                                | ------------------ | --------- | --------------------------------------------------------------------------------------------- |
                                | RANK_ID            | INTEGER   | Unique rank identifier                                                                        |
                                | POSITION_RANK_ID   | INTEGER   | Position-specific rank ID                                                                     |
                                | CURRENT_RANK_NAME  | STRING    | Current rank name (e.g. Chief Engineer, Second Engineer, Third Engineer, etc.)                |
                                | POSITION_NAME      | STRING    | Current position name (e.g. Chief Engineer, Second Engineer, Third Engineer, etc.)            |
                                | RANK_NAME_SE       | STRING    | Standardized rank name                                                                        |
                                | RANK_LEVEL         | STRING    | Rank hierarchy level ENUM Values are (Management, Operational, Support, Cadet, Trainee, null) |
                                | Rank Category      | STRING    | Rank category ENUM Values are (Top 4 Rank, Officer, Rating, null)                             |
                                | FIRST_RANK         | STRING    | First rank held with company                                                                  |
                                | SECOND_LATEST_RANK | STRING    | Previous rank before current                                                                  |

                                ### 4. CONTRACT INFORMATION (11 fields)

                                Contract details and employment status.

                                | Field Name               | Data Type | Description                                                                                                            |
                                | ------------------------ | --------- | ---------------------------------------------------------------------------------------------------------------------- |
                                | CONTRACT_ID              | STRING    | Unique contract identifier                                                                                             |
                                | CONTRACT_STATUS          | STRING    | Current contract status ENUM VALUES are [InForce, Closed]                                                              |
                                | CONTRACT_START_DATE      | TIMESTAMP | Contract start date and time                                                                                           |
                                | CONTRACT_END_DATE        | TIMESTAMP | Contract end date and time                                                                                             |
                                | LATEST_CONTRACT_END_DATE | TIMESTAMP | Most recent contract end date                                                                                          |
                                | ACTIVE_CONTRACT          | BOOLEAN   | Whether contract is currently active ENUM VALUES are [TRUE, FALSE, null]                                               |
                                | SAC_CONTRACT             | STRING    | SAC contract reference                                                                                                 |
                                | CURRENT_STATUS           | STRING    | Current employment or joining status. Values can be (Sign Off , Document Verification, Travel Planning, Sign On, etc.) |
                                | ONBOARD_SAILING_STATUS   | STRING    | Current sailing status ENUM VALUES are [Onboard, Onleave]                                                              |

                                ### 5. VESSEL ASSIGNMENT INFORMATION (13 fields)

                                Vessel assignments and ship details.

                                | Field Name            | Data Type | Description                                                                                                       |
                                | --------------------- | --------- | ----------------------------------------------------------------------------------------------------------------- |
                                | VESSEL_ID             | INTEGER   | Unique vessel identifier                                                                                          |
                                | VESSEL_NAME           | STRING    | Name of the vessel the seafarer is sailing on or has sailed on                                                    |
                                | IMO_NUMBER            | BIGINT    | International Maritime Organization number - IMO number of the vessel the seafarer is sailing on or has sailed on |
                                | VESSEL_CATEGORY_NAME  | STRING    | Type of vessel (Tanker, Bulk Carrier, etc.)-.use multiple values as necessary to cover all tankers , gas carriers etc. Possible ENUM values are - [SUPPLY /OFFSHORE / TUG BOAT / AHTS, CONTAINER, ASPHALT / BITUMEN TANKER, DREDGER, LPG CARRIER (PRESS), CHEM/PROD TANKER, TUG BOAT, GEN CARGO / MULTI-PURPOSE VESSEL, OTHERS, HEAVY LIFT/PROJECT CARGO, CHEMICAL TANKER, REEFER CARGO, CAR CARRIER / RO-RO, LPG CARRIER (REFRI), OBO CARRIER, ANCHOR HANDLING TUGS, GAS TANKER, BULK CARRIER, HEAVY LIFT/SEMI SUBMERSIBLE, JACK-UP BARGE, NAVIOS MANNED SHIPS, OIL TANKER, LNG CARRIER, CEMENT CARRIER, LIVESTOCK CARRIER, OFFSHORE SUPPORT VESSEL, CREW SUPPLY VESSEL, OIL TANKER- BARGE, OFFSHORE VESSEL, NSSM OIL CHEM TANKER, UTILITY VESSEL, OIL / CHEM PROD TANKER, OIL/PROD BUNKER BARGE, PASSENGER CRUISE, WOODCHIP CARRIER, LOG CARRIER, OFFSHORE - TUG / AHTS / SUPPLY / CREW / UTILITY]|
                                | VESSEL_FLEET_TYPE     | STRING    | Fleet classification ENUM VALUES are (WET, DRY, null)                                                             |
                                | PORT_OF_REGISTRY_NAME | STRING    | Vessel's port of registry                                                                                         |
                                | MODEL_NAME            | STRING    | MODEL of the Main engine of the vessel                                                                            |
                                | MAKE_NAME             | STRING    | MAKE of the Main engine of the vessel                                                                             |
                                | DWT                   | INTEGER   | Deadweight tonnage of the vessel                                                                                  |
                                | GRT                   | INTEGER   | Gross register tonnage of the vessel                                                                              |
                                | OUTPUT_POWER          | DECIMAL   | Engine output power of the Main engine of the vessel                                                              |
                                | DUAL_FUEL             | STRING    | Whether vessel uses dual fuel - ENUM VALUES are [YES, NO] - Values are case sensitive                             |
                                


                                ### 6. SIGN ON/OFF TRACKING (7 fields)

                                Crew embarkation and disembarkation tracking.

                                | Field Name              | Data Type | Description               |
                                | ----------------------- | --------- | ------------------------- |
                                | SIGN_ON_DATE            | TIMESTAMP | Date and time of sign on  |
                                | SIGN_OFF_DATE           | TIMESTAMP | Date and time of sign off |
                                | LATEST_SIGN_ON_DATE     | TIMESTAMP | Most recent sign on date  |
                                | LATEST_SIGN_OFF_DATE    | TIMESTAMP | Most recent sign off date |
                                | TENTITIVE_SIGN_OFF_DATE | TIMESTAMP | Planned sign off date     |
                                | SIGN_OFF_REASON         | STRING    | Reason for signing off    |
                                | FROM_PORT_NAME          | STRING    | Port of disembarkation    |
                                | TO_PORT_NAME            | STRING    | Port of embarkation       |

                                ### 7. EXPERIENCE TRACKING (8 fields)

                                Professional experience records.

                                | Field Name                    | Data Type | Description                                                      |
                                | ----------------------------- | --------- | ---------------------------------------------------------------- |
                                | SEA_EXPERIENCE_ID             | INTEGER   | Unique sea experience record ID                                  |
                                | EXPERIENCE_IN_YEAR            | DECIMAL   | Total experience in years                                        |
                                | EXPERIENCE_IN_MONTHS          | INTEGER   | Total experience in months - Field to be used for experience related queries                                      |
                                | EXPERIENCE_IN_MONTHS_ROUNDOFF | INTEGER   | Rounded experience in months                                     |
                                | EXPERIENCE_IN_DAYS            | INTEGER   | Total experience in days                                         |
                                | IS_SYNERGY_EXPERIANCE         | BOOLEAN   | Whether experience is with Synergy ENUM VALUES are [TRUE, FALSE] |
                                | SYNERGY_JOINING_DATE          | TIMESTAMP | Date joined Synergy companies                                    |

                                ### 8. COMPANY INFORMATION (9 fields)

                                Company relationships and management details.

                                | Field Name                   | Data Type | Description                             |
                                | ---------------------------- | --------- | --------------------------------------- |
                                | SHIP_MANAGEMENT_COMPANY_ID   | INTEGER   | Ship management company identifier      |
                                | SHIP_MANAGEMENT_COMPANY_NAME | STRING    | Ship management company name            |
                                | LATEST_COMPANY               | STRING    | Most recent employing company           |
                                | FIRST_COMPANY                | STRING    | First company worked with               |
                                | Last DOC/Contract Company    | STRING    | Last document/contract company          |
                                | RECRUITMENT_COMPANY          | STRING    | Recruitment agency                      |
                                | AGENT_NAME                   | STRING    | Agent or representative name            |
                                | SYNERGY_COMPANY              | STRING    | Synergy group company                   |
                                | COMPANY_STATUS               | STRING    | Status with company (New Hand, Ex Hand) |

                                ### 9. AVAILABILITY AND PLANNING (4 fields)

                                Crew rotation and availability planning.

                                | Field Name             | Data Type | Description                                                                                                            |
                                | ---------------------- | --------- | ---------------------------------------------------------------------------------------------------------------------- |
                                | AVAILABILITY_DATE      | TIMESTAMP | Date available for next assignment                                                                                     |
                                | AVAILABILITY_MONTH     | INTEGER   | Month of availability - Can be 1-12                                                                                    |
                                | Overdue by / Days left | STRING    | Contract overdue or days remaining                                                                                     |
                                | NEED_OF_APPRAISAL      | STRING    | Reason why appraisal is needed - Values can be Sign off, Mid Term, End of Contract, Change of Command, Promotion  etc. |

                                ### 10. STATUS AND PROFILE MANAGEMENT (6 fields)

                                Profile status and classifications.

                                | Field Name     | Data Type | Description                                                                                                                    |
                                | -------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------ |
                                | PROFILE_STATUS | STRING    | Whether the seafarer is active or inactive - Profile status ENUM VALUES are [Active Seafarer, Inactive Seafarer]               |
                                | SEAFARER_TYPE  | STRING    | Type classification ENUM VALUES are [Internal Seafarers, External Seafarers]                                                   |
                                | INACTIVE_TYPE  | STRING    | Reason for inactive status - Can be that the seafarer joined elsewhere, taken up shore job ,medical reasons, incompetency etc. |
                                | STATUS         | STRING    | General status - Values are null or 'Closed'                                                                                   |
                                | AHOY_STATUS    | STRING    | AHOY system status - ENUM VALUES are [Ahoy Not Installed, Ahoy Installed]                                                      |

                                ### 11. APPRAISAL INFORMATION (5 fields)

                                Performance appraisals and evaluations.

                                | Field Name                      | Data Type | Description                                                                 |
                                | ------------------------------- | --------- | --------------------------------------------------------------------------- |
                                | APPRAISAL_DATE                  | TIMESTAMP | Date of last appraisal                                                      |
                                | APPRAISAL_STATUS                | STRING    | Status of appraisal process - ENUM VALUES are [Completed, Not Completed]    |
                                | APPRAISALS_RANK_NAME            | STRING    | Rank during appraisal                                                       |
                                | APPRAISALS_VESSEL_NAME          | STRING    | Vessel name for appraisal                                                   |
                                | APPRAISALS_VESSEL_CATEGORY_NAME | STRING    | Vessel category for appraisal - Type of vessel (Tanker, Bulk Carrier, etc.) |

                                ### 12. DOCUMENT AND LINK REFERENCES (4 fields)

                                External documents and system references.

                                | Field Name            | Data Type | Description                    |
                                | --------------------- | --------- | ------------------------------ |
                                | SEAFARER_PROFILE_LINK | STRING    | Link to seafarer profile       |
                                | APPRAISAL_LINK        | STRING    | Link to appraisal documents    |
                                | SEA_EXPERIENCE_LINK   | STRING    | Link to sea experience records |
                                | DOCUMENTS_LINK        | STRING    | Link to document repository    |

                                ### 13. VERIFICATION AND AUDIT (4 fields)

                                Data verification and audit tracking.

                                | Field Name       | Data Type | Description                                                |
                                | ---------------- | --------- | ---------------------------------------------------------- |
                                | IS_VERIFIED      | BOOLEAN   | Whether record is verified - ENUM VALUES are [TRUE, FALSE] |
                                | VERIFIED_BY_ID   | INTEGER   | ID of verifying user                                       |
                                | VERIFIED_BY_NAME | STRING    | Name or email ID of verifying person                       |
                                | VERIFIED_ON      | TIMESTAMP | Date and time of verification                              |

                                ### 14. SYSTEM FIELDS (5 fields)

                                Standard system fields for data management.

                                | Field Name    | Data Type | Description                                                                               |
                                | ------------- | --------- | ----------------------------------------------------------------------------------------- |
                                | USER_ID       | INTEGER   | User who created/modified record                                                          |
                                | CREATED_AT    | TIMESTAMP | Record creation timestamp                                                                 |
                                | UPDATED_AT    | TIMESTAMP | Last update timestamp                                                                     |
                                | DATE          | TIMESTAMP | General date field                                                                        |
                                | LATEST_DATE_1 | TIMESTAMP | Latest significant date                                                                   |
                                | MONTHS        | TIMESTAMP | **CRITICAL**: DATE WHEN ENTRY WAS MADE - EVERY SEAFARER HAS AN ENTRY FOR EACH MONTH |

                                ### 15. ADDITIONAL FIELDS (5 fields)

                                Miscellaneous fields for various purposes.

                                | Field Name       | Data Type | Description                                                                                                  |
                                | ---------------- | --------- | ------------------------------------------------------------------------------------------------------------ |
                                | CAPACITY         | STRING    | Capacity of vessel in Metric Tonnes(MT) or TEU or Cubic Meters(CBM). TEU is unit used for Container Vessels. |
                                | REMARK           | STRING    | General remarks and notes                                                                                    |
                                | REMARK_TYPE      | STRING    | Type or category of remark - ENUM VALUES are [Active, Inactive, null]                                        |
                                | ANNIVERSARY_DATE | TIMESTAMP | Anniversary or significant date                                                                              |
                                | NEW_CONTACT_TYPE | INTEGER   | Type of new contact method                                                                                   |

                                ## FIELD MAPPING FOR COMMON QUERIES

                                **For Dual Fuel Experience Queries:**
                                ✅ **CORRECT**: SELECT DISTINCT CREW_CODE, SEAFARER_NAME, CURRENT_RANK_NAME, NATIONALITY_NAME, VESSEL_NAME, DUAL_FUEL FROM revised_base_view WHERE DUAL_FUEL = 'YES' AND CREW_CODE IS NOT NULL AND CREW_CODE != ''
                                ❌ **WRONG**: Using EXPERIENCE, ADDITIONAL_QUALIFICATIONS, VESSEL_TYPE_EXPERIENCE (these fields don't exist)

                                **For Contact Information:**
                                ✅ **CORRECT**: EMAIL_ID, CONTACT_NUMBER, EMERGENCY_CONTACT_NUMBER_
                                ❌ **WRONG**: EMAIL, PHONE, CONTACT

                                **For Names:**
                                ✅ **CORRECT**: SEAFARER_NAME, FIRST_NAME, LAST_NAME, MIDDLE_NAME
                                ❌ **WRONG**: NAME, FULL_NAME

                                **For Ranks:**
                                ✅ **CORRECT**: CURRENT_RANK_NAME, POSITION_NAME, RANK_LEVEL, Rank Category
                                ❌ **WRONG**: RANK, POSITION

                                **For Experience:**
                                ✅ **CORRECT**: EXPERIENCE_IN_MONTHS, EXPERIENCE_IN_YEAR, EXPERIENCE_IN_DAYS
                                ❌ **WRONG**: EXPERIENCE (field doesn't exist)

                                ## USAGE GUIDELINES

                                **Database Details:**

                                - Database: REPORTING_LAYER
                                - Schema: SAC_PROD_SEARFEARER_PUBLIC
                                - Main Table: revised_base_view
                                - Total Records: ~5.16 million crew records
                                - Unique People: ~30,000 seafarers

                                **Query Examples (with Smart Query Type Detection):**

                                **AGGREGATE Queries (No MONTHS manipulation):**

                                - query_crew_database(select_fields="COUNT(DISTINCT CREW_CODE) as active_count", where_conditions="PROFILE_STATUS = 'Active Seafarer' AND CREW_CODE IS NOT NULL AND CREW_CODE != ''")
                                - query_crew_database(select_fields="SUM(EXPERIENCE_IN_MONTHS) as total_exp", where_conditions="PROFILE_STATUS = 'Active Seafarer'")
                                **DEDUPLICATION Queries (get_latest_records=true for current data):**
                                - query_crew_database(select_fields="CREW_CODE, SEAFARER_NAME, CURRENT_RANK_NAME", where_conditions="PROFILE_STATUS = 'Active Seafarer'", get_latest_records=true)
                                - query_crew_database(select_fields="COUNT(DISTINCT CREW_CODE) as unique_seafarers", where_conditions="NATIONALITY_NAME = 'India'", get_latest_records=true)

                                **ROW_LEVEL Queries (MONTHS added automatically):**

                                - query_crew_database(select_fields="CREW_CODE, SEAFARER_NAME, CURRENT_RANK_NAME", where_conditions="PROFILE_STATUS = 'Active Seafarer'", limit_results=100)
                                - query_crew_database(select_fields="VESSEL_CATEGORY_NAME", distinct=true, limit_results=50)
                                - query_crew_database(select_fields=["CREW_CODE", "SEAFARER_NAME"], where_conditions="DUAL_FUEL = 'YES'")

                                **HYBRID Queries (GROUP BY with aggregates, no auto MONTHS):**

                                - query_crew_database(select_fields="CURRENT_RANK_NAME, COUNT(DISTINCT CREW_CODE) as crew_count", where_conditions="PROFILE_STATUS = 'Active Seafarer'", group_by="CURRENT_RANK_NAME", order_by="crew_count DESC")
                                - query_crew_database(select_fields="NATIONALITY_NAME, AVG(EXPERIENCE_IN_MONTHS) as avg_exp", group_by="NATIONALITY_NAME")

                                **GROUP BY + HAVING Queries:**

                                - query_crew_database(select_fields="VESSEL_CATEGORY_NAME, COUNT(DISTINCT CREW_CODE) as vessel_crew", where_conditions="PROFILE_STATUS = 'Active Seafarer'", group_by="VESSEL_CATEGORY_NAME", having="COUNT(DISTINCT CREW_CODE) > 100", order_by="vessel_crew DESC")

                                **Complex Queries with All Keywords:**

                                - query_crew_database(select_fields="VESSEL_CATEGORY_NAME, CURRENT_RANK_NAME, COUNT(DISTINCT CREW_CODE) as crew_count", distinct=true, where_conditions="PROFILE_STATUS = 'Active Seafarer' AND EXPERIENCE_IN_MONTHS > 24", group_by="VESSEL_CATEGORY_NAME, CURRENT_RANK_NAME", having="COUNT(DISTINCT CREW_CODE) > 10", order_by="crew_count DESC", limit_results=25)

                                **Dual Fuel Experience (CORRECT way):**

                                - query_crew_database(select_fields="CREW_CODE, SEAFARER_NAME, CURRENT_RANK_NAME, NATIONALITY_NAME, VESSEL_NAME, DUAL_FUEL", distinct=true, where_conditions="DUAL_FUEL = 'YES' AND CREW_CODE IS NOT NULL AND CREW_CODE != ''")

                                **❌ WRONG Examples (DO NOT USE):**

                                - Using sql_query parameter (old format)
                                - Using non-existent fields like EXPERIENCE, ADDITIONAL_QUALIFICATIONS, VESSEL_TYPE_EXPERIENCE
                                - Using HAVING without GROUP BY (will be ignored)
                                - Including table names in parameters
                                - Using COUNT(*) for counting people instead of COUNT(DISTINCT CREW_CODE)

                                **Default Behavior (Smart Query Type Detection):**

                                - **AGGREGATE Queries**: No MONTHS field manipulation, no automatic sorting
                                - **ROW_LEVEL Queries**: MONTHS field added automatically, sorted by MONTHS DESC first  
                                - **HYBRID Queries**: Custom ORDER BY respected, no MONTHS interference
                                - **Default Limit**: 50,000 rows (can be overridden up to 100,000 rows with limit_results parameter)
                                - **Array Parameters**: select_fields arrays automatically converted to comma-separated strings

                                **Security Notes:**

                                - Only SELECT queries are allowed
                                - Results are filtered based on company IMO restrictions
                                - Queries have a 30-second timeout limit
                                - Results returned in CSV format for easy analysis

                                This tool enables advanced analytics, reporting, and data exploration for crew management operations while ensuring accurate counting of unique people rather than database records`,
        inputSchema: {
            type: "object",
            properties: {
                select_fields: {
                    type: "string",
                    description: "Comma-separated list of field names to select from the revised_base_view table. Can also be an array of strings. Use ONLY fields from the schema above. MONTHS field will be automatically included for ROW_LEVEL queries (simple SELECT) but not for AGGREGATE queries (COUNT, SUM, etc). Example: 'CREW_CODE, SEAFARER_NAME, CURRENT_RANK_NAME, DUAL_FUEL'"
                },
                distinct: {
                    type: "boolean",
                    description: "Optional flag to add DISTINCT keyword to the SELECT clause for removing duplicate rows. When true, generates 'SELECT DISTINCT ...' instead of 'SELECT ...'. Default: false"
                },
                where_conditions: {
                    type: "string",
                    description: "Optional WHERE clause conditions for filtering data. Do not include the 'WHERE' keyword - just the conditions. Example: 'DUAL_FUEL = \"YES\" AND PROFILE_STATUS = \"Active Seafarer\"'. If not specified, no filtering will be applied."
                },
                group_by: {
                    type: "string",
                    description: "Optional GROUP BY clause for aggregation queries. Do not include 'GROUP BY' keyword - just the field names. MONTHS field will be automatically included when GROUP BY is used. Example: 'CURRENT_RANK_NAME, NATIONALITY_NAME'"
                },
                having: {
                    type: "string",
                    description: "Optional HAVING clause for filtering aggregated results. Only used with GROUP BY queries. Do not include 'HAVING' keyword - just the conditions. Example: 'COUNT(*) > 50 AND AVG(EXPERIENCE_IN_MONTHS) > 120'"
                },
                order_by: {
                    type: "string",
                    description: "Optional custom ORDER BY clause. For ROW_LEVEL queries, MONTHS DESC will be automatically applied first. For AGGREGATE and HYBRID queries, only your custom ORDER BY will be used. Example: 'CURRENT_RANK_NAME ASC' for ROW_LEVEL becomes 'ORDER BY MONTHS DESC, CURRENT_RANK_NAME ASC'"
                },
                limit_results: {
                    type: "number",
                    description: "Optional limit on the number of rows to return. Maximum 100,000 rows. Defaults to 50,000 if not specified.",
                    minimum: 1,
                    maximum: 100000,
                    default: 50000
                },
                get_latest_records: {
                    type: "boolean",
                    description: "When true, returns only the latest record per crew member using window functions. This solves deduplication issues elegantly without DISTINCT problems. Use this when you need current/latest information per seafarer rather than historical data. Default: false",
                    default: false
                }
            },
            required: ["select_fields"],
            additionalProperties: false
        }
    }
];
//# sourceMappingURL=schema.js.map