@cyanheads/pubchem-mcp-server 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +236 -0
- package/dist/config/index.d.ts +98 -0
- package/dist/config/index.js +326 -0
- package/dist/index.d.ts +24 -0
- package/dist/index.js +214 -0
- package/dist/mcp-server/server.d.ts +21 -0
- package/dist/mcp-server/server.js +124 -0
- package/dist/mcp-server/tools/fetchAssaySummary/index.d.ts +7 -0
- package/dist/mcp-server/tools/fetchAssaySummary/index.js +7 -0
- package/dist/mcp-server/tools/fetchAssaySummary/logic.d.ts +71 -0
- package/dist/mcp-server/tools/fetchAssaySummary/logic.js +96 -0
- package/dist/mcp-server/tools/fetchAssaySummary/registration.d.ts +12 -0
- package/dist/mcp-server/tools/fetchAssaySummary/registration.js +68 -0
- package/dist/mcp-server/tools/fetchCompoundProperties/index.d.ts +7 -0
- package/dist/mcp-server/tools/fetchCompoundProperties/index.js +7 -0
- package/dist/mcp-server/tools/fetchCompoundProperties/logic.d.ts +131 -0
- package/dist/mcp-server/tools/fetchCompoundProperties/logic.js +100 -0
- package/dist/mcp-server/tools/fetchCompoundProperties/registration.d.ts +13 -0
- package/dist/mcp-server/tools/fetchCompoundProperties/registration.js +52 -0
- package/dist/mcp-server/tools/fetchCompoundXrefs/index.d.ts +7 -0
- package/dist/mcp-server/tools/fetchCompoundXrefs/index.js +7 -0
- package/dist/mcp-server/tools/fetchCompoundXrefs/logic.d.ts +89 -0
- package/dist/mcp-server/tools/fetchCompoundXrefs/logic.js +145 -0
- package/dist/mcp-server/tools/fetchCompoundXrefs/registration.d.ts +13 -0
- package/dist/mcp-server/tools/fetchCompoundXrefs/registration.js +52 -0
- package/dist/mcp-server/tools/fetchSubstanceDetails/index.d.ts +7 -0
- package/dist/mcp-server/tools/fetchSubstanceDetails/index.js +7 -0
- package/dist/mcp-server/tools/fetchSubstanceDetails/logic.d.ts +69 -0
- package/dist/mcp-server/tools/fetchSubstanceDetails/logic.js +97 -0
- package/dist/mcp-server/tools/fetchSubstanceDetails/registration.d.ts +13 -0
- package/dist/mcp-server/tools/fetchSubstanceDetails/registration.js +79 -0
- package/dist/mcp-server/tools/getCompoundImage/index.d.ts +7 -0
- package/dist/mcp-server/tools/getCompoundImage/index.js +7 -0
- package/dist/mcp-server/tools/getCompoundImage/logic.d.ts +42 -0
- package/dist/mcp-server/tools/getCompoundImage/logic.js +68 -0
- package/dist/mcp-server/tools/getCompoundImage/registration.d.ts +12 -0
- package/dist/mcp-server/tools/getCompoundImage/registration.js +57 -0
- package/dist/mcp-server/tools/searchAssaysByTarget/index.d.ts +7 -0
- package/dist/mcp-server/tools/searchAssaysByTarget/index.js +7 -0
- package/dist/mcp-server/tools/searchAssaysByTarget/logic.d.ts +35 -0
- package/dist/mcp-server/tools/searchAssaysByTarget/logic.js +64 -0
- package/dist/mcp-server/tools/searchAssaysByTarget/registration.d.ts +12 -0
- package/dist/mcp-server/tools/searchAssaysByTarget/registration.js +62 -0
- package/dist/mcp-server/tools/searchCompoundByIdentifier/index.d.ts +7 -0
- package/dist/mcp-server/tools/searchCompoundByIdentifier/index.js +7 -0
- package/dist/mcp-server/tools/searchCompoundByIdentifier/logic.d.ts +35 -0
- package/dist/mcp-server/tools/searchCompoundByIdentifier/logic.js +59 -0
- package/dist/mcp-server/tools/searchCompoundByIdentifier/registration.d.ts +12 -0
- package/dist/mcp-server/tools/searchCompoundByIdentifier/registration.js +51 -0
- package/dist/mcp-server/tools/searchCompoundsByFormula/index.d.ts +7 -0
- package/dist/mcp-server/tools/searchCompoundsByFormula/index.js +7 -0
- package/dist/mcp-server/tools/searchCompoundsByFormula/logic.d.ts +38 -0
- package/dist/mcp-server/tools/searchCompoundsByFormula/logic.js +75 -0
- package/dist/mcp-server/tools/searchCompoundsByFormula/registration.d.ts +12 -0
- package/dist/mcp-server/tools/searchCompoundsByFormula/registration.js +62 -0
- package/dist/mcp-server/tools/searchCompoundsBySimilarity/index.d.ts +7 -0
- package/dist/mcp-server/tools/searchCompoundsBySimilarity/index.js +7 -0
- package/dist/mcp-server/tools/searchCompoundsBySimilarity/logic.d.ts +41 -0
- package/dist/mcp-server/tools/searchCompoundsBySimilarity/logic.js +82 -0
- package/dist/mcp-server/tools/searchCompoundsBySimilarity/registration.d.ts +12 -0
- package/dist/mcp-server/tools/searchCompoundsBySimilarity/registration.js +62 -0
- package/dist/mcp-server/tools/searchCompoundsByStructure/index.d.ts +7 -0
- package/dist/mcp-server/tools/searchCompoundsByStructure/index.js +7 -0
- package/dist/mcp-server/tools/searchCompoundsByStructure/logic.d.ts +41 -0
- package/dist/mcp-server/tools/searchCompoundsByStructure/logic.js +78 -0
- package/dist/mcp-server/tools/searchCompoundsByStructure/registration.d.ts +13 -0
- package/dist/mcp-server/tools/searchCompoundsByStructure/registration.js +63 -0
- package/dist/mcp-server/transports/auth/core/authContext.d.ts +33 -0
- package/dist/mcp-server/transports/auth/core/authContext.js +24 -0
- package/dist/mcp-server/transports/auth/core/authTypes.d.ts +17 -0
- package/dist/mcp-server/transports/auth/core/authTypes.js +5 -0
- package/dist/mcp-server/transports/auth/core/authUtils.d.ts +18 -0
- package/dist/mcp-server/transports/auth/core/authUtils.js +45 -0
- package/dist/mcp-server/transports/auth/index.d.ts +10 -0
- package/dist/mcp-server/transports/auth/index.js +9 -0
- package/dist/mcp-server/transports/auth/strategies/jwt/jwtMiddleware.d.ts +27 -0
- package/dist/mcp-server/transports/auth/strategies/jwt/jwtMiddleware.js +149 -0
- package/dist/mcp-server/transports/auth/strategies/oauth/oauthMiddleware.d.ts +20 -0
- package/dist/mcp-server/transports/auth/strategies/oauth/oauthMiddleware.js +124 -0
- package/dist/mcp-server/transports/httpErrorHandler.d.ts +26 -0
- package/dist/mcp-server/transports/httpErrorHandler.js +73 -0
- package/dist/mcp-server/transports/httpTransport.d.ts +21 -0
- package/dist/mcp-server/transports/httpTransport.js +208 -0
- package/dist/mcp-server/transports/stdioTransport.d.ts +42 -0
- package/dist/mcp-server/transports/stdioTransport.js +63 -0
- package/dist/services/pubchem/pubchemApiClient.d.ts +52 -0
- package/dist/services/pubchem/pubchemApiClient.js +120 -0
- package/dist/types-global/errors.d.ts +127 -0
- package/dist/types-global/errors.js +126 -0
- package/dist/utils/index.d.ts +12 -0
- package/dist/utils/index.js +20 -0
- package/dist/utils/internal/errorHandler.d.ts +176 -0
- package/dist/utils/internal/errorHandler.js +335 -0
- package/dist/utils/internal/index.d.ts +9 -0
- package/dist/utils/internal/index.js +9 -0
- package/dist/utils/internal/logger.d.ts +148 -0
- package/dist/utils/internal/logger.js +430 -0
- package/dist/utils/internal/requestContext.d.ts +83 -0
- package/dist/utils/internal/requestContext.js +72 -0
- package/dist/utils/metrics/index.d.ts +7 -0
- package/dist/utils/metrics/index.js +7 -0
- package/dist/utils/metrics/tokenCounter.d.ts +35 -0
- package/dist/utils/metrics/tokenCounter.js +110 -0
- package/dist/utils/network/fetchWithTimeout.d.ts +21 -0
- package/dist/utils/network/fetchWithTimeout.js +59 -0
- package/dist/utils/network/index.d.ts +6 -0
- package/dist/utils/network/index.js +5 -0
- package/dist/utils/parsing/dateParser.d.ts +73 -0
- package/dist/utils/parsing/dateParser.js +107 -0
- package/dist/utils/parsing/index.d.ts +8 -0
- package/dist/utils/parsing/index.js +8 -0
- package/dist/utils/parsing/jsonParser.d.ts +82 -0
- package/dist/utils/parsing/jsonParser.js +126 -0
- package/dist/utils/scheduling/index.d.ts +6 -0
- package/dist/utils/scheduling/index.js +6 -0
- package/dist/utils/scheduling/scheduler.d.ts +72 -0
- package/dist/utils/scheduling/scheduler.js +152 -0
- package/dist/utils/security/idGenerator.d.ts +137 -0
- package/dist/utils/security/idGenerator.js +215 -0
- package/dist/utils/security/index.d.ts +9 -0
- package/dist/utils/security/index.js +9 -0
- package/dist/utils/security/rateLimiter.d.ts +108 -0
- package/dist/utils/security/rateLimiter.js +179 -0
- package/dist/utils/security/sanitization.d.ts +184 -0
- package/dist/utils/security/sanitization.js +453 -0
- package/package.json +108 -0
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Barrel file for internal utility modules.
|
|
3
|
+
* This file re-exports core internal utilities related to error handling,
|
|
4
|
+
* logging, and request context management.
|
|
5
|
+
* @module src/utils/internal
|
|
6
|
+
*/
|
|
7
|
+
export * from "./errorHandler.js";
|
|
8
|
+
export * from "./logger.js";
|
|
9
|
+
export * from "./requestContext.js";
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { RequestContext } from "./requestContext.js";
|
|
2
|
+
/**
|
|
3
|
+
* Defines the supported logging levels based on RFC 5424 Syslog severity levels,
|
|
4
|
+
* as used by the Model Context Protocol (MCP).
|
|
5
|
+
* Levels are: 'debug'(7), 'info'(6), 'notice'(5), 'warning'(4), 'error'(3), 'crit'(2), 'alert'(1), 'emerg'(0).
|
|
6
|
+
* Lower numeric values indicate higher severity.
|
|
7
|
+
*/
|
|
8
|
+
export type McpLogLevel = "debug" | "info" | "notice" | "warning" | "error" | "crit" | "alert" | "emerg";
|
|
9
|
+
/**
|
|
10
|
+
* Interface for the payload of an MCP log notification.
|
|
11
|
+
* This structure is used when sending log data via MCP `notifications/message`.
|
|
12
|
+
*/
|
|
13
|
+
export interface McpLogPayload {
|
|
14
|
+
message: string;
|
|
15
|
+
context?: RequestContext;
|
|
16
|
+
error?: {
|
|
17
|
+
message: string;
|
|
18
|
+
stack?: string;
|
|
19
|
+
};
|
|
20
|
+
[key: string]: any;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Type for the `data` parameter of the `McpNotificationSender` function.
|
|
24
|
+
*/
|
|
25
|
+
export type McpNotificationData = McpLogPayload | Record<string, unknown>;
|
|
26
|
+
/**
|
|
27
|
+
* Defines the signature for a function that can send MCP log notifications.
|
|
28
|
+
* This function is typically provided by the MCP server instance.
|
|
29
|
+
* @param level - The severity level of the log message.
|
|
30
|
+
* @param data - The payload of the log notification.
|
|
31
|
+
* @param loggerName - An optional name or identifier for the logger/server.
|
|
32
|
+
*/
|
|
33
|
+
export type McpNotificationSender = (level: McpLogLevel, data: McpNotificationData, loggerName?: string) => void;
|
|
34
|
+
/**
|
|
35
|
+
* Singleton Logger class that wraps Winston for robust logging.
|
|
36
|
+
* Supports file logging, conditional console logging, and MCP notifications.
|
|
37
|
+
*/
|
|
38
|
+
export declare class Logger {
|
|
39
|
+
private static instance;
|
|
40
|
+
private winstonLogger?;
|
|
41
|
+
private interactionLogger?;
|
|
42
|
+
private initialized;
|
|
43
|
+
private mcpNotificationSender?;
|
|
44
|
+
private currentMcpLevel;
|
|
45
|
+
private currentWinstonLevel;
|
|
46
|
+
private readonly MCP_NOTIFICATION_STACK_TRACE_MAX_LENGTH;
|
|
47
|
+
private readonly LOG_FILE_MAX_SIZE;
|
|
48
|
+
private readonly LOG_MAX_FILES;
|
|
49
|
+
/** @private */
|
|
50
|
+
private constructor();
|
|
51
|
+
/**
|
|
52
|
+
* Initializes the Winston logger instance.
|
|
53
|
+
* Should be called once at application startup.
|
|
54
|
+
* @param level - The initial minimum MCP log level.
|
|
55
|
+
*/
|
|
56
|
+
initialize(level?: McpLogLevel): Promise<void>;
|
|
57
|
+
/**
|
|
58
|
+
* Sets the function used to send MCP 'notifications/message'.
|
|
59
|
+
* @param sender - The function to call for sending notifications, or undefined to disable.
|
|
60
|
+
*/
|
|
61
|
+
setMcpNotificationSender(sender: McpNotificationSender | undefined): void;
|
|
62
|
+
/**
|
|
63
|
+
* Dynamically sets the minimum logging level.
|
|
64
|
+
* @param newLevel - The new minimum MCP log level to set.
|
|
65
|
+
*/
|
|
66
|
+
setLevel(newLevel: McpLogLevel): void;
|
|
67
|
+
/**
|
|
68
|
+
* Configures the console transport based on the current log level and TTY status.
|
|
69
|
+
* Adds or removes the console transport as needed.
|
|
70
|
+
* @returns {{ enabled: boolean, message: string | null }} Status of console logging.
|
|
71
|
+
* @private
|
|
72
|
+
*/
|
|
73
|
+
private _configureConsoleTransport;
|
|
74
|
+
/**
|
|
75
|
+
* Gets the singleton instance of the Logger.
|
|
76
|
+
* @returns The singleton Logger instance.
|
|
77
|
+
*/
|
|
78
|
+
static getInstance(): Logger;
|
|
79
|
+
/**
|
|
80
|
+
* Ensures the logger has been initialized.
|
|
81
|
+
* @returns True if initialized, false otherwise.
|
|
82
|
+
* @private
|
|
83
|
+
*/
|
|
84
|
+
private ensureInitialized;
|
|
85
|
+
/**
|
|
86
|
+
* Centralized log processing method.
|
|
87
|
+
* @param level - The MCP severity level of the message.
|
|
88
|
+
* @param msg - The main log message.
|
|
89
|
+
* @param context - Optional request context for the log.
|
|
90
|
+
* @param error - Optional error object associated with the log.
|
|
91
|
+
* @private
|
|
92
|
+
*/
|
|
93
|
+
private log;
|
|
94
|
+
/** Logs a message at the 'debug' level. */
|
|
95
|
+
debug(msg: string, context?: RequestContext): void;
|
|
96
|
+
/** Logs a message at the 'info' level. */
|
|
97
|
+
info(msg: string, context?: RequestContext): void;
|
|
98
|
+
/** Logs a message at the 'notice' level. */
|
|
99
|
+
notice(msg: string, context?: RequestContext): void;
|
|
100
|
+
/** Logs a message at the 'warning' level. */
|
|
101
|
+
warning(msg: string, context?: RequestContext): void;
|
|
102
|
+
/**
|
|
103
|
+
* Logs a message at the 'error' level.
|
|
104
|
+
* @param msg - The main log message.
|
|
105
|
+
* @param err - Optional. Error object or RequestContext.
|
|
106
|
+
* @param context - Optional. RequestContext if `err` is an Error.
|
|
107
|
+
*/
|
|
108
|
+
error(msg: string, err?: Error | RequestContext, context?: RequestContext): void;
|
|
109
|
+
/**
|
|
110
|
+
* Logs a message at the 'crit' (critical) level.
|
|
111
|
+
* @param msg - The main log message.
|
|
112
|
+
* @param err - Optional. Error object or RequestContext.
|
|
113
|
+
* @param context - Optional. RequestContext if `err` is an Error.
|
|
114
|
+
*/
|
|
115
|
+
crit(msg: string, err?: Error | RequestContext, context?: RequestContext): void;
|
|
116
|
+
/**
|
|
117
|
+
* Logs a message at the 'alert' level.
|
|
118
|
+
* @param msg - The main log message.
|
|
119
|
+
* @param err - Optional. Error object or RequestContext.
|
|
120
|
+
* @param context - Optional. RequestContext if `err` is an Error.
|
|
121
|
+
*/
|
|
122
|
+
alert(msg: string, err?: Error | RequestContext, context?: RequestContext): void;
|
|
123
|
+
/**
|
|
124
|
+
* Logs a message at the 'emerg' (emergency) level.
|
|
125
|
+
* @param msg - The main log message.
|
|
126
|
+
* @param err - Optional. Error object or RequestContext.
|
|
127
|
+
* @param context - Optional. RequestContext if `err` is an Error.
|
|
128
|
+
*/
|
|
129
|
+
emerg(msg: string, err?: Error | RequestContext, context?: RequestContext): void;
|
|
130
|
+
/**
|
|
131
|
+
* Logs a message at the 'emerg' (emergency) level, typically for fatal errors.
|
|
132
|
+
* @param msg - The main log message.
|
|
133
|
+
* @param err - Optional. Error object or RequestContext.
|
|
134
|
+
* @param context - Optional. RequestContext if `err` is an Error.
|
|
135
|
+
*/
|
|
136
|
+
fatal(msg: string, err?: Error | RequestContext, context?: RequestContext): void;
|
|
137
|
+
/**
|
|
138
|
+
* Logs a structured interaction object to a dedicated file.
|
|
139
|
+
* @param interactionName - A name for the interaction type (e.g., 'OpenRouterIO').
|
|
140
|
+
* @param data - The structured data to log.
|
|
141
|
+
*/
|
|
142
|
+
logInteraction(interactionName: string, data: Record<string, any>): void;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* The singleton instance of the Logger.
|
|
146
|
+
* Use this instance for all logging operations.
|
|
147
|
+
*/
|
|
148
|
+
export declare const logger: Logger;
|
|
@@ -0,0 +1,430 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Provides a singleton Logger class that wraps Winston for file logging
|
|
3
|
+
* and supports sending MCP (Model Context Protocol) `notifications/message`.
|
|
4
|
+
* It handles different log levels compliant with RFC 5424 and MCP specifications.
|
|
5
|
+
* @module src/utils/internal/logger
|
|
6
|
+
*/
|
|
7
|
+
import path from "path";
|
|
8
|
+
import winston from "winston";
|
|
9
|
+
import { config } from "../../config/index.js";
|
|
10
|
+
/**
|
|
11
|
+
* Numeric severity mapping for MCP log levels (lower is more severe).
|
|
12
|
+
* @private
|
|
13
|
+
*/
|
|
14
|
+
const mcpLevelSeverity = {
|
|
15
|
+
emerg: 0,
|
|
16
|
+
alert: 1,
|
|
17
|
+
crit: 2,
|
|
18
|
+
error: 3,
|
|
19
|
+
warning: 4,
|
|
20
|
+
notice: 5,
|
|
21
|
+
info: 6,
|
|
22
|
+
debug: 7,
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* Maps MCP log levels to Winston's core levels for file logging.
|
|
26
|
+
* @private
|
|
27
|
+
*/
|
|
28
|
+
const mcpToWinstonLevel = {
|
|
29
|
+
debug: "debug",
|
|
30
|
+
info: "info",
|
|
31
|
+
notice: "info",
|
|
32
|
+
warning: "warn",
|
|
33
|
+
error: "error",
|
|
34
|
+
crit: "error",
|
|
35
|
+
alert: "error",
|
|
36
|
+
emerg: "error",
|
|
37
|
+
};
|
|
38
|
+
// The logsPath from config is already resolved and validated by src/config/index.ts
|
|
39
|
+
const resolvedLogsDir = config.logsPath;
|
|
40
|
+
const isLogsDirSafe = !!resolvedLogsDir; // If logsPath is set, it's considered safe by config logic.
|
|
41
|
+
/**
|
|
42
|
+
* Creates the Winston console log format.
|
|
43
|
+
* @returns The Winston log format for console output.
|
|
44
|
+
* @private
|
|
45
|
+
*/
|
|
46
|
+
function createWinstonConsoleFormat() {
|
|
47
|
+
return winston.format.combine(winston.format.colorize(), winston.format.timestamp({ format: "YYYY-MM-DD HH:mm:ss" }), winston.format.printf(({ timestamp, level, message, ...meta }) => {
|
|
48
|
+
let metaString = "";
|
|
49
|
+
const metaCopy = { ...meta };
|
|
50
|
+
if (metaCopy.error && typeof metaCopy.error === "object") {
|
|
51
|
+
const errorObj = metaCopy.error;
|
|
52
|
+
if (errorObj.message)
|
|
53
|
+
metaString += `\n Error: ${errorObj.message}`;
|
|
54
|
+
if (errorObj.stack)
|
|
55
|
+
metaString += `\n Stack: ${String(errorObj.stack)
|
|
56
|
+
.split("\n")
|
|
57
|
+
.map((l) => ` ${l}`)
|
|
58
|
+
.join("\n")}`;
|
|
59
|
+
delete metaCopy.error;
|
|
60
|
+
}
|
|
61
|
+
if (Object.keys(metaCopy).length > 0) {
|
|
62
|
+
try {
|
|
63
|
+
const replacer = (_key, value) => typeof value === "bigint" ? value.toString() : value;
|
|
64
|
+
const remainingMetaJson = JSON.stringify(metaCopy, replacer, 2);
|
|
65
|
+
if (remainingMetaJson !== "{}")
|
|
66
|
+
metaString += `\n Meta: ${remainingMetaJson}`;
|
|
67
|
+
}
|
|
68
|
+
catch (stringifyError) {
|
|
69
|
+
const errorMessage = stringifyError instanceof Error
|
|
70
|
+
? stringifyError.message
|
|
71
|
+
: String(stringifyError);
|
|
72
|
+
metaString += `\n Meta: [Error stringifying metadata: ${errorMessage}]`;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return `${timestamp} ${level}: ${message}${metaString}`;
|
|
76
|
+
}));
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Singleton Logger class that wraps Winston for robust logging.
|
|
80
|
+
* Supports file logging, conditional console logging, and MCP notifications.
|
|
81
|
+
*/
|
|
82
|
+
export class Logger {
|
|
83
|
+
/** @private */
|
|
84
|
+
constructor() {
|
|
85
|
+
this.initialized = false;
|
|
86
|
+
this.currentMcpLevel = "info";
|
|
87
|
+
this.currentWinstonLevel = "info";
|
|
88
|
+
this.MCP_NOTIFICATION_STACK_TRACE_MAX_LENGTH = 1024;
|
|
89
|
+
this.LOG_FILE_MAX_SIZE = 5 * 1024 * 1024; // 5MB
|
|
90
|
+
this.LOG_MAX_FILES = 5;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Initializes the Winston logger instance.
|
|
94
|
+
* Should be called once at application startup.
|
|
95
|
+
* @param level - The initial minimum MCP log level.
|
|
96
|
+
*/
|
|
97
|
+
async initialize(level = "info") {
|
|
98
|
+
if (this.initialized) {
|
|
99
|
+
this.warning("Logger already initialized.", {
|
|
100
|
+
loggerSetup: true,
|
|
101
|
+
requestId: "logger-init",
|
|
102
|
+
timestamp: new Date().toISOString(),
|
|
103
|
+
});
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
// Set initialized to true at the beginning of the initialization process.
|
|
107
|
+
this.initialized = true;
|
|
108
|
+
this.currentMcpLevel = level;
|
|
109
|
+
this.currentWinstonLevel = mcpToWinstonLevel[level];
|
|
110
|
+
// The logs directory (config.logsPath / resolvedLogsDir) is expected to be created and validated
|
|
111
|
+
// by the configuration module (src/config/index.ts) before logger initialization.
|
|
112
|
+
// If isLogsDirSafe is true, we assume resolvedLogsDir exists and is usable.
|
|
113
|
+
// No redundant directory creation logic here.
|
|
114
|
+
const fileFormat = winston.format.combine(winston.format.timestamp(), winston.format.errors({ stack: true }), winston.format.json());
|
|
115
|
+
const transports = [];
|
|
116
|
+
const fileTransportOptions = {
|
|
117
|
+
format: fileFormat,
|
|
118
|
+
maxsize: this.LOG_FILE_MAX_SIZE,
|
|
119
|
+
maxFiles: this.LOG_MAX_FILES,
|
|
120
|
+
tailable: true,
|
|
121
|
+
};
|
|
122
|
+
if (isLogsDirSafe) {
|
|
123
|
+
transports.push(new winston.transports.File({
|
|
124
|
+
filename: path.join(resolvedLogsDir, "error.log"),
|
|
125
|
+
level: "error",
|
|
126
|
+
...fileTransportOptions,
|
|
127
|
+
}), new winston.transports.File({
|
|
128
|
+
filename: path.join(resolvedLogsDir, "warn.log"),
|
|
129
|
+
level: "warn",
|
|
130
|
+
...fileTransportOptions,
|
|
131
|
+
}), new winston.transports.File({
|
|
132
|
+
filename: path.join(resolvedLogsDir, "info.log"),
|
|
133
|
+
level: "info",
|
|
134
|
+
...fileTransportOptions,
|
|
135
|
+
}), new winston.transports.File({
|
|
136
|
+
filename: path.join(resolvedLogsDir, "debug.log"),
|
|
137
|
+
level: "debug",
|
|
138
|
+
...fileTransportOptions,
|
|
139
|
+
}), new winston.transports.File({
|
|
140
|
+
filename: path.join(resolvedLogsDir, "combined.log"),
|
|
141
|
+
...fileTransportOptions,
|
|
142
|
+
}));
|
|
143
|
+
}
|
|
144
|
+
else {
|
|
145
|
+
if (process.stdout.isTTY) {
|
|
146
|
+
console.warn("File logging disabled as logsPath is not configured or invalid.");
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
this.winstonLogger = winston.createLogger({
|
|
150
|
+
level: this.currentWinstonLevel,
|
|
151
|
+
transports,
|
|
152
|
+
exitOnError: false,
|
|
153
|
+
});
|
|
154
|
+
// Initialize a separate logger for structured interactions
|
|
155
|
+
if (isLogsDirSafe) {
|
|
156
|
+
this.interactionLogger = winston.createLogger({
|
|
157
|
+
format: winston.format.combine(winston.format.timestamp(), winston.format.json({ space: 2 })),
|
|
158
|
+
transports: [
|
|
159
|
+
new winston.transports.File({
|
|
160
|
+
filename: path.join(resolvedLogsDir, "interactions.log"),
|
|
161
|
+
...fileTransportOptions,
|
|
162
|
+
}),
|
|
163
|
+
],
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
// Configure console transport after Winston logger is created
|
|
167
|
+
const consoleStatus = this._configureConsoleTransport();
|
|
168
|
+
const initialContext = {
|
|
169
|
+
loggerSetup: true,
|
|
170
|
+
requestId: "logger-init-deferred",
|
|
171
|
+
timestamp: new Date().toISOString(),
|
|
172
|
+
};
|
|
173
|
+
// Removed logging of logsDirCreatedMessage as it's no longer set
|
|
174
|
+
if (consoleStatus.message) {
|
|
175
|
+
this.info(consoleStatus.message, initialContext);
|
|
176
|
+
}
|
|
177
|
+
this.initialized = true; // Ensure this is set after successful setup
|
|
178
|
+
this.info(`Logger initialized. File logging level: ${this.currentWinstonLevel}. MCP logging level: ${this.currentMcpLevel}. Console logging: ${consoleStatus.enabled ? "enabled" : "disabled"}`, {
|
|
179
|
+
loggerSetup: true,
|
|
180
|
+
requestId: "logger-post-init",
|
|
181
|
+
timestamp: new Date().toISOString(),
|
|
182
|
+
logsPathUsed: resolvedLogsDir,
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Sets the function used to send MCP 'notifications/message'.
|
|
187
|
+
* @param sender - The function to call for sending notifications, or undefined to disable.
|
|
188
|
+
*/
|
|
189
|
+
setMcpNotificationSender(sender) {
|
|
190
|
+
this.mcpNotificationSender = sender;
|
|
191
|
+
const status = sender ? "enabled" : "disabled";
|
|
192
|
+
this.info(`MCP notification sending ${status}.`, {
|
|
193
|
+
loggerSetup: true,
|
|
194
|
+
requestId: "logger-set-sender",
|
|
195
|
+
timestamp: new Date().toISOString(),
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Dynamically sets the minimum logging level.
|
|
200
|
+
* @param newLevel - The new minimum MCP log level to set.
|
|
201
|
+
*/
|
|
202
|
+
setLevel(newLevel) {
|
|
203
|
+
const setLevelContext = {
|
|
204
|
+
loggerSetup: true,
|
|
205
|
+
requestId: "logger-set-level",
|
|
206
|
+
timestamp: new Date().toISOString(),
|
|
207
|
+
};
|
|
208
|
+
if (!this.ensureInitialized()) {
|
|
209
|
+
if (process.stdout.isTTY) {
|
|
210
|
+
console.error("Cannot set level: Logger not initialized.");
|
|
211
|
+
}
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
if (!(newLevel in mcpLevelSeverity)) {
|
|
215
|
+
this.warning(`Invalid MCP log level provided: ${newLevel}. Level not changed.`, setLevelContext);
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
const oldLevel = this.currentMcpLevel;
|
|
219
|
+
this.currentMcpLevel = newLevel;
|
|
220
|
+
this.currentWinstonLevel = mcpToWinstonLevel[newLevel];
|
|
221
|
+
if (this.winstonLogger) {
|
|
222
|
+
// Ensure winstonLogger is defined
|
|
223
|
+
this.winstonLogger.level = this.currentWinstonLevel;
|
|
224
|
+
}
|
|
225
|
+
const consoleStatus = this._configureConsoleTransport();
|
|
226
|
+
if (oldLevel !== newLevel) {
|
|
227
|
+
this.info(`Log level changed. File logging level: ${this.currentWinstonLevel}. MCP logging level: ${this.currentMcpLevel}. Console logging: ${consoleStatus.enabled ? "enabled" : "disabled"}`, setLevelContext);
|
|
228
|
+
if (consoleStatus.message &&
|
|
229
|
+
consoleStatus.message !== "Console logging status unchanged.") {
|
|
230
|
+
this.info(consoleStatus.message, setLevelContext);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Configures the console transport based on the current log level and TTY status.
|
|
236
|
+
* Adds or removes the console transport as needed.
|
|
237
|
+
* @returns {{ enabled: boolean, message: string | null }} Status of console logging.
|
|
238
|
+
* @private
|
|
239
|
+
*/
|
|
240
|
+
_configureConsoleTransport() {
|
|
241
|
+
if (!this.winstonLogger) {
|
|
242
|
+
return {
|
|
243
|
+
enabled: false,
|
|
244
|
+
message: "Cannot configure console: Winston logger not initialized.",
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
const consoleTransport = this.winstonLogger.transports.find((t) => t instanceof winston.transports.Console);
|
|
248
|
+
const shouldHaveConsole = this.currentMcpLevel === "debug" && process.stdout.isTTY;
|
|
249
|
+
let message = null;
|
|
250
|
+
if (shouldHaveConsole && !consoleTransport) {
|
|
251
|
+
const consoleFormat = createWinstonConsoleFormat();
|
|
252
|
+
this.winstonLogger.add(new winston.transports.Console({
|
|
253
|
+
level: "debug", // Console always logs debug if enabled
|
|
254
|
+
format: consoleFormat,
|
|
255
|
+
}));
|
|
256
|
+
message = "Console logging enabled (level: debug, stdout is TTY).";
|
|
257
|
+
}
|
|
258
|
+
else if (!shouldHaveConsole && consoleTransport) {
|
|
259
|
+
this.winstonLogger.remove(consoleTransport);
|
|
260
|
+
message = "Console logging disabled (level not debug or stdout not TTY).";
|
|
261
|
+
}
|
|
262
|
+
else {
|
|
263
|
+
message = "Console logging status unchanged.";
|
|
264
|
+
}
|
|
265
|
+
return { enabled: shouldHaveConsole, message };
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Gets the singleton instance of the Logger.
|
|
269
|
+
* @returns The singleton Logger instance.
|
|
270
|
+
*/
|
|
271
|
+
static getInstance() {
|
|
272
|
+
if (!Logger.instance) {
|
|
273
|
+
Logger.instance = new Logger();
|
|
274
|
+
}
|
|
275
|
+
return Logger.instance;
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* Ensures the logger has been initialized.
|
|
279
|
+
* @returns True if initialized, false otherwise.
|
|
280
|
+
* @private
|
|
281
|
+
*/
|
|
282
|
+
ensureInitialized() {
|
|
283
|
+
if (!this.initialized || !this.winstonLogger) {
|
|
284
|
+
if (process.stdout.isTTY) {
|
|
285
|
+
console.warn("Logger not initialized; message dropped.");
|
|
286
|
+
}
|
|
287
|
+
return false;
|
|
288
|
+
}
|
|
289
|
+
return true;
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* Centralized log processing method.
|
|
293
|
+
* @param level - The MCP severity level of the message.
|
|
294
|
+
* @param msg - The main log message.
|
|
295
|
+
* @param context - Optional request context for the log.
|
|
296
|
+
* @param error - Optional error object associated with the log.
|
|
297
|
+
* @private
|
|
298
|
+
*/
|
|
299
|
+
log(level, msg, context, error) {
|
|
300
|
+
if (!this.ensureInitialized())
|
|
301
|
+
return;
|
|
302
|
+
if (mcpLevelSeverity[level] > mcpLevelSeverity[this.currentMcpLevel]) {
|
|
303
|
+
return; // Do not log if message level is less severe than currentMcpLevel
|
|
304
|
+
}
|
|
305
|
+
const logData = { ...context };
|
|
306
|
+
const winstonLevel = mcpToWinstonLevel[level];
|
|
307
|
+
if (error) {
|
|
308
|
+
this.winstonLogger.log(winstonLevel, msg, { ...logData, error });
|
|
309
|
+
}
|
|
310
|
+
else {
|
|
311
|
+
this.winstonLogger.log(winstonLevel, msg, logData);
|
|
312
|
+
}
|
|
313
|
+
if (this.mcpNotificationSender) {
|
|
314
|
+
const mcpDataPayload = { message: msg };
|
|
315
|
+
if (context && Object.keys(context).length > 0)
|
|
316
|
+
mcpDataPayload.context = context;
|
|
317
|
+
if (error) {
|
|
318
|
+
mcpDataPayload.error = { message: error.message };
|
|
319
|
+
// Include stack trace in debug mode for MCP notifications, truncated for brevity
|
|
320
|
+
if (this.currentMcpLevel === "debug" && error.stack) {
|
|
321
|
+
mcpDataPayload.error.stack = error.stack.substring(0, this.MCP_NOTIFICATION_STACK_TRACE_MAX_LENGTH);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
try {
|
|
325
|
+
const serverName = config?.mcpServerName ?? "MCP_SERVER_NAME_NOT_CONFIGURED";
|
|
326
|
+
this.mcpNotificationSender(level, mcpDataPayload, serverName);
|
|
327
|
+
}
|
|
328
|
+
catch (sendError) {
|
|
329
|
+
const errorMessage = sendError instanceof Error ? sendError.message : String(sendError);
|
|
330
|
+
const internalErrorContext = {
|
|
331
|
+
requestId: context?.requestId || "logger-internal-error",
|
|
332
|
+
timestamp: new Date().toISOString(),
|
|
333
|
+
originalLevel: level,
|
|
334
|
+
originalMessage: msg,
|
|
335
|
+
sendError: errorMessage,
|
|
336
|
+
mcpPayload: JSON.stringify(mcpDataPayload).substring(0, 500), // Log a preview
|
|
337
|
+
};
|
|
338
|
+
this.winstonLogger.error("Failed to send MCP log notification", internalErrorContext);
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
/** Logs a message at the 'debug' level. */
|
|
343
|
+
debug(msg, context) {
|
|
344
|
+
this.log("debug", msg, context);
|
|
345
|
+
}
|
|
346
|
+
/** Logs a message at the 'info' level. */
|
|
347
|
+
info(msg, context) {
|
|
348
|
+
this.log("info", msg, context);
|
|
349
|
+
}
|
|
350
|
+
/** Logs a message at the 'notice' level. */
|
|
351
|
+
notice(msg, context) {
|
|
352
|
+
this.log("notice", msg, context);
|
|
353
|
+
}
|
|
354
|
+
/** Logs a message at the 'warning' level. */
|
|
355
|
+
warning(msg, context) {
|
|
356
|
+
this.log("warning", msg, context);
|
|
357
|
+
}
|
|
358
|
+
/**
|
|
359
|
+
* Logs a message at the 'error' level.
|
|
360
|
+
* @param msg - The main log message.
|
|
361
|
+
* @param err - Optional. Error object or RequestContext.
|
|
362
|
+
* @param context - Optional. RequestContext if `err` is an Error.
|
|
363
|
+
*/
|
|
364
|
+
error(msg, err, context) {
|
|
365
|
+
const errorObj = err instanceof Error ? err : undefined;
|
|
366
|
+
const actualContext = err instanceof Error ? context : err;
|
|
367
|
+
this.log("error", msg, actualContext, errorObj);
|
|
368
|
+
}
|
|
369
|
+
/**
|
|
370
|
+
* Logs a message at the 'crit' (critical) level.
|
|
371
|
+
* @param msg - The main log message.
|
|
372
|
+
* @param err - Optional. Error object or RequestContext.
|
|
373
|
+
* @param context - Optional. RequestContext if `err` is an Error.
|
|
374
|
+
*/
|
|
375
|
+
crit(msg, err, context) {
|
|
376
|
+
const errorObj = err instanceof Error ? err : undefined;
|
|
377
|
+
const actualContext = err instanceof Error ? context : err;
|
|
378
|
+
this.log("crit", msg, actualContext, errorObj);
|
|
379
|
+
}
|
|
380
|
+
/**
|
|
381
|
+
* Logs a message at the 'alert' level.
|
|
382
|
+
* @param msg - The main log message.
|
|
383
|
+
* @param err - Optional. Error object or RequestContext.
|
|
384
|
+
* @param context - Optional. RequestContext if `err` is an Error.
|
|
385
|
+
*/
|
|
386
|
+
alert(msg, err, context) {
|
|
387
|
+
const errorObj = err instanceof Error ? err : undefined;
|
|
388
|
+
const actualContext = err instanceof Error ? context : err;
|
|
389
|
+
this.log("alert", msg, actualContext, errorObj);
|
|
390
|
+
}
|
|
391
|
+
/**
|
|
392
|
+
* Logs a message at the 'emerg' (emergency) level.
|
|
393
|
+
* @param msg - The main log message.
|
|
394
|
+
* @param err - Optional. Error object or RequestContext.
|
|
395
|
+
* @param context - Optional. RequestContext if `err` is an Error.
|
|
396
|
+
*/
|
|
397
|
+
emerg(msg, err, context) {
|
|
398
|
+
const errorObj = err instanceof Error ? err : undefined;
|
|
399
|
+
const actualContext = err instanceof Error ? context : err;
|
|
400
|
+
this.log("emerg", msg, actualContext, errorObj);
|
|
401
|
+
}
|
|
402
|
+
/**
|
|
403
|
+
* Logs a message at the 'emerg' (emergency) level, typically for fatal errors.
|
|
404
|
+
* @param msg - The main log message.
|
|
405
|
+
* @param err - Optional. Error object or RequestContext.
|
|
406
|
+
* @param context - Optional. RequestContext if `err` is an Error.
|
|
407
|
+
*/
|
|
408
|
+
fatal(msg, err, context) {
|
|
409
|
+
const errorObj = err instanceof Error ? err : undefined;
|
|
410
|
+
const actualContext = err instanceof Error ? context : err;
|
|
411
|
+
this.log("emerg", msg, actualContext, errorObj);
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* Logs a structured interaction object to a dedicated file.
|
|
415
|
+
* @param interactionName - A name for the interaction type (e.g., 'OpenRouterIO').
|
|
416
|
+
* @param data - The structured data to log.
|
|
417
|
+
*/
|
|
418
|
+
logInteraction(interactionName, data) {
|
|
419
|
+
if (!this.interactionLogger) {
|
|
420
|
+
this.warning("Interaction logger not available. File logging may be disabled.", data.context);
|
|
421
|
+
return;
|
|
422
|
+
}
|
|
423
|
+
this.interactionLogger.info({ interactionName, ...data });
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
/**
|
|
427
|
+
* The singleton instance of the Logger.
|
|
428
|
+
* Use this instance for all logging operations.
|
|
429
|
+
*/
|
|
430
|
+
export const logger = Logger.getInstance();
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview Utilities for creating and managing request contexts.
|
|
3
|
+
* A request context is an object carrying a unique ID, timestamp, and other
|
|
4
|
+
* relevant data for logging, tracing, and processing. It also defines
|
|
5
|
+
* configuration and operational context structures.
|
|
6
|
+
* @module src/utils/internal/requestContext
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* Defines the core structure for context information associated with a request or operation.
|
|
10
|
+
* This is fundamental for logging, tracing, and passing operational data.
|
|
11
|
+
*/
|
|
12
|
+
export interface RequestContext {
|
|
13
|
+
/**
|
|
14
|
+
* Unique ID for the context instance.
|
|
15
|
+
* Used for log correlation and request tracing.
|
|
16
|
+
*/
|
|
17
|
+
requestId: string;
|
|
18
|
+
/**
|
|
19
|
+
* ISO 8601 timestamp indicating when the context was created.
|
|
20
|
+
*/
|
|
21
|
+
timestamp: string;
|
|
22
|
+
/**
|
|
23
|
+
* Allows arbitrary key-value pairs for specific context needs.
|
|
24
|
+
* Using `unknown` promotes type-safe access.
|
|
25
|
+
* Consumers must type-check/assert when accessing extended properties.
|
|
26
|
+
*/
|
|
27
|
+
[key: string]: unknown;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Configuration for the {@link requestContextService}.
|
|
31
|
+
* Allows for future extensibility of service-wide settings.
|
|
32
|
+
*/
|
|
33
|
+
export interface ContextConfig {
|
|
34
|
+
/** Custom configuration properties. Allows for arbitrary key-value pairs. */
|
|
35
|
+
[key: string]: unknown;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Represents a broader context for a specific operation or task.
|
|
39
|
+
* It can optionally include a base {@link RequestContext} and other custom properties
|
|
40
|
+
* relevant to the operation.
|
|
41
|
+
*/
|
|
42
|
+
export interface OperationContext {
|
|
43
|
+
/** Optional base request context data, adhering to the `RequestContext` structure. */
|
|
44
|
+
requestContext?: RequestContext;
|
|
45
|
+
/** Allows for additional, custom properties specific to the operation. */
|
|
46
|
+
[key: string]: unknown;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Primary export for request context functionalities.
|
|
50
|
+
* This service provides methods to create and manage {@link RequestContext} instances,
|
|
51
|
+
* which are essential for logging, tracing, and correlating operations.
|
|
52
|
+
*/
|
|
53
|
+
export declare const requestContextService: {
|
|
54
|
+
/**
|
|
55
|
+
* Internal configuration store for the service.
|
|
56
|
+
*/
|
|
57
|
+
config: ContextConfig;
|
|
58
|
+
/**
|
|
59
|
+
* Configures the request context service with new settings.
|
|
60
|
+
* Merges the provided partial configuration with existing settings.
|
|
61
|
+
*
|
|
62
|
+
* @param config - A partial `ContextConfig` object containing settings to update or add.
|
|
63
|
+
* @returns A shallow copy of the newly updated configuration.
|
|
64
|
+
*/
|
|
65
|
+
configure(config: Partial<ContextConfig>): ContextConfig;
|
|
66
|
+
/**
|
|
67
|
+
* Retrieves a shallow copy of the current service configuration.
|
|
68
|
+
* This prevents direct mutation of the internal configuration state.
|
|
69
|
+
*
|
|
70
|
+
* @returns A shallow copy of the current `ContextConfig`.
|
|
71
|
+
*/
|
|
72
|
+
getConfig(): ContextConfig;
|
|
73
|
+
/**
|
|
74
|
+
* Creates a new {@link RequestContext} instance.
|
|
75
|
+
* Each context is assigned a unique `requestId` (UUID) and a current `timestamp` (ISO 8601).
|
|
76
|
+
* Additional custom properties can be merged into the context.
|
|
77
|
+
*
|
|
78
|
+
* @param additionalContext - An optional record of key-value pairs to be
|
|
79
|
+
* included in the created request context.
|
|
80
|
+
* @returns A new `RequestContext` object.
|
|
81
|
+
*/
|
|
82
|
+
createRequestContext(additionalContext?: Record<string, unknown>): RequestContext;
|
|
83
|
+
};
|