imo-publications-mcp-server
Version:
MCP server for IMO (International Maritime Organization) publications - Node.js TypeScript version
60 lines (59 loc) • 2.35 kB
JavaScript
import axios, { AxiosError } from 'axios';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const logFile = path.join(os.tmpdir(), 'imo-publications-mcp.log');
const _AUTH_CACHE = {
token: null,
expires_at: 0,
};
export const logger = {
log: (message) => {
fs.appendFileSync(logFile, `[INFO] ${new Date().toISOString()} - ${message}\n`);
},
error: (message, error) => {
fs.appendFileSync(logFile, `[ERROR] ${new Date().toISOString()} - ${message}\n`);
if (error) {
fs.appendFileSync(logFile, `${error.stack || error}\n`);
}
}
};
export async function makeApiRequest({ baseUrl, endpoint, method = 'GET', params = {}, data = {}, headers = {}, apiKey = '', authService = '', pathParams = {} }) {
try {
let url = endpoint;
for (const [key, value] of Object.entries(pathParams)) {
url = url.replace(`{${key}}`, value);
}
const fullUrl = `${baseUrl}/${url}`.replace(/([^:]\/)\/+/g, '$1');
const defaultHeaders = {
'Content-Type': 'application/json'
};
logger.log(`Auth service name: ${authService}`);
if (authService === 'openai' || authService === 'cohere' || authService === 'perplexity') {
defaultHeaders['Authorization'] = `Bearer ${apiKey}`;
}
else if (apiKey) {
defaultHeaders['Authorization'] = apiKey;
}
logger.log(`Making ${method} request to ${fullUrl}`);
const response = await axios({
method,
url: fullUrl,
params,
data: method !== 'GET' ? data : undefined,
headers: { ...defaultHeaders, ...headers }
});
return response?.data;
}
catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
const errorResponse = error instanceof AxiosError ? error.response?.data : undefined;
logger.error(`API request failed: ${errorMessage}`, error);
logger.error(`Response data: ${JSON.stringify(errorResponse)}`);
throw new Error(`API request failed: ${errorMessage}`);
}
}