pms-analysis-reports-mcp-server
Version:
PMS analysis reports server handling maintenance reports, equipment analysis, compliance tracking, and performance metrics with ERP access for data extraction
377 lines • 16.4 kB
JavaScript
import { getTypesenseClient } from "../../utils/typesense.js";
import { fetchQADetails, getArtifact } from "../../utils/helper_functions.js";
import { DatabaseManager } from "../../utils/mongodb.js";
import { logger } from "../../index.js";
export class FuelAnalysisToolHandler {
constructor() {
this.typesenseClient = getTypesenseClient();
}
async getFuelOilAnalysisTableSchema(args) {
logger.info("getFuelOilAnalysisTableSchema called", args);
const category = args.category;
if (!category) {
throw new Error("category is required. Only the following properties are allowed: category. Please check the tool schema for getFuelOilAnalysisTableSchema for the allowed properties.");
}
const mongodbEtlDevDataDbName = process.env.MONGODB_ETL_DEV_DATA_DB_NAME || process.env.mongodbEtlDevDataDbName || 'syia-etl-dev';
const mongodbEtlDevDataUri = process.env.MONGODB_ETL_DEV_DATA_URI || process.env.mongodbEtlDevDataUri || '';
const dbManager = new DatabaseManager();
try {
await dbManager.initializeDatabase(mongodbEtlDevDataDbName, mongodbEtlDevDataUri);
const db = dbManager.getDb();
const collection = db.collection("typesense_schema");
const query = { category };
const projection = { _id: 0, schema: 1, category: 1 };
const documents = await collection.find(query, { projection }).toArray();
const formattedResults = {
count: documents.length,
documents
};
const formattedText = JSON.stringify(formattedResults, null, 2);
const response = {
type: "text",
text: formattedText
};
return [response];
}
catch (error) {
logger.error(`Error querying collection typesense_schema: ${error}`);
throw new Error(`Error querying collection: ${error}`);
}
finally {
await dbManager.closeDatabase();
}
}
async getLatestFuelBunkerDetails(args) {
logger.info("getLatestFuelBunkerDetails called", args);
try {
const imo = args.imo;
if (!imo) {
throw new Error("imo is required. Only the following properties are allowed: imo. Please check the tool schema for getLatestFuelBunkerDetails for the allowed properties.");
}
// Fetch QA details for question 83 (Latest Fuel Bunker Details)
const mongodbEtlDevDataDbName = process.env.MONGODB_ETL_DEV_DATA_DB_NAME || process.env.mongodbEtlDevDataDbName || 'syia-etl-dev';
const mongodbEtlDevDataUri = process.env.MONGODB_ETL_DEV_DATA_URI || process.env.mongodbEtlDevDataUri || '';
let result;
try {
result = await fetchQADetails(imo, 83, mongodbEtlDevDataDbName, mongodbEtlDevDataUri);
}
catch (error) {
// If no fuel bunker details found, return appropriate message
const noResultsResponse = {
type: "text",
text: "No fuel bunker details found for this vessel."
};
return [noResultsResponse];
}
// Get link and vessel name for MongoDB
const dataLink = result.Artifactlink ?? "";
const vesselName = result.vesselName || "";
// // Insert the data link to mongodb collection
// await insertDataLinkToMongoDB(
// dataLink,
// "latest fuel bunker details",
// sessionId,
// imo,
// vesselName,
// mongodbEtlDevDataDbName,
// mongodbEtlDevDataUri
// );
// Format results as JSON
const formattedText = JSON.stringify(result, null, 2);
// Create artifact
const artifactData = getArtifact("get_latest_fuel_bunker_details", dataLink);
const content = {
type: "text",
text: formattedText
};
const artifact = {
type: "text",
text: JSON.stringify(artifactData, null, 2)
};
return [content, artifact];
}
catch (error) {
logger.error("Error in getLatestFuelBunkerDetails", { error });
throw new Error(`Error retrieving fuel bunker details: ${error instanceof Error ? error.message : String(error)}`);
}
}
async getFleetFuelOilBunkerAnalysis(args) {
logger.info("getFleetFuelOilBunkerAnalysis called", args);
try {
const imo = args.imo;
if (!imo) {
throw new Error("imo is required. Only the following properties are allowed: imo. Please check the tool schema for getFleetFuelOilBunkerAnalysis for the allowed properties.");
}
// Fetch QA details for question 209 (Fleet Fuel Oil Bunker Analysis)
const mongodbEtlDevDataDbName = process.env.MONGODB_ETL_DEV_DATA_DB_NAME || process.env.mongodbEtlDevDataDbName || 'syia-etl-dev';
const mongodbEtlDevDataUri = process.env.MONGODB_ETL_DEV_DATA_URI || process.env.mongodbEtlDevDataUri || '';
let result;
try {
result = await fetchQADetails(imo, 209, mongodbEtlDevDataDbName, mongodbEtlDevDataUri);
}
catch (error) {
// If no fuel bunker details found, return appropriate message
const noResultsResponse = {
type: "text",
text: "No fuel bunker details found for this vessel."
};
return [noResultsResponse];
}
// Get link and vessel name for MongoDB
const dataLink = result.Artifactlink ?? "";
const vesselName = result.vesselName || "";
// // Insert the data link to mongodb collection
// await insertDataLinkToMongoDB(
// dataLink,
// "fleet fuel oil bunker analysis",
// sessionId,
// imo,
// vesselName,
// mongodbEtlDevDataDbName,
// mongodbEtlDevDataUri
// );
// Format results as JSON
const formattedText = JSON.stringify(result, null, 2);
// Create artifact
const artifactData = getArtifact("get_fleet_fuel_oil_bunker_analysis", dataLink);
const content = {
type: "text",
text: formattedText
};
const artifact = {
type: "text",
text: JSON.stringify(artifactData, null, 2)
};
return [content, artifact];
}
catch (error) {
logger.error("Error in getFleetFuelOilBunkerAnalysis", { error });
throw new Error(`Error retrieving fleet fuel oil bunker analysis: ${error instanceof Error ? error.message : String(error)}`);
}
}
}
// export async function getHistoricalFuelAnalysisData(args: HistoricalFuelAnalysisArgs): Promise<ToolResponse> {
// logger.info("Executing get_historical_fuel_analysis_data", { args });
//
// try {
// const imo = args.imo;
// const lookbackMonths = args.lookback_months;
// const fuelType = args.fuelType;
// const perPage = args.per_page || 100;
// const sessionId = args.session_id || "testing";
//
// if (!imo || !lookbackMonths) {
// throw new Error("IMO number and lookback period are required");
// }
//
// // Calculate the start date for the lookback period
// const startDate = new Date();
// startDate.setMonth(startDate.getMonth() - lookbackMonths);
// const startTs = Math.floor(startDate.getTime() / 1000);
//
// // Build filter_by string
// const filterBy = `imo:${imo} && bunkerDate:>${startTs}`;
//
// // Set up search parameters
// const searchParameters: any = {
// q: fuelType || "*",
// filter_by: filterBy,
// sort_by: "bunkerDate:desc",
// per_page: perPage
// };
//
// if (fuelType) {
// searchParameters.query_by = "fuelType";
// }
//
// // Execute search using TypesenseClient
// const results = await getTypesenseClient().collections("fuel_oil_data").documents().search(searchParameters);
//
// if (!results || !results.hits) {
// const noDataMessage = `No fuel analysis reports found for vessel ${imo} in the last ${lookbackMonths} months${fuelType ? ' with fuel type ' + fuelType : ''}.`;
// const noDataResponse: TextContent = {
// type: "text",
// text: noDataMessage
// };
// return [noDataResponse];
// }
//
// // Process all records
// const hits = results.hits;
// const processedReports = [];
//
// if (hits.length === 0) {
// const noDataMessage = `No fuel analysis reports found for vessel ${imo} in the last ${lookbackMonths} months${fuelType ? ' with fuel type ' + fuelType : ''}.`;
// const noDataResponse: TextContent = {
// type: "text",
// text: noDataMessage
// };
// return [noDataResponse];
// }
//
// for (const hit of hits as TypesenseHit[]) {
// let documentData = hit.document || {};
// // Convert dates if needed
// documentData = convertUnixDates(documentData);
//
// // Parse the report if a link is available
// const reportLink = documentData.reportLink;
// if (reportLink) {
// const report = await parseDocumentLink({ document_link: reportLink });
// documentData.report = report;
// }
//
// processedReports.push(documentData);
// }
//
// // Get data link
// const dataLink = await getDataLink(processedReports);
//
// // Get vessel name from processed reports
// const vesselName = processedReports[0]?.vesselName || "";
//
// // Insert the data link to mongodb collection
// const linkHeader = `historical fuel analysis data for past ${lookbackMonths} months${fuelType ? ' - ' + fuelType : ''}`;
// await insertDataLinkToMongoDB(dataLink || "", linkHeader, sessionId, imo, vesselName);
//
// // Format results
// const formattedText = JSON.stringify(processedReports, null, 2);
//
// // Create artifact
// const artifactData = getArtifact("get_historical_fuel_analysis_data", dataLink || "no_link");
//
// const content: TextContent = {
// type: "text",
// text: formattedText
// };
// const artifact: TextContent = {
// type: "text",
// text: JSON.stringify(artifactData, null, 2)
// };
// return [content, artifact];
//
// } catch (error) {
// logger.error("Error in getHistoricalFuelAnalysisData", { error });
// const errorResponse: TextContent = {
// type: "text",
// text: `Error retrieving historical fuel analysis data: ${error instanceof Error ? error.message : String(error)}`
// };
// return [errorResponse];
// }
// }
// export async function getLatestFuelAnalysisReport(args: LatestFuelAnalysisReportArgs): Promise<ToolResponse> {
// logger.info("Executing get_latest_fuel_analysis_report", { args });
//
// try {
// const imo = args.imo;
// const fuelType = args.fuelType;
// const perPage = args.per_page || 5;
// const sessionId = args.session_id || "testing";
//
// if (!imo) {
// throw new Error("IMO number is required");
// }
//
// // Build filter_by string
// const filterBy = `imo:${imo}`;
//
// // Set up search parameters
// const searchParameters: any = {
// q: fuelType || "*",
// filter_by: filterBy,
// sort_by: "bunkerDate:desc",
// per_page: perPage
// };
//
// if (fuelType) {
// searchParameters.query_by = "fuelType";
// }
//
// // Execute search using TypesenseClient
// const results = await getTypesenseClient().collections("fuel_oil_data").documents().search(searchParameters);
//
// // Check if results exist and have hits
// if (!results || !results.hits || results.hits.length === 0) {
// let noResultsMessage = `No fuel analysis reports found for vessel ${imo}`;
// if (fuelType) {
// noResultsMessage += ` with fuel type ${fuelType}`;
// }
//
// const noResultsResponse: TextContent = {
// type: "text",
// text: noResultsMessage
// };
// return [noResultsResponse];
// }
//
// // Get the hits array
// const hits = results.hits;
//
// // Additional safety check before accessing first element
// if (hits.length === 0) {
// const emptyResultsResponse: TextContent = {
// type: "text",
// text: `Search returned empty results for vessel ${imo}${fuelType ? ' with fuel type ' + fuelType : ''}.`
// };
// return [emptyResultsResponse];
// }
//
// // Safely get the latest record
// let latest;
// try {
// latest = hits[0].document;
// } catch (error) {
// const errorResponse: TextContent = {
// type: "text",
// text: `Error accessing search results: ${error instanceof Error ? error.message : String(error)}. The search results may be malformed.`
// };
// return [errorResponse];
// }
//
// latest = convertUnixDates(latest);
//
// // Parse the report if a link is available
// const reportLink = latest.reportLink;
// const report = reportLink ? await parseDocumentLink({ document_link: reportLink }) : null;
//
// latest.report = report;
// latest.reportLink = reportLink;
//
// // Get documents for data link
// const documents = hits.map((hit: any) => hit.document);
//
// // Get data link
// const dataLink = await getDataLink(documents);
//
// // Get vessel name from latest record
// const vesselName = latest.vesselName || "";
//
// // Insert the data link to mongodb collection
// const linkHeader = `latest fuel analysis report${fuelType ? ' for ' + fuelType : ''}`;
// await insertDataLinkToMongoDB(dataLink || "", linkHeader, sessionId, imo, vesselName);
//
// // Format results
// const formattedText = JSON.stringify(latest, null, 2);
//
// // Create artifact
// const artifactData = getArtifact("get_latest_fuel_analysis_report", dataLink || "no_link");
// const content: TextContent = {
// type: "text",
// text: formattedText
// };
// const artifact: TextContent = {
// type: "text",
// text: JSON.stringify(artifactData, null, 2)
// };
// return [content, artifact];
//
// } catch (error) {
// logger.error("Error in getLatestFuelAnalysisReport", { error });
// const errorResponse: TextContent = {
// type: "text",
// text: `Error retrieving fuel analysis report: ${error instanceof Error ? error.message : String(error)}`
// };
// return [errorResponse];
// }
// }
//# sourceMappingURL=fuelAnalysisTools.js.map